class Sequel::Postgres::JSONBaseOp

The JSONBaseOp class is a simple container for a single object that defines methods that yield Sequel expression objects representing PostgreSQL json operators and functions.

In the method documentation examples, assume that:

json_op = Sequel.pg_json(:json)

Constants

EMPTY_STRING
GET
GET_PATH
GET_PATH_TEXT
GET_TEXT
IS_JSON
IS_JSON_MAP
IS_NOT_JSON
WITH_UNIQUE

Public Instance Methods

[](key) click to toggle source

Get JSON array element or object field as json. If an array is given, gets the object at the specified path.

json_op[1] # (json -> 1)
json_op['a'] # (json -> 'a')
json_op[%w'a b'] # (json #> ARRAY['a', 'b'])
    # File lib/sequel/extensions/pg_json_ops.rb
215 def [](key)
216   if is_array?(key)
217     json_op(GET_PATH, wrap_array(key))
218   else
219     json_op(GET, key)
220   end
221 end
Also aliased as: get
array_elements() click to toggle source

Returns a set of json values for the elements in the json array.

json_op.array_elements # json_array_elements(json)
    # File lib/sequel/extensions/pg_json_ops.rb
227 def array_elements
228   function(:array_elements)
229 end
array_elements_text() click to toggle source

Returns a set of text values for the elements in the json array.

json_op.array_elements_text # json_array_elements_text(json)
    # File lib/sequel/extensions/pg_json_ops.rb
234 def array_elements_text
235   function(:array_elements_text)
236 end
array_length() click to toggle source

Get the length of the outermost json array.

json_op.array_length # json_array_length(json)
    # File lib/sequel/extensions/pg_json_ops.rb
241 def array_length
242   Sequel::SQL::NumericExpression.new(:NOOP, function(:array_length))
243 end
each() click to toggle source

Returns a set of key and value pairs, where the keys are text and the values are JSON.

json_op.each # json_each(json)
    # File lib/sequel/extensions/pg_json_ops.rb
249 def each
250   function(:each)
251 end
each_text() click to toggle source

Returns a set of key and value pairs, where the keys and values are both text.

json_op.each_text # json_each_text(json)
    # File lib/sequel/extensions/pg_json_ops.rb
257 def each_text
258   function(:each_text)
259 end
exists(path, opts=OPTS) click to toggle source

Return whether the given JSON path yields any items in the receiver. Options:

:on_error

How to handle errors when evaluating the JSON path expression.

true

Return true

false

Return false (default behavior)

:null

Return nil

:error

raise a DatabaseError

:passing

Variables to pass to the JSON path expression. Keys are variable names, values are the values of the variable.

json_op.exists("$.a") # json_exists(json, '$.a')
json_op.exists("$.a", passing: {a: 1}) # json_exists(json, '$.a' PASSING 1 AS a)
json_op.exists("$.a", on_error: :error) # json_exists(json, '$.a' ERROR ON ERROR)
    # File lib/sequel/extensions/pg_json_ops.rb
275 def exists(path, opts=OPTS)
276   Sequel::SQL::BooleanExpression.new(:NOOP, JSONExistsOp.new(self, path, opts))
277 end
extract(*a) click to toggle source

Returns a JSON value for the object at the given path.

json_op.extract('a') # json_extract_path(json, 'a')
json_op.extract('a', 'b') # json_extract_path(json, 'a', 'b')
    # File lib/sequel/extensions/pg_json_ops.rb
283 def extract(*a)
284   self.class.new(function(:extract_path, *a))
285 end
extract_text(*a) click to toggle source

Returns a text value for the object at the given path.

json_op.extract_text('a') # json_extract_path_text(json, 'a')
json_op.extract_text('a', 'b') # json_extract_path_text(json, 'a', 'b')
    # File lib/sequel/extensions/pg_json_ops.rb
291 def extract_text(*a)
292   Sequel::SQL::StringExpression.new(:NOOP, function(:extract_path_text, *a))
293 end
get(key)
Alias for: []
get_text(key) click to toggle source

Get JSON array element or object field as text. If an array is given, gets the object at the specified path.

json_op.get_text(1) # (json ->> 1)
json_op.get_text('a') # (json ->> 'a')
json_op.get_text(%w'a b') # (json #>> ARRAY['a', 'b'])
    # File lib/sequel/extensions/pg_json_ops.rb
301 def get_text(key)
302   if is_array?(key)
303     json_op(GET_PATH_TEXT, wrap_array(key))
304   else
305     json_op(GET_TEXT, key)
306   end
307 end
is_json(opts=OPTS) click to toggle source

Return whether the json object can be parsed as JSON.

Options:

:type

Check whether the json object can be parsed as a specific type of JSON (:value, :scalar, :object, :array).

:unique

Check JSON objects for unique keys.

json_op.is_json                 # json IS JSON
json_op.is_json(type: :object)  # json IS JSON OBJECT
json_op.is_json(unique: true)   # json IS JSON WITH UNIQUE
    # File lib/sequel/extensions/pg_json_ops.rb
