Class: ActiveRecord::ConnectionAdapters::SpatiaLiteAdapter::MainAdapter

Inherits:
SQLite3Adapter
  • Object
show all
Defined in:
lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb

Constant Summary collapse

@@native_database_types =
nil

Instance Method Summary collapse

Constructor Details

#initialize(*args_) ⇒ MainAdapter

Returns a new instance of MainAdapter.



52
53
54
55
56
57
58
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 52

def initialize(*args_)
  super
  # Rails 3.2 way of defining the visitor: do so in the constructor
  if defined?(@visitor) && @visitor
    @visitor = ::Arel::Visitors::SpatiaLite.new(self)
  end
end

Instance Method Details

#adapter_nameObject



66
67
68
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 66

def adapter_name
  SpatiaLiteAdapter::ADAPTER_NAME
end

#add_column(table_name_, column_name_, type_, options_ = {}) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 190

def add_column(table_name_, column_name_, type_, options_={})
  if (info_ = spatial_column_constructor(type_.to_sym))
    limit_ = options_[:limit]
    options_.merge!(limit_) if limit_.is_a?(::Hash)
    type_ = (options_[:type] || info_[:type] || type_).to_s.gsub('_', '').upcase
    null_ = options_[:null].nil? ? true : options_[:null]
    execute("SELECT AddGeometryColumn('#{quote_string(table_name_.to_s)}', '#{quote_string(column_name_.to_s)}', #{options_[:srid].to_i}, '#{quote_string(type_.to_s)}', 'XY', #{null_ ? 0 : 1})")
  else
    super
  end
end

#add_index(table_name_, column_name_, options_ = {}) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 203

def add_index(table_name_, column_name_, options_={})
  if options_[:spatial]
    column_name_ = column_name_.first if column_name_.kind_of?(::Array) && column_name_.size == 1
    table_name_ = table_name_.to_s
    column_name_ = column_name_.to_s
    spatial_info_ = spatial_column_info(table_name_)
    unless spatial_info_[column_name_]
      raise ::ArgumentError, "Can't create spatial index because column '#{column_name_}' in table '#{table_name_}' is not a geometry column"
    end
    result_ = select_value("SELECT CreateSpatialIndex('#{quote_string(table_name_)}', '#{quote_string(column_name_)}')").to_i
    if result_ == 0
      raise ::ArgumentError, "Spatial index already exists on table '#{table_name_}', column '#{column_name_}'"
    end
    result_
  else
    super
  end
end

#columns(table_name_, name_ = nil) ⇒ Object

:nodoc:



132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 132

def columns(table_name_, name_=nil)  #:nodoc:
  spatial_info_ = spatial_column_info(table_name_)
  table_structure(table_name_).map do |field_|
    col_ = SpatialColumn.new(@rgeo_factory_settings, table_name_.to_s, field_['name'],
      field_['dflt_value'], field_['type'], field_['notnull'].to_i == 0)
    info_ = spatial_info_[field_['name']]
    if info_
      col_.set_srid(info_[:srid])
    end
    col_
  end
end

#create_table(table_name_, options_ = {}) {|table_definition_| ... } ⇒ Object

Yields:

  • (table_definition_)


159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 159

def create_table(table_name_, options_={})
  table_name_ = table_name_.to_s
  table_definition_ = SpatialTableDefinition.new(self)
  table_definition_.primary_key(options_[:primary_key] || ::ActiveRecord::Base.get_primary_key(table_name_.singularize)) unless options_[:id] == false
  yield table_definition_ if block_given?
  if options_[:force] && table_exists?(table_name_)
    drop_table(table_name_, options_)
  end

  create_sql_ = "CREATE#{' TEMPORARY' if options_[:temporary]} TABLE "
  create_sql_ << "#{quote_table_name(table_name_)} ("
  create_sql_ << table_definition_.to_sql
  create_sql_ << ") #{options_[:options]}"
  execute create_sql_

  table_definition_.spatial_columns.each do |col_|
    null_ = col_.null.nil? ? true : col_.null
    execute("SELECT AddGeometryColumn('#{quote_string(table_name_)}', '#{quote_string(col_.name.to_s)}', #{col_.srid}, '#{quote_string(col_.spatial_type.gsub('_','').upcase)}', 'XY', #{null_ ? 0 : 1})")
  end
end

#drop_table(table_name_, *options_) ⇒ Object



181
182
183
184
185
186
187
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 181

def drop_table(table_name_, *options_)
  indexes(table_name_).each do |index_|
    remove_index(table_name_, :spatial => true, :column => index_.columns[0]) if index_.spatial
  end
  execute("DELETE from geometry_columns where f_table_name='#{quote_string(table_name_.to_s)}'")
  super
end

#exec_query(sql_, name_ = nil, binds_ = []) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 118

