Last active
August 12, 2017 04:51
-
-
Save retgoat/be91745ed74b6bc07257c68bac5c7036 to your computer and use it in GitHub Desktop.
postgrex
This file contains 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
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