Skip to content

Instantly share code, notes, and snippets.

@retgoat
Last active Aug 12, 2017
Embed
What would you like to do?
postgrex
def get_specific_version(id, version, scope) do
datetime = Timex.parse!(version, "%FT%T.%fZ", :strftime)
|> Timex.shift(seconds: -1)
|> Timex.to_datetime
q = """
SELECT #{version_fields()} FROM #{table()}
WHERE id = $1::integer AND sys_period @> $2::timestamptz AND scope @> $3::ltree
UNION ALL
SELECT #{version_fields()} from #{history_table()}
WHERE id = $1::integer AND sys_period @> $2::timestamptz AND scope @> $3::ltree;
"""
case Ecto.Adapters.SQL.query(Repo, q, [id, datetime, scope]) do
{:ok, res} -> format_version(res)
{:error, _} -> raise %NotFoundError{message: "Version #{version} not found"}
end
end
def format_version(data) do
cols = Enum.map(data.columns, &(String.to_atom(&1)))
v = Enum.flat_map(data.rows, fn(r) ->
Enum.zip(cols, r)
end)
|> Enum.into(%{})
|> Map.update!(:inserted_at, &(Timex.format!(&1, "%FT%T.%fZ", :strftime)))
|> Map.update!(:updated_at, &(Timex.format!(&1, "%FT%T.%fZ", :strftime)))
d = if Map.has_key?(v, :schema_version) do
Map.update!(v, :schema_version, &(Timex.format!(&1, "%FT%T.%fZ", :strftime)))
else
v
end
{:ok, d}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment