Class: ActiveRecord::Refined::AST::JsonHasKey

Inherits:
Predicate show all
Defined in:
lib/active_record/refined/ast.rb

Overview

Whether a key is in the document. PostgreSQL's spelling is the ? operator rather than jsonb_exists, the function it is shorthand for, because a GIN index matches the operator and never the function. A ? is a bind placeholder only to sanitize_sql, which none of the SQL written here passes through.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Predicate

#!, #&, #|

Methods inherited from Node

#as, #asc, #desc

Constructor Details

#initialize(operand, key) ⇒ JsonHasKey

Returns a new instance of JsonHasKey.



1038
1039
1040
1041
# File 'lib/active_record/refined/ast.rb', line 1038

def initialize(operand, key)
  @operand = operand
  @key = key
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



1036
1037
1038
# File 'lib/active_record/refined/ast.rb', line 1036

def key
  @key
end

#operandObject (readonly)

Returns the value of attribute operand.



1036
1037
1038
# File 'lib/active_record/refined/ast.rb', line 1036

def operand
  @operand
end

Instance Method Details

#to_arel(table, model) ⇒ Object



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
# File 'lib/active_record/refined/ast.rb', line 1043

def to_arel(table, model)
  document = to_arel_operand(operand, table, model)
  name = Arel::Nodes.build_quoted(key.to_s)
  path = Arel::Nodes.build_quoted("$.#{key}")
  case AST.adapter_family(model)
  when :postgresql
    Arel::Nodes::InfixOperation.new(:"?", document, name)
  when :mysql
    Arel::Nodes::NamedFunction.new(
      "JSON_CONTAINS_PATH", [document, Arel::Nodes.build_quoted("one"), path])
  else
    Arel::Nodes::NamedFunction.new("json_type", [document, path]).not_eq(nil)
  end
end