diff --git a/lib/alog.ex b/lib/alog.ex index a742a29..5d782d7 100644 --- a/lib/alog.ex +++ b/lib/alog.ex @@ -175,12 +175,15 @@ defmodule Alog do end) end).() |> order_by([m], desc: m.inserted_at) - |> limit([m], 1) + |> distinct([m], m.entry_id) |> select([m], m) query = from(m in subquery(sub), where: not m.deleted, select: m) - item = @repo.one(query) + query + |> @repo.all + |> Enum.filter(fn item -> item && __MODULE__.get(item.entry_id) == item end) + |> List.last() end @doc """ diff --git a/mix.exs b/mix.exs index 30022f7..b7e96a5 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule Alog.MixProject do def project do [ app: :alog, - version: "0.4.1", + version: "0.4.2", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, diff --git a/test/get_by_test.exs b/test/get_by_test.exs index 650a12b..7bf938a 100644 --- a/test/get_by_test.exs +++ b/test/get_by_test.exs @@ -35,5 +35,32 @@ defmodule AlogTest.GetByTest do assert User.get_by([name: "thor"], case_insensitive: true) == user assert User.get_by(%{name: "thor"}, case_insensitive: true) == user end + + test "does not retrieve outdated results" do + {:ok, user} = %User{} |> User.changeset(Helpers.user_1_params()) |> User.insert() + {:ok, updated_user} = user |> User.changeset(%{postcode: "EC3 RST"}) |> User.update() + + assert User.get_by(postcode: "E2 0SY") == nil + end + + test "does retrieve updated results if they match" do + {:ok, user} = %User{} |> User.changeset(Helpers.user_1_params()) |> User.insert() + {:ok, updated_user} = user |> User.changeset(%{postcode: "EC3 RST"}) |> User.update() + + assert User.get_by(name: "Thor") |> User.preload(:items) == updated_user + end + + test "ignores outdated and retrieves matching" do + {:ok, user} = %User{} |> User.changeset(Helpers.user_1_params()) |> User.insert() + + {:ok, user_2} = + %User{} + |> User.changeset(Map.put(Helpers.user_2_params(), :postcode, "E2 0SY")) + |> User.insert() + + {:ok, updated_user_2} = user_2 |> User.changeset(%{postcode: "EC3 RST"}) |> User.update() + + assert User.get_by(postcode: "E2 0SY") == user + end end end