Rails / Active RecordでMySQLのgeometry型をサポートするライブラリを書いた

Armgという、ARをMySQLのgeometry型に対応させるためのライブラリを書きました。

github.com

使い方は以下の通り。

require 'active_record'
require 'armg'

ActiveRecord::Base.establish_connection(adapter: 'mysql2', database: 'my_db');

ActiveRecord::Migration.create_table :geoms, options: 'ENGINE=MyISAM' do |t|
  t.geometry 'location', null: false
  t.index ['location'], name: 'idx_location', type: :spatial
end

class Geom < ActiveRecord::Base; end

wkt_parser = RGeo::WKRep::WKTParser.new(nil, support_ewkt: true)
point = wkt_parser.parse('SRID=4326;Point(-122.1 47.3)')
Geom.create!(location: point)

Geom.first
#=> #<Geom id: 1, location: #<RGeo::Cartesian::PointImpl:0x... "POINT (-122.1 47.3)">>

ridgepoleにPRをもらって、コードを眺めていたら何となく対応できそうだったので、書いてみた感じです。当初は自前でWKBのパースをやっていたんですが、まじめに考えると大変そうだったので、RGeoを使うようにしました。 MySQL 5.7の最新版だとInnoDBでもgeometry型にインデックスを貼れるので、利用する機会も増えるかも。

ridgepoleでは以下のように-rオプションでarmgを渡してやると、ダンプできます(が、動作はきちんと確認できてません)

$ ridgepole -c mysql2://root:pass@127.0.0.1:13306/test -r armg -e
# Export Schema
create_table "geoms", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t|
  t.geometry "location", null: false
  t.index ["location"], name: "idx_location", type: :spatial
end