module Sequel::Postgres::JSONDatabaseMethods

Methods enabling Database object integration with the json type.

Public Class Methods

extended(db) click to toggle source
# 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_json(s) click to toggle source

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 106
def self.parse_json(s)
  begin
    value = Sequel.parse_json(s)
  rescue JSON::ParserError=>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

Public Instance Methods

bound_variable_arg(arg, conn) click to toggle source

Handle JSONArray and JSONHash in bound variables

Calls superclass method
# File lib/sequel/extensions/pg_json.rb, line 124
def bound_variable_arg(arg, conn)
  case arg
  when JSONArray, JSONHash
    arg.to_json
  else
    super
  end
end

Private Instance Methods

bound_variable_array(a) click to toggle source

Handle json[] types in bound variables.

Calls superclass method
# File lib/sequel/extensions/pg_json.rb, line 136
def bound_variable_array(a)
  case a
  when JSONHash, JSONArray
    "\"#{a.to_json.gsub('"', '\\"')}\""
  else
    super
  end
end
schema_column_type(db_type) click to toggle source

Make the column type detection recognize the json type.

Calls superclass method
# File lib/sequel/extensions/pg_json.rb, line 146
def schema_column_type(db_type)
  case db_type
  when 'json'
    :json
  else
    super
  end
end
typecast_value_json(value) click to toggle source

Given a value to typecast to the json column

# File lib/sequel/extensions/pg_json.rb, line 161
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