activerecord-postgis-adapter 0.6.6 → 0.7.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (33) hide show
  1. checksums.yaml +4 -4
  2. data/History.rdoc +7 -0
  3. data/{lib/rgeo/active_record/postgis_adapter/railtie.rb → LICENSE.txt} +2 -12
  4. data/lib/active_record/connection_adapters/postgis_adapter.rb +1 -60
  5. data/lib/active_record/connection_adapters/postgis_adapter/rails4/create_connection.rb +15 -74
  6. data/lib/active_record/connection_adapters/postgis_adapter/rails4/databases.rake +0 -38
  7. data/lib/active_record/connection_adapters/postgis_adapter/rails4/main_adapter.rb +0 -68
  8. data/lib/active_record/connection_adapters/postgis_adapter/rails4/postgis_database_tasks.rb +0 -36
  9. data/lib/active_record/connection_adapters/postgis_adapter/rails4/spatial_column.rb +0 -36
  10. data/lib/active_record/connection_adapters/postgis_adapter/rails4/spatial_table_definition.rb +0 -36
  11. data/lib/active_record/connection_adapters/postgis_adapter/railtie.rb +0 -36
  12. data/lib/active_record/connection_adapters/postgis_adapter/shared/arel_tosql.rb +0 -36
  13. data/lib/active_record/connection_adapters/postgis_adapter/shared/common_adapter_methods.rb +3 -70
  14. data/lib/active_record/connection_adapters/postgis_adapter/shared/railtie.rb +1 -54
  15. data/lib/active_record/connection_adapters/postgis_adapter/shared/setup.rb +0 -36
  16. data/lib/active_record/connection_adapters/postgis_adapter/version.rb +7 -0
  17. data/lib/activerecord-postgis-adapter.rb +0 -36
  18. data/lib/activerecord/postgis/adapter.rb +0 -36
  19. data/test/database.yml +5 -0
  20. data/test/tc_basic.rb +0 -35
  21. data/test/tc_ddl.rb +0 -35
  22. data/test/tc_nested_class.rb +0 -35
  23. data/test/tc_spatial_queries.rb +0 -35
  24. data/test/tc_tasks.rb +0 -78
  25. metadata +33 -38
  26. data/Version +0 -1
  27. data/lib/active_record/connection_adapters/postgis_adapter/rails3/create_connection.rb +0 -96
  28. data/lib/active_record/connection_adapters/postgis_adapter/rails3/databases.rake +0 -232
  29. data/lib/active_record/connection_adapters/postgis_adapter/rails3/main_adapter.rb +0 -298
  30. data/lib/active_record/connection_adapters/postgis_adapter/rails3/spatial_column.rb +0 -195
  31. data/lib/active_record/connection_adapters/postgis_adapter/rails3/spatial_table_definition.rb +0 -145
  32. data/lib/active_record/connection_adapters/postgis_adapter/shared/jdbc_compat.rb +0 -134
  33. data/lib/active_record/connection_adapters/postgis_adapter/shared/version.rb +0 -62