def exec_query(sql_, name_=nil, binds_=[])
  real_binds_ = []
  binds_.each do |bind_|
    if bind_[0].spatial?
      real_binds_ << bind_
      real_binds_ << [bind_[0], bind_[1] ? bind_[1].srid : nil]
    else
      real_binds_ << bind_
    end
  end
  super(sql_, name_, real_binds_)
end

#indexes(table_name_, name_ = nil) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 146

def indexes(table_name_, name_=nil)
  results_ = super.map do |index_|
    ::RGeo::ActiveRecord::SpatialIndexDefinition.new(index_.table, index_.name, index_.unique, index_.columns, index_.lengths)
  end
  table_name_ = table_name_.to_s
  names_ = select_values("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'idx_#{quote_string(table_name_)}_%' AND rootpage=0") || []
  results_ + names_.map do |n_|
    col_name_ = n_.sub("idx_#{table_name_}_", '')
    ::RGeo::ActiveRecord::SpatialIndexDefinition.new(table_name_, n_, false, [col_name_], [], true)
  end
end

#native_database_typesObject



76
77
78
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 76

def native_database_types
  @@native_database_types ||= super.merge(:spatial => {:name => 'geometry'})
end

#quote(value_, column_ = nil) ⇒ Object



91
92
93
94
95
96
97
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 91

def quote(value_, column_=nil)
  if ::RGeo::Feature::Geometry.check_type(value_)
    "GeomFromWKB(X'#{::RGeo::WKRep::WKBGenerator.new(:hex_format => true).generate(value_)}', #{value_.srid})"
  else
    super
  end
end

#remove_index(table_name_, options_ = {}) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 223

def remove_index(table_name_, options_={})
  if options_[:spatial]
    table_name_ = table_name_.to_s
    column_ = options_[:column]
    if column_
      column_ = column_[0] if column_.kind_of?(::Array)
      column_ = column_.to_s
    else
      index_name_ = options_[:name]
      unless index_name_
        raise ::ArgumentError, "You need to specify a column or index name to remove a spatial index."
      end
      if index_name_ =~ /^idx_#{table_name_}_(\w+)$/
        column_ = $1
      else
        raise ::ArgumentError, "Unknown spatial index name: #{index_name_.inspect}."
      end
    end
    spatial_info_ = spatial_column_info(table_name_)
    unless spatial_info_[column_]
      raise ::ArgumentError, "Can't remove spatial index because column '#{column_}' in table '#{table_name_}' is not a geometry column"
    end
    index_name_ = "idx_#{table_name_}_#{column_}"
    has_index_ = select_value("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='#{quote_string(index_name_)}'").to_i > 0
    unless has_index_
      raise ::ArgumentError, "Spatial index not present on table '#{table_name_}', column '#{column_}'"
    end
    execute("SELECT DisableSpatialIndex('#{quote_string(table_name_)}', '#{quote_string(column_)}')")
    execute("DROP TABLE #{quote_table_name(index_name_)}")
  else
    super
  end
end

#set_rgeo_factory_settings(factory_settings_) ⇒ Object



61
62
63
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 61

def set_rgeo_factory_settings(factory_settings_)
  @rgeo_factory_settings = factory_settings_
end

#spatial_column_constructor(name_) ⇒ Object



71
72
73
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 71

def spatial_column_constructor(name_)
  ::RGeo::ActiveRecord::DEFAULT_SPATIAL_COLUMN_CONSTRUCTORS[name_]
end

#spatial_column_info(table_name_) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 258

def spatial_column_info(table_name_)
  info_ = execute("SELECT * FROM geometry_columns WHERE f_table_name='#{quote_string(table_name_.to_s)}'")
  result_ = {}
  info_.each do |row_|
    result_[row_['f_geometry_column']] = {
      :name => row_['f_geometry_column'],
      :type => row_['type'],
      :dimension => row_['coord_dimension'],
      :srid => row_['srid'],
      :has_index => row_['spatial_index_enabled'],
    }
  end
  result_
end

#spatialite_versionObject



81
82
83
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 81

def spatialite_version
  @spatialite_version ||= SQLiteAdapter::Version.new(select_value('SELECT spatialite_version()'))
end

#srs_database_columnsObject



86
87
88
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 86

def srs_database_columns
  {:name_column => 'ref_sys_name', :proj4text_column => 'proj4text', :auth_name_column => 'auth_name', :auth_srid_column => 'auth_srid'}
end

#substitute_at(column_, index_) ⇒ Object



100
101
102
103
104
105
106
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 100

def substitute_at(column_, index_)
  if column_.spatial?
    ::Arel.sql('GeomFromText(?,?)')
  else
    super
  end
end

#type_cast(value_, column_) ⇒ Object



109
110
111
112
113
114
115
# File 'lib/active_record/connection_adapters/spatialite_adapter/main_adapter.rb', line 109

def type_cast(value_, column_)
  if column_.spatial? && ::RGeo::Feature::Geometry.check_type(value_)
    ::RGeo::WKRep::WKTGenerator.new(:convert_case => :upper).generate(value_)
  else
    super
  end
end