Methods enabling Database object integration with the json type.
Parse JSON data coming from the database. Since PostgreSQL allows non JSON data in JSON fields (such as plain numbers and strings), we don't want to raise an exception for that.
# File lib/sequel/extensions/pg_json.rb, line 106 def self.db_parse_json(s) parse_json(s) rescue Sequel::InvalidValue raise unless s.is_a?(String) parse_json("[#{s}]").first end
# File lib/sequel/extensions/pg_json.rb, line 96 def self.extended(db) db.instance_eval do copy_conversion_procs([114, 199]) @schema_type_classes[:json] = [JSONHash, JSONArray] end end
Parse the given string as json, returning either a JSONArray or JSONHash instance, and raising an error if the JSON parsing does not yield an array or hash.
# File lib/sequel/extensions/pg_json.rb, line 116 def self.parse_json(s) begin value = Sequel.parse_json(s) rescue Sequel.json_parser_error_class => e raise Sequel.convert_exception_class(e, Sequel::InvalidValue) end case value when Array JSONArray.new(value) when Hash JSONHash.new(value) else raise Sequel::InvalidValue, "unhandled json value: #{value.inspect} (from #{s.inspect})" end end
Handle json[] types in bound variables.
# File lib/sequel/extensions/pg_json.rb, line 146 def bound_variable_array(a) case a when JSONHash, JSONArray "\"#{Sequel.object_to_json(a).gsub('"', '\\"')}\"" else super end end
Make the column type detection recognize the json type.
# File lib/sequel/extensions/pg_json.rb, line 156 def schema_column_type(db_type) case db_type when 'json' :json else super end end
Given a value to typecast to the json column
If given a String, parse it as would be done during database retrieval.
# File lib/sequel/extensions/pg_json.rb, line 171 def typecast_value_json(value) case value when JSONArray, JSONHash value when Array JSONArray.new(value) when Hash JSONHash.new(value) when String JSONDatabaseMethods.parse_json(value) else raise Sequel::InvalidValue, "invalid value for json: #{value.inspect}" end end