Module: RGeo::ActiveRecord::SpatialToSql

Defined in:
lib/rgeo/active_record/arel_spatial_queries.rb

Overview

A set of common Arel visitor hacks for spatial ToSql visitors. Generally, a spatial ActiveRecord adapter should provide a custom ToSql Arel visitor that includes and customizes this module. See the existing spatial adapters (i.e. postgis, spatialite, mysqlspatial, and mysql2spatial) for usage examples.

Instance Method Summary collapse

Instance Method Details

#st_func(standard_name) ⇒ Object

Map a standard OGC SQL function name to the actual name used by a particular database. This method should take a name and return either the changed name or the original name.



16
17
18
# File 'lib/rgeo/active_record/arel_spatial_queries.rb', line 16

def st_func(standard_name)
  standard_name
end

#visit_in_spatial_context(node, collector) ⇒ Object

Generates SQL for a spatial node. The node must be a string (in which case it is treated as WKT), an RGeo feature, or a spatial attribute.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rgeo/active_record/arel_spatial_queries.rb', line 45

def visit_in_spatial_context(node, collector)
  if node.is_a?(String)
    collector << "#{st_func('ST_GeomFromText')}(#{quote(node)})"
  elsif node.is_a?(RGeo::Feature::Instance)
    srid = node.srid
    collector << "#{st_func('ST_GeomFromText')}(#{quote(node.to_s)}, #{srid})"
  elsif node.is_a?(RGeo::Cartesian::BoundingBox)
    geom = node.to_geometry
    srid = geom.srid
    collector << "#{st_func('ST_GeomFromText')}(#{quote(geom.to_s)}, #{srid})"
  else
    visit(node, collector)
  end
end

#visit_RGeo_ActiveRecord_SpatialNamedFunction(node, collector) ⇒ Object

Visit the SpatialNamedFunction node. This operates similarly to the standard NamedFunction node, but it performs function name mapping for the database, and it also uses the type information in the node to determine when to cast string arguments to WKT,



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rgeo/active_record/arel_spatial_queries.rb', line 25

def visit_RGeo_ActiveRecord_SpatialNamedFunction(node, collector)
  name = st_func(node.name)
  collector << name
  collector << "("
  collector << "DISTINCT " if node.distinct
  node.expressions.each_with_index do |expr, index|
    node.spatial_argument?(index) ? visit_in_spatial_context(expr, collector) : visit(expr, collector)
    collector << ", " unless index == node.expressions.size - 1
  end
  collector << ")"
  if node.alias
    collector << " AS "
    visit node.alias, collector
  end
  collector
end