activerecord-cockroachdb-adapter 6.0.0beta1 → 6.1.0.pre.beta.2

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a580dde40d074b1982c6642310513d79bbcb710032a476a64bb9fcb99bec72bb
4
- data.tar.gz: 91b11b334235484e298704ae514d435a61451a02f3f759881141fd6354549ee4
3
+ metadata.gz: 856c8a5b793b12c32950311165d759ca18ae2ad2eadf28fe840f2fc3408f69af
4
+ data.tar.gz: 1826396e865d87ff66729cdad7b68f89aeec84ffc7a83cdfb9de8141661f1c09
5
5
  SHA512:
6
- metadata.gz: 77b98dff7d2069ba0cdcd78bccf5aedf9ac31192c0813d7893a5a6f1084537d9d0b03039be58fe83a5a0e0cd58d5d42ba567e43beee62507d8212242722fdb13
7
- data.tar.gz: f1bf6e2fa1925d94133a98dcd03690a24da2631134cc6a5eb6dd860253392f398db88572942f409f13dec4d3d7aeb34f18317a5b8cd4b30c70e4d75d13599b47
6
+ metadata.gz: 8ded85319e0d91018cef909714262f0474485f814aa0d35b0230a9e0a4adc31f66184a4203163aeef971d0fc3263631b3adb807b79263778212b742cfc243419
7
+ data.tar.gz: a730aef8f48b921d78df77f636699728ef37c6047bc28ad599aca252ea8c0967adae03a39a0b78e027e1fb4d5c7b95035b1efa53d3f4ef55b606db15dcc5621e
data/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 6.1.0-beta.2 - 2021-03-06
4
+
5
+ - Improved connection performance by refactoring an introspection
6
+ that loads types.
7
+ - Changed version numbers to semver.
8
+
9
+ ## 6.1.0beta1
10
+
11
+ - Initial support for Rails 6.1.
12
+ - Support for spatial functionality.
data/CONTRIBUTING.md CHANGED
@@ -78,6 +78,26 @@ RAILS_SOURCE="path/to/local_copy" bundle exec rake test
78
78
 
79
79
  `test/config.yml` assumes CockroachDB will be running at localhost:26257 with a root user. Make changes to `test/config.yml` as needed.
80
80
 
81
+ ### Run Tests from a Backup
82
+
83
+ Loading the full test schema every time a test runs can take a while, so for cases where loading the schema sequentially is unimportant, it is possible to use a backup to set up the database. This is significantly faster than the standard method and is provided to run individual tests faster, but should not be used to validate a build.
84
+
85
+ First create the template database.
86
+
87
+ ```bash
88
+ bundle exec rake db:create_test_template
89
+ ```
90
+
91
+ This will create a template database for the current version (ex. `activerecord_test_template611` for version 6.1.1) and create a `BACKUP` in the `nodelocal://self/activerecord-crdb-adapter/#{activerecord_version}` directory.
92
+
93
+ To load from the template, use the `COCKROACH_LOAD_FROM_TEMPLATE` flag.
94
+
95
+ ```bash
96
+ COCKROACH_LOAD_FROM_TEMPLATE=1 TEST_FILES="test/cases/adapters/postgresql/ddl_test.rb" bundle exec rake test
97
+ ```
98
+
99
+ And the `activerecord_unittest` database will use the `RESTORE` command to load the schema from the template database.
100
+
81
101
  # Improvements
82
102
 
83
103
 
data/README.md CHANGED
@@ -22,6 +22,297 @@ development:
22
22
  user: <username>