319 def is_json(opts=OPTS)
320   _is_json(IS_JSON, opts)
321 end
is_not_json(opts=OPTS) click to toggle source

Return whether the json object cannot be parsed as JSON. The opposite of is_json. See is_json for options.

json_op.is_not_json                 # json IS NOT JSON
json_op.is_not_json(type: :object)  # json IS NOT JSON OBJECT
json_op.is_not_json(unique: true)   # json IS NOT JSON WITH UNIQUE
    # File lib/sequel/extensions/pg_json_ops.rb
329 def is_not_json(opts=OPTS)
330   _is_json(IS_NOT_JSON, opts)
331 end
keys() click to toggle source

Returns a set of keys AS text in the json object.

json_op.keys # json_object_keys(json)
    # File lib/sequel/extensions/pg_json_ops.rb
336 def keys
337   function(:object_keys)
338 end
populate(arg) click to toggle source

Expands the given argument using the columns in the json.

json_op.populate(arg) # json_populate_record(arg, json)
    # File lib/sequel/extensions/pg_json_ops.rb
343 def populate(arg)
344   SQL::Function.new(function_name(:populate_record), arg, self)
345 end
populate_set(arg) click to toggle source

Expands the given argument using the columns in the json.

json_op.populate_set(arg) # json_populate_recordset(arg, json)
    # File lib/sequel/extensions/pg_json_ops.rb
350 def populate_set(arg)
351   SQL::Function.new(function_name(:populate_recordset), arg, self)
352 end
query(path, opts=OPTS) click to toggle source

Return the result of applying the JSON path expression to the receiver, by default returning results as jsonb. Options:

:on_empty

How to handle case where path expression yields an empty set. Uses same values as :on_error option.

:on_error

How to handle errors when evaluating the JSON path expression:

:null

Return nil (default)

:empty_array

Return an empty array

:empty_object

Return an empty object

:error

raise a DatabaseError

any other value

used as default value

:passing

Variables to pass to the JSON path expression. Keys are variable names, values are the values of the variable.

:returning

The data type to return (jsonb by default)

:wrapper

How to wrap returned values:

true, :unconditional

Always wrap returning values in an array

:conditional

Only wrap multiple return values in an array

:omit_quotes

Do not wrap scalar strings in quotes

json_op.query("$.a") # json_query(json, '$.a')
json_op.query("$.a", passing: {a: 1}) # json_query(json, '$.a' PASSING 1 AS a)
json_op.query("$.a", on_error: :empty_array) # json_query(json, '$.a' EMPTY ARRAY ON ERROR)
json_op.query("$.a", returning: Time) # json_query(json, '$.a' RETURNING timestamp)
json_op.query("$.a", on_empty: 2) # json_query(json, '$.a' DEFAULT 2 ON EMPTY)
json_op.query("$.a", wrapper: true) # json_query(json, '$.a' WITH WRAPPER)
    # File lib/sequel/extensions/pg_json_ops.rb
379 def query(path, opts=OPTS)
380   self.class.new(JSONQueryOp.new(self, path, opts))
381 end
strip_nulls() click to toggle source

Returns a json value stripped of all internal null values.

json_op.strip_nulls # json_strip_nulls(json)
    # File lib/sequel/extensions/pg_json_ops.rb
386 def strip_nulls
387   self.class.new(function(:strip_nulls))
388 end
table(path, opts=OPTS, &block) click to toggle source

Returns json_table SQL function expression, querying JSON data and returning the results as a relational view, which can be accessed similarly to a regular SQL table. This accepts a block that is handled in a similar manner to Database#create_table, though it operates differently.

Table level options:

:on_error

How to handle errors when evaluating the JSON path expression.

:empty_array

Return an empty array/result set

:error

raise a DatabaseError

:passing

Variables to pass to the JSON path expression. Keys are variable names, values are the values of the variable.

Inside the block, the following methods can be used:

ordinality(name)

Include a FOR ORDINALITY column, which operates similar to an autoincrementing primary key.

column(name, type, opts={})

Return a normal column that uses the given type.

exists(name, type, opts={})

Return a boolean column for whether the JSON path yields any values.

nested(path, &block)

Extract nested data from the result set at the given path. This block is treated the same as a json_table block, and arbitrary levels of nesting are supported.

The column method supports the following options:

:path

JSON path to the object (the default is $.NAME, where NAME is the name of the column).

:format

Set to :json to use FORMAT JSON, when you expect the value to be a valid JSON object.

:on_empty, :on_error

How to handle case where JSON path evaluation is empty or results in an error. Values supported are:

:empty_array

Return empty array (requires format: :json)

:empty_object

Return empty object (requires format: :json)

:error

Raise a DatabaseError

:null

Return nil (NULL)

:wrapper

How to wrap returned values:

true, :unconditional

Always wrap returning values in an array

:conditional

Only wrap multiple return values in an array

:keep_quotes

Wrap scalar strings in quotes

:omit_quotes

Do not wrap scalar strings in quotes

The exists method supports the following options:

:path

JSON path to the object (same as column option)

:on_error

How to handle case where JSON path evaluation results in an error. Values supported are:

