Skip to content

Commit 04d7b26

Browse files
authored
Merge pull request #65 from brunohkbx/feat/add-history_query/1
feat: add function history_query/1
2 parents 678e53e + af01997 commit 04d7b26

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

lib/repo/queryable.ex

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
defmodule ExAudit.Queryable do
22
require Logger
33

4+
import Ecto.Query, only: [from: 2, where: 3]
5+
46
defp version_schema() do
57
Application.get_env(:ex_audit, :version_schema)
68
end
@@ -16,8 +18,6 @@ defmodule ExAudit.Queryable do
1618
end
1719

1820
def history(module, struct, opts) do
19-
import Ecto.Query
20-
2121
query =
2222
from(
2323
v in version_schema(),
@@ -74,6 +74,15 @@ defmodule ExAudit.Queryable do
7474
end
7575
end
7676

77+
def history_query(%{id: id, __struct__: struct}) do
78+
from(
79+
v in version_schema(),
80+
where: v.entity_id == ^id,
81+
where: v.entity_schema == ^struct,
82+
order_by: [desc: :recorded_at]
83+
)
84+
end
85+
7786
@drop_fields [:__meta__, :__struct__]
7887

7988
def revert(module, version, opts) do

lib/repo/repo.ex

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,10 @@ defmodule ExAudit.Repo do
212212
def revert(version, opts \\ []) do
213213
ExAudit.Queryable.revert(__MODULE__, version, opts)
214214
end
215+
216+
def history_query(struct) do
217+
ExAudit.Queryable.history_query(struct)
218+
end
215219
end
216220
end
217221

@@ -228,6 +232,12 @@ defmodule ExAudit.Repo do
228232
"""
229233
@callback history(struct, opts :: list) :: [version :: struct]
230234

235+
@doc """
236+
Returns a query that gathers the version history for the given struct, ordered by the time the changes
237+
happened from newest to oldest.
238+
"""
239+
@callback history_query(struct) :: Ecto.Query.t()
240+
231241
@doc """
232242
Undoes the changes made in the given version, as well as all of the following versions.
233243
Inserts a new version entry in the process, with the `:rollback` flag set to true

test/ex_audit_test.exs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,4 +245,23 @@ defmodule ExAuditTest do
245245

246246
assert 2 = Repo.aggregate(query, :count, :id)
247247
end
248+
249+
describe "history_query/1" do
250+
setup do
251+
params = %{
252+
name: "Foo",
253+
254+
}
255+
256+
changeset = User.changeset(%User{}, params)
257+
258+
{:ok, user} = Repo.insert(changeset)
259+
260+
%{user: user}
261+
end
262+
263+
test "returns a queryable", %{user: user} do
264+
assert user |> Repo.history_query() |> Repo.all() |> Enum.count() == 1
265+
end
266+
end
248267
end

0 commit comments

Comments
 (0)