Created
March 8, 2024 01:25
-
-
Save mitchellhenke/25ade3032c3fe5cb9153c002c4189571 to your computer and use it in GitHub Desktop.
Sqlite Point
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Sqlite.EctoTypes do | |
defmodule Point do | |
use Ecto.Type | |
def type, do: :binary | |
def cast(%Geo.Point{} = point), do: {:ok, point} | |
def cast(_), do: :error | |
def load(data) when is_binary(data) do | |
case parse(data) do | |
:error -> | |
:error | |
point -> | |
{:ok, point} | |
end | |
end | |
def dump(%Geo.Point{coordinates: {x, y}, srid: srid}) do | |
{:ok, | |
<<0, 1::size(8)-unsigned-integer, srid::size(32)-unsigned-integer-little, | |
x::size(64)-signed-float-little, y::size(64)-signed-float-little, | |
x::size(64)-signed-float-little, y::size(64)-signed-float-little, 124, | |
1::size(32)-unsigned-integer-little, x::size(64)-signed-float-little, | |
y::size(64)-signed-float-little, 254>>} | |
end | |
def dump(_), do: :error | |
defp parse(<<0, 1, rest::binary>>) do | |
little_parse(rest) | |
end | |
defp parse(<<0, 0, rest::binary>>) do | |
big_parse(rest) | |
end | |
defp parse(_), do: :error | |
defp little_parse( | |
<<srid::size(32)-unsigned-integer-little, _mbr_stuff::little-32-bytes, 124, | |
class::size(32)-unsigned-integer-little, rest::binary>> | |
) do | |
parse_little_geometry(rest, class, srid) | |
end | |
defp big_parse( | |
<<srid::size(32)-unsigned-integer, _mbr_stuff::32-bytes, 124, | |
class::size(32)-unsigned-integer, rest::binary>> | |
) do | |
parse_big_geometry(rest, class, srid) | |
end | |
defp parse_little_geometry( | |
<<x::size(64)-signed-float-little, y::size(64)-signed-float-little, 254>>, | |
1, | |
srid | |
) do | |
%Geo.Point{coordinates: {x, y}, srid: srid} | |
end | |
defp parse_big_geometry(<<x::size(64)-signed-float, y::size(64)-signed-float, 254>>, 1, srid) do | |
%Geo.Point{coordinates: {x, y}, srid: srid} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment