-
Notifications
You must be signed in to change notification settings - Fork 47
/
migration.ex
301 lines (250 loc) · 8.22 KB
/
migration.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
defmodule Rihanna.Migration do
@max_32_bit_signed_integer (:math.pow(2, 31) |> round) - 1
@moduledoc """
A set of tools for creating the Rihanna jobs table.
Rihanna stores jobs in a table in your database. The default table name is
"rihanna_jobs". The name is configurable by either passing it as an argument
to the functions below or setting `:jobs_table_name` in Rihanna's config.
#### Using Ecto
The easiest way to create the database is with Ecto.
Run `mix ecto.gen.migration create_rihanna_jobs` and make your migration file
look like this:
```elixir
defmodule MyApp.CreateRihannaJobs do
use Rihanna.Migration
end
```
Now you can run `mix ecto.migrate`.
#### Without Ecto
Ecto is not required to run Rihanna. If you want to create the table yourself,
without Ecto, take a look at either `statements/0` or `sql/0`.
"""
defmacro __using__(opts) do
table_name = Keyword.get(opts, :table_name, Rihanna.Config.jobs_table_name()) |> to_string
quote do
use Ecto.Migration
def up do
Enum.each(Rihanna.Migration.statements(unquote(table_name)), fn statement ->
execute(statement)
end)
end
def down do
Enum.each(Rihanna.Migration.drop_statements(unquote(table_name)), fn statement ->
execute(statement)
end)
end
end
end
@doc """
Returns a list of SQL statements that will drop the Rihanna jobs table if
executed sequentially.
By default it takes the name of the table from the application config.
You may optionally supply a table name as an argument if you want to override
this.
## Examples
> Rihanna.Migration.drop_statements
[...]
> Rihanna.Migration.drop_statements("my_alternative_table_name")
[...]
"""
def drop_statements(table_name \\ Rihanna.Config.jobs_table_name()) do
[
"""
DROP TABLE IF EXISTS "#{table_name}";
""",
"""
DROP SEQUENCE IF EXISTS #{table_name}_id_seq;
"""
]
end
@doc """
Returns a list of SQL statements that will create the Rihanna jobs table if
executed sequentially.
By default it takes the name of the table from the application config.
You may optionally supply a table name as an argument if you want to override
this.
## Examples
> Rihanna.Migration.statements
[...]
> Rihanna.Migration.statements("my_alternative_table_name")
[...]
"""
@spec statements() :: list[String.t()]
@spec statements(String.t() | atom) :: list[String.t()]
def statements(table_name \\ Rihanna.Config.jobs_table_name())
when is_binary(table_name) or is_atom(table_name) do
[
"""
CREATE TABLE #{table_name} (
id int NOT NULL,
term bytea NOT NULL,
priority integer NOT NULL DEFAULT 50,
enqueued_at timestamp with time zone NOT NULL,
due_at timestamp with time zone,
failed_at timestamp with time zone,
fail_reason text,
rihanna_internal_meta jsonb NOT NULL DEFAULT '{}',
CONSTRAINT failed_at_required_fail_reason CHECK((failed_at IS NOT NULL AND fail_reason IS NOT NULL) OR (failed_at IS NULL and fail_reason IS NULL))
);
""",
"""
COMMENT ON CONSTRAINT failed_at_required_fail_reason ON #{table_name} IS 'When setting failed_at you must also set a fail_reason';
""",
"""
CREATE SEQUENCE #{table_name}_id_seq
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE #{@max_32_bit_signed_integer}
CACHE 1
CYCLE;
""",
"""
ALTER SEQUENCE #{table_name}_id_seq OWNED BY #{table_name}.id;
""",
"""
ALTER TABLE ONLY #{table_name} ALTER COLUMN id SET DEFAULT nextval('#{table_name}_id_seq'::regclass);
""",
"""
ALTER TABLE ONLY #{table_name}
ADD CONSTRAINT #{table_name}_pkey PRIMARY KEY (id);
""",
"""
CREATE INDEX IF NOT EXISTS #{table_name}_locking_index ON #{table_name} (priority ASC, due_at ASC NULLS FIRST, enqueued_at ASC, id ASC);
"""
]
end
@doc """
Returns a string of semi-colon-terminated SQL statements that you can execute
directly to create the Rihanna jobs table.
"""
@spec sql(String.t() | atom) :: String.t()
def sql(table_name \\ Rihanna.Config.jobs_table_name()) do
Enum.join(statements(table_name), "\n")
end
@migrate_help_message """
The Rihanna jobs table must be created.
Rihanna stores jobs in a table in your database.
The default table name is "rihanna_jobs".
The easiest way to create the database is with Ecto.
Run `mix ecto.gen.migration create_rihanna_jobs` and make your migration look
like this:
defmodule MyApp.CreateRihannaJobs do
use Rihanna.Migration
end
Now you can run `mix ecto.migrate`.
"""
@doc false
# Check that the rihanna jobs table exists
def check_table!(pg) do
case Postgrex.query(
pg,
"""
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_name = $1
AND table_schema = current_schema()
);
""",
[Rihanna.Job.table()]
) do
{:ok, %{rows: [[true]]}} ->
:ok
{:ok, %{rows: [[false]]}} ->
raise_jobs_table_missing!()
end
end
@doc false
def raise_jobs_table_missing!() do
raise ArgumentError, @migrate_help_message
end
@upgrade_help_message """
The Rihanna jobs table must be upgraded.
The easiest way to upgrade the database is with Ecto.
Run `mix ecto.gen.migration upgrade_rihanna_jobs` and make your migration look
like this:
defmodule MyApp.UpgradeRihannaJobs do
use Rihanna.Migration.Upgrade
end
Now you can run `mix ecto.migrate`.
"""
@doc false
# Check that the required upgrades have been added
def check_upgrade_not_required!(pg) do
required_upgrade_columns = ["due_at", "rihanna_internal_meta", "priority"]
table_name = Rihanna.Job.table()
case Postgrex.query(
pg,
"""
SELECT column_name
FROM information_schema.columns
WHERE table_name = $1
AND column_name = ANY($2)
AND table_schema = current_schema();
""",
# Migration adds due_at, test if this is present
[table_name, required_upgrade_columns]
) do
{:ok, %{rows: rows}} when length(rows) < length(required_upgrade_columns) ->
raise_upgrade_required!()
{:ok, %{rows: rows}} when length(rows) == length(required_upgrade_columns) ->
:ok
end
required_indexes = ["#{table_name}_pkey", "#{table_name}_locking_index"]
case Postgrex.query(
pg,
"""
SELECT
DISTINCT i.relname AS index_name
FROM
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a
WHERE
t.oid = ix.indrelid
AND i.oid = ix.indexrelid
AND a.attrelid = t.oid
AND a.attnum = ANY(ix.indkey)
AND t.relkind = 'r'
AND t.relname = $1
AND i.relname = ANY($2);
""",
[table_name, required_indexes]
) do
{:ok, %{rows: rows}} when length(rows) < length(required_indexes) ->
raise_upgrade_required!()
{:ok, %{rows: rows}} when length(rows) == length(required_indexes) ->
:ok
end
nulls_first = ~r/due_at NULLS FIRST/
# check to ensure the locking index orders due_at with NULLS FIRST
# if it does not, then an upgrade needs to be performed as the
# performance will be impacted
case Postgrex.query(
pg,
"""
SELECT indexdef
FROM pg_indexes
WHERE tablename = $1
AND indexname = $2
AND schemaname = current_schema()
""",
[table_name, "#{table_name}_locking_index"]
) do
{:ok, %{rows: []}} ->
raise_upgrade_required!()
{:ok, %{rows: [[index]]}} ->
if Regex.match?(nulls_first, index) do
:ok
else
raise_upgrade_required!()
end
end
end
@doc false
def raise_upgrade_required!() do
raise ArgumentError, @upgrade_help_message
end
end