Using geometry types with sqlite_ecto2
anagromataf opened this issue · comments
I'm currently using this library together with a PostgreSQL database (using PostGIS). There I have a schema with a field using Geo.Point
.
defmodule City do
use Ecto.Schema
schema "locality" do
field(:name, :string)
field(:population, :integer)
field(:coordinate, Geo.Point)
end
end
This works perfectly.
Now I need to provide support for a sqlite database. When I only change the adapter I get the following issue (I stored the coordinate as GeoJSON and also tried WKB):
** (ArgumentError) cannot load `"{\"type\":\"Point\",\"coordinates\":[13.41053,52.52437]}"` as type Geo.Point for field `coordinate` in schema City
(ecto) lib/ecto/schema.ex:1533: Ecto.Schema.load!/5
(ecto) lib/ecto/schema.ex:1474: Ecto.Schema.safe_load_zip/4
(ecto) lib/ecto/schema.ex:1475: Ecto.Schema.safe_load_zip/4
(ecto) lib/ecto/schema.ex:1460: Ecto.Schema.__safe_load__/6
(ecto) lib/ecto/repo/queryable.ex:307: Ecto.Repo.Queryable.process_source/6
(ecto) lib/ecto/repo/queryable.ex:178: Ecto.Repo.Queryable.preprocess/5
(elixir) lib/enum.ex:1294: Enum."-map/2-lists^map/1-0-"/2
(sqlite_ecto2) lib/sqlite_db_connection/query.ex:43: DBConnection.Query.Sqlite.DbConnection.Query.decode/3
I played around a bit and could solve the issue by adding the following function head to Geo.Point
:
if Code.ensure_loaded?(Poison) do
def load(point) when is_binary(point), do: { :ok, Poison.decode!(point) |> Geo.JSON.decode }
end
If this is the right direction and a PR is welcome I would be happy to do the changes.
I think this brings up an interesting point. I am hoping to separate the ecto-specific code from here make this more generic so that there may be in the future a sqlite package that uses geo maybe. I think what you have is good in the short term though until we can meet that goal
Actually, probably not anymore (sorry I just merged in some changes to master). But maybe in geo_postgis
for now since that's where that code will live