File tree Expand file tree Collapse file tree 3 files changed +40
-2
lines changed
Expand file tree Collapse file tree 3 files changed +40
-2
lines changed Original file line number Diff line number Diff line change 11defmodule 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
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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
248267end
You can’t perform that action at this time.
0 commit comments