23
23
  ```
24
24
 
25
+ ## Working with Spatial Data
26
+
27
+ The adapter uses [RGeo](https://github.com/rgeo/rgeo) and [RGeo-ActiveRecord](https://github.com/rgeo/rgeo-activerecord) to represent geometric and geographic data as Ruby objects and easily interface them with the adapter. The following is a brief introduction to RGeo and tips to help setup your spatial application. More documentation about RGeo can be found in the [YARD Docs](https://rubydoc.info/github/rgeo/rgeo) and [wiki](https://github.com/rgeo/rgeo/wiki).
28
+
29
+ ### Installing RGeo
30
+
31
+ RGeo can be installed with the following command:
32
+
33
+ ```sh
34
+ gem install rgeo
35
+ ```
36
+
37
+ The best way to use RGeo is with GEOS support. If you have a version of libgeos installed, you can check that it was properly linked with RGeo by running the following commands:
38
+
39
+ ```rb
40
+ require 'rgeo'
41
+
42
+ RGeo::Geos.supported?
43
+ #=> true
44
+ ```
45
+
46
+ If this is `false`, you may need to specify the GEOS directory while installing. Here's an example linking it to the CockroachDB GEOS binary.
47
+
48
+ ```sh
49
+ gem install rgeo -- --with-geos-dir=/path/to/cockroach/lib/
50
+ ```
51
+
52
+ ### Working with RGeo
53
+
54
+ RGeo uses [factories](https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)) to create geometry objects and define their properties. Different factories define their own implementations for standard methods. For instance, the `RGeo::Geographic.spherical_factory` accepts latitudes and longitues as its coordinates and does computations on a spherical surface, while `RGeo::Cartesian.factory` implements geometry objects on a plane.
55
+
56
+ The factory (or factories) you choose to use will depend on the requirements of your application and what you need to do with the geometries they produce. For example, if you are working with points or other simple geometries across long distances and need precise results, the spherical factory is a good choice. If you're working with polygons or multipolygons and analyzing complex relationships between them (`intersects?`, `difference`, etc.), then using a cartesian factory backed by GEOS is a much better option.
57
+
58
+ Once you've selected a factory, you need to create objects. RGeo supports geometry creation through standard constructors (`point`, `line_string`, `polygon`, etc.) or by WKT and WKB.
59
+
60
+ ```rb
61
+ require 'rgeo'
62
+ factory = RGeo::Cartesian.factory(srid: 3857)
63
+
64
+ # Create a line_string from points
65
+ pt1 = factory.point(0,0)
66
+ pt2 = factory.point(1,1)
67
+ pt3 = factory.point(2,2)
68
+ line_string = factory.line_string([pt1,pt2,pt3])
69
+
70
+ p line_string.length
71
+ #=> 2.8284271247461903
72
+
73
+ # check line_string equality
74
+ line_string2 = factory.parse_wkt("LINESTRING (0 0, 1 1, 2 2)")
75
+ p line_string == line_string2
76
+ #=> true
77
+
78
+ # create polygon and test intersection with line_string
79
+ pt4 = factory.point(0,2)
80
+ outer_ring = factory.linear_ring([pt1,pt2,pt3,pt4,pt1])
81
+ poly = factory.polygon(outer_ring)
82
+
83
+ p line_string.intersects? poly
84
+ #=> true
85
+ ```
86
+ ### Creating Spatial Tables
87
+
88
+ To store spatial data, you must create a column with a spatial type. PostGIS
89
+ provides a variety of spatial types, including point, linestring, polygon, and
90
+ different kinds of collections. These types are defined in a standard produced
91
+ by the Open Geospatial Consortium. You can specify options indicating the coordinate system and number of coordinates for the values you are storing.
92
+
93
+ The adapter extends ActiveRecord's migration syntax to
94
+ support these spatial types. The following example creates five spatial
95
+ columns in a table:
96
+
97
+ ```rb
98
+ create_table :my_spatial_table do |t|
99
+ t.column :shape1, :geometry
100
+ t.geometry :shape2
101
+ t.line_string :path, srid: 3857
102
+ t.st_point :lonlat, geographic: true
103
+ t.st_point :lonlatheight, geographic: true, has_z: true
104
+ end
105
+ ```
106
+
107
+ The first column, "shape1", is created with type "geometry". This is a general
108
+ "base class" for spatial types; the column declares that it can contain values
109
+ of _any_ spatial type.
110
+
111
+ The second column, "shape2", uses a shorthand syntax for the same type as the shape1 column.
112
+ You can create a column either by invoking `column` or invoking the name of the type directly.
113
+
114
+ The third column, "path", has a specific geometric type, `line_string`. It
115
+ also specifies an SRID (spatial reference ID) that indicates which coordinate
116
+ system it expects the data to be in. The column now has a "constraint" on it;
117
+ it will accept only LineString data, and only data whose SRID is 3857.
118
+
119
+ The fourth column, "lonlat", has the `st_point` type, and accepts only Point
120
+ data. Furthermore, it declares the column as "geographic", which means it
121
+ accepts longitude/latitude data, and performs calculations such as distances
122
+ using a spheroidal domain.
123
+
124
+ The fifth column, "lonlatheight", is a geographic (longitude/latitude) point
125
+ that also includes a third "z" coordinate that can be used to store height
126
+ information.
127
+
128
+ The following are the data types understood by PostGIS and exposed by
129
+ the adapter:
130
+
131
+ - `:geometry` -- Any geometric type
132
+ - `:st_point` -- Point data
133
+ - `:line_string` -- LineString data
134
+ - `:st_polygon` -- Polygon data
135
+ - `:geometry_collection` -- Any collection type
136
+ - `:multi_point` -- A collection of Points
137
+ - `:multi_line_string` -- A collection of LineStrings
138
+ - `:multi_polygon` -- A collection of Polygons
139
+
140
+ Following are the options understood by the adapter:
141
+
142
+ - `:geographic` -- If set to true, create a PostGIS geography column for
143
+ longitude/latitude data over a spheroidal domain; otherwise create a
144
+ geometry column in a flat coordinate system. Default is false. Also
145
+ implies :srid set to 4326.
146
+ - `:srid` -- Set a SRID constraint for the column. Default is 4326 for a
147
+ geography column, or 0 for a geometry column. Note that PostGIS currently
148
+ (as of version 2.0) requires geography columns to have SRID 4326, so this
149
+ constraint is of limited use for geography columns.
150
+ - `:has_z` -- Specify that objects in this column include a Z coordinate.
151
+ Default is false.
152
+ - `:has_m` -- Specify that objects in this column include an M coordinate.
153
+ Default is false.
154
+
155
+ To create a PostGIS spatial index, add `using: :gist` to your index:
156
+
157
+ ```rb
158
+ add_index :my_table, :lonlat, using: :gist
159
+
160
+ # or
161
+
162
+ change_table :my_table do |t|
163
+ t.index :lonlat, using: :gist
164
+ end
165
+ ```
166
+ ### Configuring ActiveRecord
167
+
168
+ ActiveRecord's usefulness stems from the way it automatically configures
169
+ classes based on the database structure and schema. If a column in the
170
+ database has an integer type, ActiveRecord automatically casts the data to a
171
+ Ruby Integer. In the same way, the adapter automatically
172
+ casts spatial data to a corresponding RGeo data type.
173
+
174
+ RGeo offers more flexibility in its type system than can be
175
+ interpreted solely from analyzing the database column. For example, you can
176
+ configure RGeo objects to exhibit certain behaviors related to their
177
+ serialization, validation, coordinate system, or computation. These settings
178
+ are embodied in the RGeo factory associated with the object.
179
+
180
+ You can configure the adapter to use a particular factory (i.e. a
181
+ particular combination of settings) for data associated with each type in
182
+ the database.
183
+
184
+ Here's an example using a Geos default factory:
185
+
186
+ ```ruby
187
+ RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
188
+ # By default, use the GEOS implementation for spatial columns.
189
+ config.default = RGeo::Geos.factory_generator
190
+
191
+ # But use a geographic implementation for point columns.
192
+ config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point")
193
+ end
194
+ ```
195
+
196
+ The default spatial factory for geographic columns is `RGeo::Geographic.spherical_factory`.
197
+ The default spatial factory for cartesian columns is `RGeo::Cartesian.preferred_factory`.
198
+ You do not need to configure the `SpatialFactoryStore` if these defaults are ok.
199
+
200
+ More information about configuration options for the `SpatialFactoryStore` can be found in the [rgeo-activerecord](https://github.com/rgeo/rgeo-activerecord#spatial-factories-for-columns) docs.
201
+
202
+ ### Reading and Writing Spatial Columns
203
+
204
+ When you access a spatial attribute on your ActiveRecord model, it is given to
205
+ you as an RGeo geometry object (or nil, for attributes that allow null
206
+ values). You can then call the RGeo api on the object. For example, consider
207
+ the MySpatialTable class we worked with above:
208
+
209
+ ```rb
210
+ record = MySpatialTable.find(1)
211
+ point = record.lonlat # Returns an RGeo::Feature::Point
212
+ p point.x # displays the x coordinate
213
+ p point.geometry_type.type_name # displays "Point"
214
+ ```
215
+
216
+ The RGeo factory for the value is determined by how you configured the
217
+ ActiveRecord class, as described above. In this case, we explicitly set a
218
+ spherical factory for the `:lonlat` column:
219
+
220
+ ```rb
221
+ factory = point.factory # returns a spherical factory
222
+ ```
223
+
224
+ You can set a spatial attribute by providing an RGeo geometry object, or by
225
+ providing the WKT string representation of the geometry. If a string is
226
+ provided, the adapter will attempt to parse it as WKT and
227
+ set the value accordingly.
228
+
229
+ ```rb
230
+ record.lonlat = 'POINT(-122 47)' # sets the value to the given point
231
+ ```
232
+
233
+ If the WKT parsing fails, the value currently will be silently set to nil. In
234
+ the future, however, this will raise an exception.
235
+
236
+ ```rb
237
+ record.lonlat = 'POINT(x)' # sets the value to nil
238
+ ```
239
+
240
+ If you set the value to an RGeo object, the factory needs to match the factory
241
+ for the attribute. If the factories do not match, the adapter
242
+ will attempt to cast the value to the correct factory.
243
+
244
+ ```rb
245
+ p2 = factory.point(-122, 47) # p2 is a point in a spherical factory
246
+ record.lonlat = p2 # sets the value to the given point
247
+ record.shape1 = p2 # shape1 uses a flat geos factory, so it
248
+ # will cast p2 into that coordinate system
249
+ # before setting the value
250
+ record.save
251
+ ```
252
+
253
+ If you attempt to set the value to the wrong type, such as setting a linestring attribute to a point value, you will get an exception from the database when you attempt to save the record.
254
+
255
+ ```rb
256
+ record.path = p2 # This will appear to work, but...
257
+ record.save # This will raise an exception from the database
258
+ ```
259
+
260
+ ### Spatial Queries
261
+
262
+ You can create simple queries based on representational equality in the same
263
+ way you would on a scalar column:
264
+
265
+ ```ruby
266
+ record2 = MySpatialTable.where(:lonlat => factory.point(-122, 47)).first
267
+ ```
268
+
269
+ You can also use WKT:
270
+
271
+ ```ruby
272
+ record3 = MySpatialTable.where(:lonlat => 'POINT(-122 47)').first
273
+ ```
274
+
275
+ Note that these queries use representational equality, meaning they return
276
+ records where the lonlat value matches the given value exactly. A 0.00001
277
+ degree difference would not match, nor would a different representation of the
278
+ same geometry (like a multi_point with a single element). Equality queries
279
+ aren't generally all that useful in real world applications. Typically, if you
280
+ want to perform a spatial query, you'll look for, say, all the points within a
281
+ given area. For those queries, you'll need to use the standard spatial SQL
282
+ functions provided by PostGIS.
283
+
284
+ To perform more advanced spatial queries, you can use the extended Arel interface included in the adapter. The functions accept WKT strings or RGeo features.
285
+
286
+ ```rb
287
+ point = RGeo::Geos.factory(srid: 0).point(1,1)
288
+
289
+ # Example Building model where geom is a column of polygons.
290
+ buildings = Building.arel_table
291
+ containing_buiildings = Building.where(buildings[:geom].st_contains(point))
292
+ ```
293
+
294
+ See the [rgeo-activerecord YARD Docs](https://rubydoc.info/github/rgeo/rgeo-activerecord/RGeo/ActiveRecord/SpatialExpressions) for a list of available PostGIS functions.
295
+
296
+ ### Validation Issues
297
+
298
+ If you see an `RGeo::Error::InvalidGeometry (LinearRing failed ring test)` message while loading data or creating geometries, this means that the geometry you are trying to instantiate is not topologically valid. This is usually due to self-intersections in the geometry. The default behavior of RGeo factories is to raise this error when an invalid geometry is being instansiated, but this can be ignored by setting the `uses_lenient_assertions` flag to `true` when creating your factory.
299
+
300
+ ```rb
301
+ regular_fac = RGeo::Geographic.spherical_factory
302
+ modified_fac = RGeo::Geographic.spherical_factory(uses_lenient_assertions: true)
303
+
304
+ wkt = "POLYGON (0 0, 1 1, 0 1, 1 0, 0 0)" # closed ring with self intersection
305
+
306
+ regular_fac.parse_wkt(wkt)
307
+ #=> RGeo::Error::InvalidGeometry (LinearRing failed ring test)
308
+
309
+ p modified_fac.parse_wkt(wkt)
310
+ #=> #<RGeo::Geographic::SphericalPolygonImpl>
311
+ ```
312
+
313
+ Be careful when performing calculations on potentially invalid geometries, as the results might be nonsensical. For example, the area returned of an hourglass made of 2 equivalent triangles with a self-intersection in the middle is 0.
314
+
315
+ Note that when using the `spherical_factory`, there is a chance that valid geometries will be interpreted as invalid due to floating point issues with small geometries.
25
316
 
26
317
  ## Modifying the adapter?
27
318
 
data/Rakefile CHANGED
@@ -2,10 +2,30 @@ require "bundler/gem_tasks"
2
2
  require "rake/testtask"
3
3
  require_relative 'test/support/paths_cockroachdb'
4
4
  require_relative 'test/support/rake_helpers'
5
+ require_relative 'test/support/template_creator'
5
6
 
6
7
  task test: ["test:cockroachdb"]
7
8
  task default: [:test]
8
9
 
10
+ namespace :db do
11
+ task "create_test_template" do
12
+ ENV['DEBUG_COCKROACHDB_ADAPTER'] = "1"
13
+ ENV['COCKROACH_SKIP_LOAD_SCHEMA'] = "1"
14
+ ENV["ARCONN"] = "cockroachdb"
15
+
16
+ TemplateCreator.connect
17
+ require_relative 'test/cases/helper'
18
+
19
+ # TODO: look into this more, but for some reason the blob alias
20
+ # is not defined while running this task.
21
+ ActiveRecord::ConnectionAdapters::CockroachDB::TableDefinition.class_eval do
22
+ alias :blob :binary
23
+ end
24
+
25
+ TemplateCreator.create_test_template
26
+ end
27
+ end
28
+
9
29
  namespace :test do
10
30
  Rake::TestTask.new("cockroachdb") do |t|
11
31
  t.libs = ARTest::CockroachDB.test_load_paths
@@ -4,7 +4,7 @@ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
4
 
5
5
  Gem::Specification.new do |spec|
6
6
  spec.name = "activerecord-cockroachdb-adapter"
7
- spec.version = "6.0.0beta1"
7
+ spec.version = "6.1.0-beta.2"
8
8
  spec.licenses = ["Apache-2.0"]
9
9
  spec.authors = ["Cockroach Labs"]
10
10
  spec.email = ["cockroach-db@googlegroups.com"]
@@ -13,8 +13,9 @@ Gem::Specification.new do |spec|
13
13
  spec.description = "Allows the use of CockroachDB as a backend for ActiveRecord and Rails apps."
14
14
  spec.homepage = "https://github.com/cockroachdb/activerecord-cockroachdb-adapter"
15
15
 
16
- spec.add_dependency "activerecord", "~> 6.0.3"
17
- spec.add_dependency "pg", ">= 0.20"
16
+ spec.add_dependency "activerecord", "~> 6.1"
17
+ spec.add_dependency "pg", "~> 1.2"
18
+ spec.add_dependency "rgeo-activerecord", "~> 7.0.0"
18
19
 
19
20
  # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
20
21
  # to allow pushing to a single host or delete this section to allow pushing to any host.
@@ -3,7 +3,7 @@
3
3
  set -euox pipefail
4
4
 
5
5
  # Download CockroachDB
6
- VERSION=v20.2.1
6
+ VERSION=v20.2.3
7
7
  wget -qO- https://binaries.cockroachdb.com/cockroach-$VERSION.linux-amd64.tgz | tar xvz
8
8
  readonly COCKROACH=./cockroach-$VERSION.linux-amd64/cockroach
9
9
 
@@ -21,7 +21,7 @@ run_cockroach() {
21
21
  cockroach quit --insecure || true
22
22
  rm -rf cockroach-data
23
23
  # Start CockroachDB.
24
- cockroach start-single-node --max-sql-memory=25% --cache=25% --insecure --host=localhost --listening-url-file="$urlfile" >/dev/null 2>&1 &
24
+ cockroach start-single-node --max-sql-memory=25% --cache=25% --insecure --host=localhost --spatial-libs=./cockroach-$VERSION.linux-amd64/lib --listening-url-file="$urlfile" >/dev/null 2>&1 &
25
25
  # Ensure CockroachDB is stopped on script exit.
26
26
  trap "echo 'Exit routine: Killing CockroachDB.' && kill -9 $! &> /dev/null" EXIT
27
27
  # Wait until CockroachDB has started.
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RGeo
4
+ module ActiveRecord
5
+ ##
6
+ # Extend rgeo-activerecord visitors to use PostGIS specific functionality
7
+ module SpatialToPostGISSql
8
+ def visit_in_spatial_context(node, collector)
9
+ # Use ST_GeomFromEWKT for EWKT geometries
10
+ if node.is_a?(String) && node =~ /SRID=[\d+]{0,};/
11
+ collector << "#{st_func('ST_GeomFromEWKT')}(#{quote(node)})"
12
+ else
13
+ super(node, collector)
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
19
+ RGeo::ActiveRecord::SpatialToSql.prepend RGeo::ActiveRecord::SpatialToPostGISSql
20
+
21
+ module Arel # :nodoc:
22
+ module Visitors # :nodoc:
23
+ class CockroachDB < PostgreSQL # :nodoc:
24
+ include RGeo::ActiveRecord::SpatialToSql
25
+ end
26
+ end
27
+ end