data/Version DELETED
@@ -1 +0,0 @@
1
- 0.6.6
@@ -1,96 +0,0 @@
1
- # -----------------------------------------------------------------------------
2
- #
3
- # PostGIS adapter for ActiveRecord
4
- #
5
- # -----------------------------------------------------------------------------
6
- # Copyright 2010-2012 Daniel Azuma
7
- #
8
- # All rights reserved.
9
- #
10
- # Redistribution and use in source and binary forms, with or without
11
- # modification, are permitted provided that the following conditions are met:
12
- #
13
- # * Redistributions of source code must retain the above copyright notice,
14
- # this list of conditions and the following disclaimer.
15
- # * Redistributions in binary form must reproduce the above copyright notice,
16
- # this list of conditions and the following disclaimer in the documentation
17
- # and/or other materials provided with the distribution.
18
- # * Neither the name of the copyright holder, nor the names of any other
19
- # contributors to this software, may be used to endorse or promote products
20
- # derived from this software without specific prior written permission.
21
- #
22
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23
- # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
- # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
- # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26
- # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27
- # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
- # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
- # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
- # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
- # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
- # POSSIBILITY OF SUCH DAMAGE.
33
- # -----------------------------------------------------------------------------
34
- ;
35
-
36
-
37
- module ActiveRecord # :nodoc:
38
-
39
- class Base # :nodoc:
40
-
41
- class << self
42
-
43
-
44
- if defined?(::RUBY_ENGINE) && ::RUBY_ENGINE == 'jruby'
45
-
46
-
47
- require 'active_record/connection_adapters/jdbcpostgresql_adapter'
48
- require 'active_record/connection_adapters/postgis_adapter/shared/jdbc_compat'
49
-
50
-
51
- def postgis_connection(config_)
52
- ::ActiveRecord::ConnectionAdapters::PostGISAdapter.create_jdbc_connection(self, config_)
53
- end
54
-
55
- alias_method :jdbcpostgis_connection, :postgis_connection
56
-
57
-
58
- else
59
-
60
-
61
- require 'pg'
62
-
63
-
64
- # ActiveRecord looks for the postgis_connection factory method in
65
- # this class.
66
- #
67
- # Based on the default <tt>postgresql_connection</tt> definition from
68
- # ActiveRecord.
69
-
70
- def postgis_connection(config_)
71
- config_ = config_.symbolize_keys
72
- host_ = config_[:host]
73
- port_ = config_[:port] || 5432
74
- username_ = config_[:username].to_s if config_[:username]
75
- password_ = config_[:password].to_s if config_[:password]
76
-
77
- if config_.key?(:database)
78
- database_ = config_[:database]
79
- else
80
- raise ::ArgumentError, "No database specified. Missing argument: database."
81
- end
82
-
83
- # The postgres drivers don't allow the creation of an unconnected PGconn object,
84
- # so just pass a nil connection object for the time being.
85
- ::ActiveRecord::ConnectionAdapters::PostGISAdapter::MainAdapter.new(nil, logger, [host_, port_, nil, nil, database_, username_, password_], config_)
86
- end
87
-
88
-
89
- end
90
-
91
-
92
- end
93
-
94
- end
95
-
96
- end
@@ -1,232 +0,0 @@
1
- # -----------------------------------------------------------------------------
2
- #
3
- # PostGIS adapter for ActiveRecord
4
- #
5
- # -----------------------------------------------------------------------------
6
- # Copyright 2010-2012 Daniel Azuma
7
- #
8
- # All rights reserved.
9
- #
10
- # Redistribution and use in source and binary forms, with or without
11
- # modification, are permitted provided that the following conditions are met:
12
- #
13
- # * Redistributions of source code must retain the above copyright notice,
14
- # this list of conditions and the following disclaimer.
15
- # * Redistributions in binary form must reproduce the above copyright notice,
16
- # this list of conditions and the following disclaimer in the documentation
17
- # and/or other materials provided with the distribution.
18
- # * Neither the name of the copyright holder, nor the names of any other
19
- # contributors to this software, may be used to endorse or promote products
20
- # derived from this software without specific prior written permission.
21
- #
22
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23
- # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
- # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
- # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26
- # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27
- # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
- # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
- # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
- # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
- # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
- # POSSIBILITY OF SUCH DAMAGE.
33
- # -----------------------------------------------------------------------------
34
- ;
35
-
36
-
37
- # :stopdoc:
38
-
39
-
40
- require 'rgeo/active_record/task_hacker'
41
-
42
-
43
- class Object
44
- alias_method :create_database_without_postgis, :create_database
45
- alias_method :drop_database_without_postgis, :drop_database
46
- end
47
-
48
-
49
- namespace :db do
50
- namespace :gis do
51
- desc "Setup PostGIS data in the database"
52
- task :setup => [:load_config, :rails_env] do
53
- if self.respond_to?(:configs_for_environment)
54
- configs_ = configs_for_environment
55
- else
56
- environments_ = [::Rails.env]
57
- environments_ << 'test' if ::Rails.env.development?
58
- configs_ = ::ActiveRecord::Base.configurations.values_at(*environments_).compact.reject{ |config_| config_['database'].blank? }
59
- end
60
- configs_.each { |config_| setup_gis(config_) }
61
- end
62
- end
63
- end
64
-
65
-
66
- # superuser name/password
67
- def get_su_auth(config_)
68
- username_ = config_['username']
69
- su_username_ = config_['su_username'] || username_
70
- su_password_ = config_['su_password'] || config_['password']
71
- has_su_ = config_.include?('su_username')
72
-
73
- [username_, su_username_, su_password_, has_su_]
74
- end
75
-
76
-
77
- def get_search_path(config_)
78
- config_["schema_search_path"].to_s.strip.split(',').map(&:strip)
79
- end
80
-
81
-
82
- # Install postgis definitions into the database.
83
- # Note: a superuser is required to run the postgis definitions.
84
- # If a separate superuser is provided, we need to grant privileges on
85
- # the postgis definitions over to the regular user afterwards.
86
- # We also need to set the ownership of the postgis tables (spatial_ref_sys
87
- # and geometry_columns) to the regular user. This is required to e.g.
88
- # be able to disable referential integrity on the database when using
89
- # a database cleaner truncation strategy during testing.
90
- # The schema for the postgis definitions is chosen as follows:
91
- # If "postgis" is present in the search path, use it.
92
- # Otherwise, use the last schema in the search path.
93
- # If no search path is given, use "public".
94
- def setup_gis(config_)
95
- # Initial setup of the database: Add schemas from the search path.
96
- # If a superuser is given, we log in as the superuser, but we make sure
97
- # the schemas are owned by the regular user.
98
- username_, su_username_, su_password_, has_su_ = get_su_auth(config_)
99
- ::ActiveRecord::Base.establish_connection(config_.merge('schema_search_path' => 'public', 'username' => su_username_, 'password' => su_password_))
100
- conn_ = ::ActiveRecord::Base.connection
101
- search_path_ = get_search_path(config_)
102
- quoted_username_ = ::ActiveRecord::Base.connection.quote_column_name(username_)
103
- auth_ = has_su_ ? " AUTHORIZATION #{quoted_username_}" : ''
104
- search_path_.each do |schema_|
105
- exists = schema_.downcase == 'public' || conn_.execute("SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='#{schema_}'").try(:first)
106
- conn_.execute("CREATE SCHEMA #{schema_}#{auth_}") unless exists
107
- end
108
-
109
- script_dir_ = config_['script_dir']
110
- postgis_extension_ = config_['postgis_extension']
111
- if script_dir_ || postgis_extension_
112
- postgis_schema_ = search_path_.include?('postgis') ? 'postgis' : (search_path_.last || 'public')
113
- if script_dir_
114
- # Use script_dir (for postgresql < 9.1 or postgis < 2.0)
115
- conn_.execute("SET search_path TO #{postgis_schema_}")
116
- conn_.execute(::File.read(::File.expand_path('postgis.sql', script_dir_)))
117
- conn_.execute(::File.read(::File.expand_path('spatial_ref_sys.sql', script_dir_)))
118
- elsif postgis_extension_
119
- # Use postgis_extension (for postgresql >= 9.1 and postgis >= 2.0)
120
- postgis_extension_ = 'postgis' if postgis_extension_ == true
121
- postgis_extension_ = postgis_extension_.to_s.split(',') unless postgis_extension_.is_a?(::Array)
122
- postgis_extension_.each do |extname_|
123
- if extname_ == 'postgis_topology'
124
- raise ArgumentError, "'topology' must be in schema_search_path for postgis_topology" unless search_path_.include?('topology')
125
- conn_.execute("CREATE EXTENSION IF NOT EXISTS #{extname_} SCHEMA topology")
126
- else
127
- conn_.execute("CREATE EXTENSION IF NOT EXISTS #{extname_} SCHEMA #{postgis_schema_}")
128
- end
129
- end
130
- end
131
- if has_su_
132
- conn_.execute("GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA #{postgis_schema_} TO #{quoted_username_}")
133
- conn_.execute("GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA #{postgis_schema_} TO #{quoted_username_}")
134
-
135
- postgis_version = conn_.execute( "SELECT #{postgis_schema_}.postgis_version();" ).first[ 'postgis_version' ]
136
- if postgis_version =~ /^2/
137
- conn_.execute("ALTER VIEW #{postgis_schema_}.geometry_columns OWNER TO #{quoted_username_}")
138
- conn_.execute("ALTER VIEW #{postgis_schema_}.geography_columns OWNER TO #{quoted_username_}")
139
- else
140
- conn_.execute("ALTER TABLE #{postgis_schema_}.geometry_columns OWNER TO #{quoted_username_}")
141
- end
142
- conn_.execute("ALTER TABLE #{postgis_schema_}.spatial_ref_sys OWNER TO #{quoted_username_}")
143
- end
144
- end
145
- end
146
-
147
-
148
- def create_database(config_)
149
- if config_['adapter'] == 'postgis'
150
- @encoding = config_['encoding'] || ::ENV['CHARSET'] || 'utf8'
151
- begin
152
- username_, su_username_, su_password_, has_su_ = get_su_auth(config_)
153
-
154
- # Create the database. Optionally do so as the given superuser.
155
- # But make sure the database is owned by the regular user.
156
- ::ActiveRecord::Base.establish_connection(config_.merge('database' => 'postgres', 'schema_search_path' => 'public', 'username' => su_username_, 'password' => su_password_))
157
- extra_configs_ = {'encoding' => @encoding}
158
- extra_configs_['owner'] = username_ if has_su_
159
- ::ActiveRecord::Base.connection.create_database(config_['database'], config_.merge(extra_configs_))
160
-
161
- setup_gis(config_)
162
-
163
- # Done
164
- ::ActiveRecord::Base.establish_connection(config_)
165
- rescue ::Exception => e_
166
- $stderr.puts(e_, *(e_.backtrace))
167
- $stderr.puts("Couldn't create database for #{config_.inspect}")
168
- end
169
- else
170
- create_database_without_postgis(config_)
171
- end
172
- end
173
-
174
-
175
- def drop_database(config_)
176
- if config_['adapter'] == 'postgis'
177
- ::ActiveRecord::Base.establish_connection(config_.merge('database' => 'postgres', 'schema_search_path' => 'public', 'username' => config_['su_username'] || config_['username'], 'password' => config_['su_password'] || config_['password']))
178
- ::ActiveRecord::Base.connection.drop_database(config_['database'])
179
- else
180
- drop_database_without_postgis(config_)
181
- end
182
- end
183
-
184
-
185
- def set_psql_env(config_)
186
- ::ENV['PGHOST'] = config_["host"] if config_["host"]
187
- ::ENV['PGPORT'] = config_["port"].to_s if config_["port"]
188
- ::ENV['PGPASSWORD'] = config_["password"].to_s if config_["password"]
189
- ::ENV['PGUSER'] = config_["username"].to_s if config_["username"]
190
- end
191
-
192
-
193
- ::RGeo::ActiveRecord::TaskHacker.modify('db:charset', nil, 'postgis') do |config_|
194
- ::ActiveRecord::Base.establish_connection(config_)
195
- puts(::ActiveRecord::Base.connection.encoding)
196
- end
197
-
198
-
199
- ::RGeo::ActiveRecord::TaskHacker.modify('db:structure:dump', nil, 'postgis') do |config_|
200
- set_psql_env(config_)
201
- filename_ = ::File.join(::Rails.root, "db/#{::Rails.env}_structure.sql")
202
- search_path_ = config_["schema_search_path"].to_s.strip
203
- search_path_ = search_path_.split(",").map{ |sp_| sp_.strip }
204
- search_path_.delete('postgis')
205
- search_path_ = ['public'] if search_path_.length == 0
206
- search_path_ = search_path_.map{ |sp_| "--schema=#{sp_}" }.join(" ")
207
- `pg_dump -i -U "#{config_["username"]}" -s -x -O -f #{filename_} #{search_path_} #{config_["database"]}`
208
- raise "Error dumping database" if $?.exitstatus == 1
209
- end
210
-
211
-
212
- ::RGeo::ActiveRecord::TaskHacker.modify('db:structure:load', nil, 'postgis') do |config_|
213
- set_psql_env(config_)
214
- filename_ = ::File.join(::Rails.root, "db/#{::Rails.env}_structure.sql")
215
- `psql -f #{filename_} #{config_["database"]}`
216
- end
217
-
218
-
219
- ::RGeo::ActiveRecord::TaskHacker.modify('db:test:clone_structure', 'test', 'postgis') do |config_|
220
- set_psql_env(config_)
221
- `psql -U "#{config_["username"]}" -f #{::Rails.root}/db/#{::Rails.env}_structure.sql #{config_["database"]}`
222
- end
223
-
224
-
225
- ::RGeo::ActiveRecord::TaskHacker.modify('db:test:purge', 'test', 'postgis') do |config_|
226
- ::ActiveRecord::Base.clear_active_connections!
227
- drop_database(config_)
228
- create_database(config_)
229
- end
230
-
231
-
232
- # :startdoc:
@@ -1,298 +0,0 @@
1
- # -----------------------------------------------------------------------------
2
- #
3
- # PostGIS adapter for ActiveRecord
4
- #
5
- # -----------------------------------------------------------------------------
6
- # Copyright 2010-2012 Daniel Azuma
7
- #
8
- # All rights reserved.
9
- #
10
- # Redistribution and use in source and binary forms, with or without
11
- # modification, are permitted provided that the following conditions are met:
12
- #
13
- # * Redistributions of source code must retain the above copyright notice,
14
- # this list of conditions and the following disclaimer.
15
- # * Redistributions in binary form must reproduce the above copyright notice,
16
- # this list of conditions and the following disclaimer in the documentation
17
- # and/or other materials provided with the distribution.
18
- # * Neither the name of the copyright holder, nor the names of any other
19
- # contributors to this software, may be used to endorse or promote products
20
- # derived from this software without specific prior written permission.
21
- #
22
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23
- # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
- # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25
- # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26
- # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27
- # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
- # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
- # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
- # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
- # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
- # POSSIBILITY OF SUCH DAMAGE.
33
- # -----------------------------------------------------------------------------
34
- ;
35
-
36
-
37
- module ActiveRecord # :nodoc:
38
-
39
- module ConnectionAdapters # :nodoc:
40
-
41
- module PostGISAdapter # :nodoc:
42
-
43
-
44
- class MainAdapter < PostgreSQLAdapter # :nodoc:
45
-
46
-
47
- def initialize(*args_)
48
- super
49
- # Rails 3.2 way of defining the visitor: do so in the constructor
50
- if defined?(@visitor) && @visitor
51
- @visitor = ::Arel::Visitors::PostGIS.new(self)
52
- end
53
- end
54
-
55
-
56
- include PostGISAdapter::CommonAdapterMethods
57
-
58
-
59
- @@native_database_types = nil
60
-
61
- def native_database_types
62
- @@native_database_types ||= super.merge(:spatial => {:name => 'geometry'})
63
- end
64
-
65
-
66
- def type_cast(value_, column_)
67
- if ::RGeo::Feature::Geometry.check_type(value_)
68
- ::RGeo::WKRep::WKBGenerator.new(:hex_format => true, :type_format => :ewkb, :emit_ewkb_srid => true).generate(value_)
69
- else
70
- super
71
- end
72
- end
73
-
74
-
75
- def columns(table_name_, name_=nil)
76
- # FULL REPLACEMENT. RE-CHECK ON NEW VERSIONS.
77
- # We needed to return a spatial column subclass.
78
- table_name_ = table_name_.to_s
79
- spatial_info_ = spatial_column_info(table_name_)
80
- column_definitions(table_name_).collect do |col_name_, type_, default_, notnull_|
81
- # JDBC support: JDBC adapter returns a hash for column definitions,
82
- # instead of an array of values.
83
- if col_name_.kind_of?(::Hash)
84
- notnull_ = col_name_["column_not_null"]
85
- default_ = col_name_["column_default"]
86
- type_ = col_name_["column_type"]
87
- col_name_ = col_name_["column_name"]
88
- end
89
-
90
- SpatialColumn.new(col_name_, default_, type_, notnull_ == 'f',
91
- ((type_ =~ /geometry/i ? spatial_info_[col_name_] : nil) || {}).merge({
92
- :table_name => table_name_,
93
- :factory_settings => @rgeo_factory_settings
94
- }))
95
- end
96
- end
97
-
98
-
99
- def indexes(table_name_, name_=nil)
100
- # FULL REPLACEMENT. RE-CHECK ON NEW VERSIONS.
101
- # We needed to modify the catalog queries to pull the index type info.
102
-
103
- # Remove postgis from schemas
104
- schemas_ = schema_search_path.split(/,/)
105
- schemas_.delete('postgis')
106
- schemas_ = schemas_.map{ |p_| quote(p_) }.join(',')
107
-
108
- # Get index type by joining with pg_am.
109
- result_ = query(<<-SQL, name_)
110
- SELECT DISTINCT i.relname, d.indisunique, d.indkey, t.oid, am.amname
111
- FROM pg_class t, pg_class i, pg_index d, pg_am am
112
- WHERE i.relkind = 'i'
113
- AND d.indexrelid = i.oid
114
- AND d.indisprimary = 'f'
115
- AND t.oid = d.indrelid
116
- AND t.relname = '#{table_name_}'
117
- AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (#{schemas_}) )
118
- AND i.relam = am.oid
119
- ORDER BY i.relname
120
- SQL
121
-
122
- result_.map do |row_|
123
- index_name_ = row_[0]
124
- unique_ = row_[1] == 't'
125
- indkey_ = row_[2].split(" ")
126
- oid_ = row_[3]
127
- indtype_ = row_[4]
128
-
129
- columns_ = query(<<-SQL, "Columns for index #{row_[0]} on #{table_name_}").inject({}){ |h_, r_| h_[r_[0].to_s] = [r_[1], r_[2]]; h_ }
130
- SELECT a.attnum, a.attname, t.typname
131
- FROM pg_attribute a, pg_type t
132
- WHERE a.attrelid = #{oid_}
133
- AND a.attnum IN (#{indkey_.join(",")})
134
- AND a.atttypid = t.oid
135
- SQL
136
-
137
- spatial_ = indtype_ == 'gist' && columns_.size == 1 && (columns_.values.first[1] == 'geometry' || columns_.values.first[1] == 'geography')
138
- column_names_ = columns_.values_at(*indkey_).compact.map{ |a_| a_[0] }
139
- if column_names_.empty?
140
- nil
141
- else
142
- ::RGeo::ActiveRecord::SpatialIndexDefinition.new(table_name_, index_name_, unique_, column_names_, nil, nil, nil, spatial_ ? true : false)
143
- end
144
- end.compact
145
- end
146
-
147
-
148
- def create_table(table_name_, options_={})
149
- # FULL REPLACEMENT. RE-CHECK ON NEW VERSIONS.
150
- # Note: we have to do a full replacement for Rails 3.0 because
151
- # there is no way to override the creation of the table
152
- # definition object. In Rails 3.1, this has been factored out
153
- # into the table_definition method, so we could rewrite this
154
- # to call super if we're willing to go 3.1 only.
155
- table_name_ = table_name_.to_s
156
- table_definition_ = SpatialTableDefinition.new(self)
157
- table_definition_.primary_key(options_[:primary_key] || ::ActiveRecord::Base.get_primary_key(table_name_.singularize)) unless options_[:id] == false
158
- yield table_definition_ if block_given?
159
- if options_[:force] && table_exists?(table_name_)
160
- drop_table(table_name_, options_)
161
- end
162
-
163
- create_sql_ = "CREATE#{' TEMPORARY' if options_[:temporary]} TABLE "
164
- create_sql_ << "#{quote_table_name(table_name_)} ("
165
- create_sql_ << table_definition_.to_sql
166
- create_sql_ << ") #{options_[:options]}"
167
- execute create_sql_
168
-
169
- table_definition_.non_geographic_spatial_columns.each do |col_|
170
- type_ = col_.spatial_type.gsub('_', '').upcase
171
- has_z_ = col_.has_z?
172
- has_m_ = col_.has_m?
173
- type_ = "#{type_}M" if has_m_ && !has_z_
174
- dimensions_ = 2
175
- dimensions_ += 1 if has_z_
176
- dimensions_ += 1 if has_m_
177
- execute("SELECT AddGeometryColumn('#{quote_string(table_name_)}', '#{quote_string(col_.name.to_s)}', #{col_.srid}, '#{quote_string(type_)}', #{dimensions_})")
178
- end
179
- end
180
-
181
-
182
- def drop_table(table_name_, *options_)
183
- if postgis_lib_version.to_s.split('.').first.to_i == 1
184
- execute("DELETE from geometry_columns where f_table_name='#{quote_string(table_name_.to_s)}'")
185
- end
186
- super
187
- end
188
-
189
-
190
- def add_column(table_name_, column_name_, type_, options_={})
191
- table_name_ = table_name_.to_s
192
- if (info_ = spatial_column_constructor(type_.to_sym))
193
- limit_ = options_[:limit]
194
- if type_.to_s == 'geometry' &&
195
- (options_[:no_constraints] || limit_.is_a?(::Hash) && limit_[:no_constraints])
196
- then
197
- options_.delete(:limit)
198
- super
199
- else
200
- options_.merge!(limit_) if limit_.is_a?(::Hash)
201
- type_ = (options_[:type] || info_[:type] || type_).to_s.gsub('_', '').upcase
202
- has_z_ = options_[:has_z]
203
- has_m_ = options_[:has_m]
204
- srid_ = (options_[:srid] || -1).to_i
205
- if options_[:geographic]
206
- type_ << 'Z' if has_z_
207
- type_ << 'M' if has_m_
208
- execute("ALTER TABLE #{quote_table_name(table_name_)} ADD COLUMN #{quote_column_name(column_name_)} GEOGRAPHY(#{type_},#{srid_})")
209
- change_column_default(table_name_, column_name_, options_[:default]) if options_include_default?(options_)
210
- change_column_null(table_name_, column_name_, false, options_[:default]) if options_[:null] == false
211
- else
212
- type_ = "#{type_}M" if has_m_ && !has_z_
213
- dimensions_ = 2
214
- dimensions_ += 1 if has_z_
215
- dimensions_ += 1 if has_m_
216
- execute("SELECT AddGeometryColumn('#{quote_string(table_name_)}', '#{quote_string(column_name_.to_s)}', #{srid_}, '#{quote_string(type_)}', #{dimensions_})")
217
- end
218
- end
219
- else
220
- super
221
- end
222
- end
223
-
224
-
225
- def remove_column(table_name_, *column_names_)
226
- column_names_ = column_names_.flatten.map{ |n_| n_.to_s }
227
- spatial_info_ = spatial_column_info(table_name_)
228
- remaining_column_names_ = []
229
- column_names_.each do |name_|
230
- if spatial_info_.include?(name_)
231
- execute("SELECT DropGeometryColumn('#{quote_string(table_name_.to_s)}','#{quote_string(name_)}')")
232
- else
233
- remaining_column_names_ << name_.to_sym
234
- end
235
- end
236
- if remaining_column_names_.size > 0
237
- super(table_name_, *remaining_column_names_)
238
- end
239
- end
240
-
241
-
242
- def add_index(table_name_, column_name_, options_={})
243
- # FULL REPLACEMENT. RE-CHECK ON NEW VERSIONS.
244
- # We have to fully-replace because of the gist_clause.
245
- table_name_ = table_name_.to_s
246
- column_names_ = ::Array.wrap(column_name_)
247
- index_name_ = index_name(table_name_, :column => column_names_)
248
- gist_clause_ = ''
249
- index_type_ = ''
250
- if ::Hash === options_ # legacy support, since this param was a string
251
- index_type_ = 'UNIQUE' if options_[:unique]
252
- index_name_ = options_[:name].to_s if options_.key?(:name)
253
- gist_clause_ = 'USING GIST' if options_[:spatial]
254
- else
255
- index_type_ = options_
256
- end
257
- if index_name_.length > index_name_length
258
- raise ::ArgumentError, "Index name '#{index_name_}' on table '#{table_name_}' is too long; the limit is #{index_name_length} characters"
259
- end
260
- if index_name_exists?(table_name_, index_name_, false)
261
- raise ::ArgumentError, "Index name '#{index_name_}' on table '#{table_name_}' already exists"
262
- end
263
- quoted_column_names_ = quoted_columns_for_index(column_names_, options_).join(", ")
264
- execute "CREATE #{index_type_} INDEX #{quote_column_name(index_name_)} ON #{quote_table_name(table_name_)} #{gist_clause_} (#{quoted_column_names_})"
265
- end
266
-
267
-
268
- def spatial_column_info(table_name_)
269
- info_ = query("SELECT * FROM geometry_columns WHERE f_table_name='#{quote_string(table_name_.to_s)}'")
270
- result_ = {}
271
- info_.each do |row_|
272
- name_ = row_[3]
273
- type_ = row_[6]
274
- dimension_ = row_[4].to_i
275
- has_m_ = type_ =~ /m$/i ? true : false
276
- type_.sub!(/m$/, '')
277
- has_z_ = dimension_ > 3 || dimension_ == 3 && !has_m_
278
- result_[name_] = {
279
- :name => name_,
280
- :type => type_,
281
- :dimension => dimension_,
282
- :srid => row_[5].to_i,
283
- :has_z => has_z_,
284
- :has_m => has_m_,
285
- }
286
- end
287
- result_
288
- end
289
-
290
-
291
- end
292
-
293
-
294
- end
295
-
296
- end
297
-
298
- end