-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathversion.ex
93 lines (78 loc) · 2.76 KB
/
version.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
defmodule PaperTrail.Version do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query
@type t :: %__MODULE__{}
# @setter PaperTrail.RepoClient.originator()
# @item_type Application.get_env(:paper_trail, :item_type, :integer)
# @originator_type Application.get_env(:paper_trail, :originator_type, :integer)
schema "versions" do
field(:event, :string)
field(:item_type, :string)
field(:item_id, Application.get_env(:paper_trail, :item_type, :integer))
field(:item_changes, :map)
field(:originator_id, Application.get_env(:paper_trail, :originator_type, :integer))
field(:origin, :string,
read_after_writes: Application.get_env(:paper_trail, :origin_read_after_writes, true)
)
field(:meta, :map)
if PaperTrail.RepoClient.originator() do
belongs_to(
PaperTrail.RepoClient.originator()[:name],
PaperTrail.RepoClient.originator()[:model],
Keyword.merge(Application.get_env(:paper_trail, :originator_relationship_options, []),
define_field: false,
foreign_key: :originator_id,
type: Application.get_env(:paper_trail, :originator_type, :integer)
)
)
end
timestamps(
updated_at: false,
type: Application.get_env(:paper_trail, :timestamps_type, :utc_datetime)
)
end
def changeset(model, params \\ :empty) do
model
|> cast(params, [:item_type, :item_id, :item_changes, :origin, :originator_id, :meta])
|> validate_required([:event, :item_type, :item_id, :item_changes])
end
@doc """
Returns the count of all version records in the database
"""
def count do
from(version in __MODULE__, select: count(version.id)) |> PaperTrail.RepoClient.repo().one()
end
def count(options) do
from(version in __MODULE__, select: count(version.id))
|> Ecto.Queryable.to_query()
|> Map.put(:prefix, options[:prefix])
|> PaperTrail.RepoClient.repo().one
end
@doc """
Returns the first version record in the database by :inserted_at
"""
def first do
from(record in __MODULE__, limit: 1, order_by: [asc: :inserted_at])
|> PaperTrail.RepoClient.repo().one
end
def first(options) do
from(record in __MODULE__, limit: 1, order_by: [asc: :inserted_at])
|> Ecto.Queryable.to_query()
|> Map.put(:prefix, options[:prefix])
|> PaperTrail.RepoClient.repo().one
end
@doc """
Returns the last version record in the database by :inserted_at
"""
def last do
from(record in __MODULE__, limit: 1, order_by: [desc: :inserted_at])
|> PaperTrail.RepoClient.repo().one
end
def last(options) do
from(record in __MODULE__, limit: 1, order_by: [desc: :inserted_at])
|> Ecto.Queryable.to_query()
|> Map.put(:prefix, options[:prefix])
|> PaperTrail.RepoClient.repo().one
end
end