:error

Raise a DatabaseError

true

Return true

false

Return false

:null

Return nil (NULL)

Inside the block, methods for Ruby class names are also supported, allowing you to use syntax such as:

json_op.table('$.a') do
  String :b
  Integer :c, path: '$.d'
end

One difference between this method and Database#create_table is that method_missing is not supported inside the block. Use the column method for PostgreSQL types that are not mapped to Ruby classes.

    # File lib/sequel/extensions/pg_json_ops.rb
452 def table(path, opts=OPTS, &block)
453   JSONTableOp.new(self, path, opts, &block)
454 end
to_record() click to toggle source

Builds arbitrary record from json object. You need to define the structure of the record using as on the resulting object:

json_op.to_record.as(:x, [Sequel.lit('a integer'), Sequel.lit('b text')]) # json_to_record(json) AS x(a integer, b text)
    # File lib/sequel/extensions/pg_json_ops.rb
460 def to_record
461   function(:to_record)
462 end
to_recordset() click to toggle source

Builds arbitrary set of records from json array of objects. You need to define the structure of the records using as on the resulting object:

json_op.to_recordset.as(:x, [Sequel.lit('a integer'), Sequel.lit('b text')]) # json_to_recordset(json) AS x(a integer, b text)
    # File lib/sequel/extensions/pg_json_ops.rb
468 def to_recordset
469   function(:to_recordset)
470 end
typeof() click to toggle source

Returns the type of the outermost json value as text.

json_op.typeof # json_typeof(json)
    # File lib/sequel/extensions/pg_json_ops.rb
475 def typeof
476   function(:typeof)
477 end
value(path=(no_args_given = true), opts=OPTS) click to toggle source

If called without arguments, operates as SQL::Wrapper#value. Otherwise, return the result of applying the JSON path expression to the receiver, by default returning results as text. Options:

:on_empty

How to handle case where path expression yields an empty set. Uses same values as :on_error option.

:on_error

How to handle errors when evaluating the JSON path expression.

:null

Return nil (default)

:error

raise a DatabaseError

any other value

used as default value

:passing

Variables to pass to the JSON path expression. Keys are variable names, values are the values of the variable.

:returning

The data type to return (text by default)

json_op.value("$.a") # json_value(json, '$.a')
json_op.value("$.a", passing: {a: 1}) # json_value(json, '$.a' PASSING 1 AS a)
json_op.value("$.a", on_error: :error) # json_value(json, '$.a' ERROR ON ERROR)
json_op.value("$.a", returning: Time) # json_value(json, '$.a' RETURNING timestamp)
json_op.value("$.a", on_empty: 2) # json_value(json, '$.a' DEFAULT 2 ON EMPTY)
Calls superclass method
    # File lib/sequel/extensions/pg_json_ops.rb
498 def value(path=(no_args_given = true), opts=OPTS)
499   if no_args_given
500     # Act as SQL::Wrapper#value
501     super()
502   else
503     Sequel::SQL::StringExpression.new(:NOOP, JSONValueOp.new(self, path, opts))
504   end
505 end

Private Instance Methods

_is_json(lit_array, opts) click to toggle source

Internals of IS [NOT] JSON support

    # File lib/sequel/extensions/pg_json_ops.rb
510 def _is_json(lit_array, opts)
511   raise Error, "invalid is_json :type option: #{opts[:type].inspect}" unless type = IS_JSON_MAP[opts[:type]]
512   unique = opts[:unique] ? WITH_UNIQUE : EMPTY_STRING
513   Sequel::SQL::BooleanExpression.new(:NOOP, Sequel::SQL::PlaceholderLiteralString.new(lit_array, [self, type, unique]))
514 end
function(name, *args) click to toggle source

Return a function with the given name, and the receiver as the first argument, with any additional arguments given.

    # File lib/sequel/extensions/pg_json_ops.rb
524 def function(name, *args)
525   SQL::Function.new(function_name(name), self, *args)
526 end
is_array?(a) click to toggle source

Whether the given object represents an array in PostgreSQL.

    # File lib/sequel/extensions/pg_json_ops.rb
529 def is_array?(a)
530   a.is_a?(Array) || (defined?(PGArray) && a.is_a?(PGArray)) || (defined?(ArrayOp) && a.is_a?(ArrayOp))
531 end
json_op(str, args) click to toggle source

Return a placeholder literal with the given str and args, wrapped in an JSONOp or JSONBOp, used by operators that return json or jsonb.

    # File lib/sequel/extensions/pg_json_ops.rb
518 def json_op(str, args)
519   self.class.new(Sequel::SQL::PlaceholderLiteralString.new(str, [self, args]))
520 end
wrap_array(arg) click to toggle source

Automatically wrap argument in a PGArray if it is a plain Array. Requires that the pg_array extension has been loaded to work.

    # File lib/sequel/extensions/pg_json_ops.rb
535 def wrap_array(arg)
536   if arg.instance_of?(Array) && Sequel.respond_to?(:pg_array)
537     Sequel.pg_array(arg)
538   else
539     arg
540   end
541 end