Skip to content

Commit

Permalink
keep inserted_at value to the original value, #30
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonLab committed Feb 5, 2019
1 parent 4355536 commit a76418c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
21 changes: 21 additions & 0 deletions lib/alog.ex
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,19 @@ defmodule Alog do
User.all()
"""
def all do
# get the oldest items
sub =
from(m in __MODULE__,
distinct: m.entry_id,
order_by: [asc: :inserted_at],
select: m
)

query = from(m in subquery(sub), where: not m.deleted, select: m)

oldest_items = @repo.all(query)

# get the most recent inserted items, ie desc: :inserted_at
sub =
from(m in __MODULE__,
distinct: m.entry_id,
Expand All @@ -258,6 +271,14 @@ defmodule Alog do
query = from(m in subquery(sub), where: not m.deleted, select: m)

@repo.all(query)
|> Enum.map(fn(newest_item) ->
oldest_item = Enum.find(oldest_items, &(&1.entry_id == newest_item.entry_id))
if oldest_item do
%{newest_item | inserted_at: oldest_item.inserted_at}
else
newest_item
end
end)
end

@doc """
Expand Down
3 changes: 2 additions & 1 deletion test/all_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ defmodule AlogTest.AllTest do
test "does not include old items" do
{:ok, user} = %User{} |> User.changeset(Helpers.user_1_params()) |> User.insert()
{:ok, _} = %User{} |> User.changeset(Helpers.user_2_params()) |> User.insert()
{:ok, _} = user |> User.changeset(%{postcode: "W2 3EC"}) |> User.update()
{:ok, user_updated} = user |> User.changeset(%{postcode: "W2 3EC"}) |> User.update()

assert length(User.all()) == 2
assert user.inserted_at == user_updated.inserted_at
end
end
end

0 comments on commit a76418c

Please sign in to comment.