Custom ecto/postgrex types for Point data type?

At this moment postgrex package have built-in point data type (geometric, not a PostGIS one), according to the source code:


I’m trying to use it with Ecto, no luck so far. Is there a way to use it in ecto schema? Regular way (Postgrex.Types.define) doesn’t seem to work for me

1 Like

UPD: created custom ecto wrapper, seems to be working correctly. No idea why no one did that before

defmodule App.EctoPoint do
  @behaviour Ecto.Type
  def type, do: Postgrex.Point

  # Casting from input into point struct
  def cast(value = %Postgrex.Point{}), do: {:ok, value}
  def cast(_), do: :error

  # loading data from the database
  def load(data) do
    {:ok, data}
  end

  # dumping data to the database
  def dump(value = %Postgrex.Point{}), do: {:ok, value}
  def dump(_), do: :error
end
6 Likes

That looks great. Also see the geo_postgis library: https://github.com/bryanjos/geo_postgis :slight_smile:

2 Likes

Sure. Besides, geo_postgis is for PostGIS stuff (separate package, not installed by default), not a regular point .
e.g. PostGIS’ Geo.Point includes coordinates and srid projection, different data type.
PostGIS makes sense if someone goes full-blown geographic approach, for more humble use-cases (e.g. sort stuff by distance to a person, sped up by an index) point is more than enough

5 Likes

I see. Thanks for clarifying!

2 Likes