Module: LcpRuby::Metrics::JsonQuery

Defined in:
lib/lcp_ruby/metrics/json_query.rb

Overview

Portable JSON column queries for error log context field. Follows the same pattern as CustomFields::Query.

Constant Summary collapse

VALID_KEY =
/\A[a-z][a-z0-9_]*\z/

Class Method Summary collapse

Class Method Details

.extract(table_name, column, key) ⇒ String

Build a JSON extraction expression for a column.

Parameters:

  • table_name (String)
  • column (String)

    the JSON column name

  • key (String)

    the JSON key to extract

Returns:

  • (String)

    SQL expression



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/lcp_ruby/metrics/json_query.rb', line 13

def self.extract(table_name, column, key)
  validate_key!(key)
  conn = ActiveRecord::Base.connection
  quoted_table = conn.quote_table_name(table_name)
  quoted_column = conn.quote_column_name(column)

  if LcpRuby.postgresql?
    "#{quoted_table}.#{quoted_column} ->> #{conn.quote(key)}"
  else
    "JSON_EXTRACT(#{quoted_table}.#{quoted_column}, #{conn.quote("$.#{key}")})"
  end
end

.where_eq(scope, table_name, column, key, value) ⇒ ActiveRecord::Relation

Apply an exact match filter on a JSON column key.

Parameters:

  • scope (ActiveRecord::Relation)
  • table_name (String)
  • column (String)
  • key (String)
  • value (Object)

Returns:

  • (ActiveRecord::Relation)


33
34
35
36
37
# File 'lib/lcp_ruby/metrics/json_query.rb', line 33

def self.where_eq(scope, table_name, column, key, value)
  expr = extract(table_name, column, key)
  conn = ActiveRecord::Base.connection
  scope.where(Arel.sql("#{expr} = #{conn.quote(value.to_s)}"))
end