Module: ActiveRecord::ConnectionAdapters::CockroachDB::Quoting

Included in:
ActiveRecord::ConnectionAdapters::CockroachDBAdapter
Defined in:
lib/active_record/connection_adapters/cockroachdb/quoting.rb

Instance Method Summary collapse

Instance Method Details

#lookup_cast_type(sql_type) ⇒ Object

NOTE: This method should be private in future rails versions. Hence we should also make it private then.

See https://github.com/rails/rails/blob/v8.1.1/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb#L190



67
68
69
70
71
72
73
74
75
76
# File 'lib/active_record/connection_adapters/cockroachdb/quoting.rb', line 67

def lookup_cast_type(sql_type)
  type_map.lookup(
    # oid
    query_value("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").to_i,
    # fmod, not needed.
    nil,
    # details needed for `..::CockroachDB::OID::Spatial` (e.g. `geometry(point,3857)`)
    sql_type
  )
end

#quote(value) ⇒ Object

CockroachDB does not allow inserting integer values into string columns, but ActiveRecord expects this to work. CockroachDB will however allow inserting string values into integer columns. It will try to parse string values and convert them to integers so they can be inserted in integer columns.

We take advantage of this behavior here by forcing numeric values to always be strings. Then, we won't have to make any additional changes to ActiveRecord to support inserting integer values into string columns.

For spatial types, data is stored as Well-known Binary (WKB) strings (https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary) but when creating objects, using RGeo features is more convenient than converting to WKB, so this does it automatically.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/active_record/connection_adapters/cockroachdb/quoting.rb', line 36

def quote(value)
  case value
  when Numeric
    # NOTE: The fact that integers are quoted is important and helps
    # mitigate a potential vulnerability.
    #
    # See
    # - https://nvd.nist.gov/vuln/detail/CVE-2022-44566
    # - https://github.com/cockroachdb/activerecord-cockroachdb-adapter/pull/280#discussion_r1288692977
    "'#{quote_string(value.to_s)}'"
  when RGeo::Feature::Geometry
    "'#{RGeo::WKRep::WKBGenerator.new(hex_format: true, type_format: :ewkb, emit_ewkb_srid: true).generate(value)}'"
  when RGeo::Cartesian::BoundingBox
    "'#{value.min_x},#{value.min_y},#{value.max_x},#{value.max_y}'::box"
  else
    super
  end
end

#quoted_date(value) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/active_record/connection_adapters/cockroachdb/quoting.rb', line 55

def quoted_date(value)
  # CockroachDB differs from PostgreSQL in its representation of
  # a `timestamp with timezone`, it does not always include the
  # timezone offset (e.g. `+00`), so we need to add it here.
  # This is tested by `BasicsTest#test_default_in_local_time`.
  super + value.strftime("%z")
end