-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathecto_ranked.ex
More file actions
344 lines (284 loc) · 9.49 KB
/
ecto_ranked.ex
File metadata and controls
344 lines (284 loc) · 9.49 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
defmodule EctoRanked do
@moduledoc """
This module provides support for automatic ranking of your `Ecto` models.
"""
import Ecto.Changeset
import Ecto.Query
@min -2_147_483_648
@max 2_147_483_647
@doc """
Updates the given changeset with the appropriate ranking, and updates/ranks
the other items in the list as necessary.
## Options
* `:rank` - the field to store the actual ranking in. Defaults to `:rank`
* `:position` - the field to use for positional changes. Defaults to `:position`
* `:scope` - the field(s) to scope all rankings to. Defaults to `nil` (no scoping).
* `:prefix` - the prefix to run all queries on (e.g. the schema path in Postgres). Defaults to `nil` (no prefix).
"""
@spec set_rank(Ecto.Changeset.t(), Keyword.t()) :: Ecto.Changeset.t()
def set_rank(changeset, opts \\ []) do
scope_field = Keyword.get(opts, :scope)
rank_field = Keyword.get(opts, :rank, :rank)
changeset =
if opts[:scope_required] do
if scope_field do
validate_required(
changeset,
if(is_list(scope_field), do: scope_field, else: [scope_field])
)
else
add_error(changeset, rank_field, "does not specify the required scope field")
end
else
changeset
end
prepare_changes(changeset, fn cs ->
if cs.action in [:insert, :update] do
options = %{
module: cs.data.__struct__,
scope_field: scope_field,
position_field: Keyword.get(opts, :position, :position),
rank_field: rank_field,
prefix: Keyword.get(opts, :prefix, nil)
}
cs
|> update_index_from_position(options, get_change(cs, options.position_field))
|> assure_unique_position(options)
end
end)
end
defp update_index_from_position(cs, options, position) do
case position do
pos when pos in ["first", :first] ->
first = get_current_first(cs, options)
if first do
rank_between(cs, options, pos, @min, first || @max)
else
update_index_from_position(cs, options, :middle)
end
pos when pos in ["middle", :middle] ->
rank_between(cs, options, pos, @min, @max)
pos when pos in ["last", :last] ->
last = get_current_last(cs, options)
if last do
rank_between(cs, options, pos, last || @min, @max)
else
update_index_from_position(cs, options, :middle)
end
pos when pos in ["up", :up] ->
case find_prev_two(cs, options) do
nil -> cs
{min, max} -> rank_between(cs, options, pos, min, max)
end
pos when pos in ["down", :down] ->
case find_next_two(cs, options) do
nil -> cs
{min, max} -> rank_between(cs, options, pos, min, max)
end
number when is_integer(number) ->
{min, max} = find_neighbors(cs, options, number)
rank_between(cs, options, number, min, max)
nil ->
if get_field(cs, options.rank_field) &&
(get_change(cs, options.rank_field) || !options.scope_field ||
!changes_to_scope_fields(cs, options.scope_field)) do
cs
else
update_index_from_position(cs, options, "last")
end
_ ->
raise ArgumentError, "invalid position"
end
end
defp changes_to_scope_fields(cs, scope_field) when is_list(scope_field) do
Enum.any?(scope_field, fn field ->
changes_to_scope_fields(cs, field)
end)
end
defp changes_to_scope_fields(cs, scope_field) do
get_change(cs, scope_field)
end
defp rank_between(cs, options, position, min, max) do
if max - min <= 1 do
cs |> rebalance_ranks(options) |> update_index_from_position(options, position)
else
rank = EctoRanked.Utils.ceiling((max - min) / 2) + min
rank_at(cs, options, rank)
end
end
defp rank_at(cs, options, rank) do
put_change(cs, options.rank_field, rank)
end
defp assure_unique_position(cs, options) do
rank = get_change(cs, options.rank_field)
if rank && (rank > @max || current_at_rank(cs, options)) do
rearrange_ranks(cs, options)
else
cs
end
end
defp current_at_rank(cs, options) do
rank = get_field(cs, options.rank_field)
finder(cs, options)
|> where([f], field(f, ^options.rank_field) == ^rank)
|> limit(1)
|> cs.repo.one(prefix: options.prefix)
end
defp rearrange_ranks(cs, options) do
rank = get_field(cs, options.rank_field)
current_first = get_current_first(cs, options)
current_last = get_current_last(cs, options)
cond do
# decrement lteq rank
current_first && current_first > @min && rank == @max ->
finder(cs, options)
|> where([m], field(m, ^options.rank_field) <= ^rank)
|> cs.repo.update_all([inc: [{options.rank_field, -1}]], prefix: options.prefix)
cs
# increment gteq rank
current_last && current_last < @max - 1 && rank < current_last ->
finder(cs, options)
|> where([m], field(m, ^options.rank_field) >= ^rank)
|> cs.repo.update_all([inc: [{options.rank_field, 1}]], prefix: options.prefix)
cs
# decrement ltrank
current_first && current_first > @min && rank > current_first ->
finder(cs, options)
|> where([m], field(m, ^options.rank_field) < ^rank)
|> cs.repo.update_all([inc: [{options.rank_field, -1}]], prefix: options.prefix)
put_change(cs, options.rank_field, rank - 1)
true ->
rebalance_ranks(cs, options)
end
end
defp rebalance_ranks(cs, options) do
items =
finder(cs, options)
|> order_by(asc: ^options.rank_field)
|> cs.repo.all(prefix: options.prefix)
rank = get_field(cs, options.rank_field)
rank_row(cs, options, items, 1, rank)
end
defp rank_row(cs, options, items, index, rank, set_self \\ false) do
if index > length(items) + 1 do
cs
else
rank_value = EctoRanked.Utils.ceiling((@max - @min) / (length(items) + 2) * index) + @min
current_index = index - 1
item = Enum.at(items, current_index)
current_rank = item && Map.get(item, options.rank_field)
if !set_self && (!item || (current_rank && current_rank < @max && current_rank >= rank)) do
cs = cs |> put_change(options.rank_field, rank_value)
rank_row(cs, options, items, index + 1, rank_value, true)
else
current_index = if set_self, do: current_index - 1, else: current_index
item = Enum.at(items, current_index)
change(item, [{options.rank_field, rank_value}])
|> cs.repo.update!(prefix: options.prefix)
rank_row(cs, options, items, index + 1, rank, set_self)
end
end
end
defp find_neighbors(cs, options, position) when position > 0 do
results =
finder(cs, options)
|> order_by(asc: ^options.rank_field)
|> limit(2)
|> offset(^(position - 1))
|> select([m], field(m, ^options.rank_field))
|> cs.repo.all(prefix: options.prefix)
case results do
[] ->
{get_current_last(cs, options), @max}
[lower] ->
{lower, @max}
[nil, nil] ->
rebalance_ranks(cs, options)
find_neighbors(cs, options, position)
[lower, upper] ->
{lower, upper}
end
end
defp find_neighbors(cs, options, _) do
first = get_current_first(cs, options)
case first do
nil -> {@min, @max}
first -> {@min, first}
end
end
defp get_current_first(cs, options) do
finder(cs, options)
|> order_by(asc: ^options.rank_field)
|> limit(1)
|> select([m], field(m, ^options.rank_field))
|> cs.repo.one(prefix: options.prefix)
end
defp get_current_last(cs, options) do
finder(cs, options)
|> order_by(desc: ^options.rank_field)
|> limit(1)
|> select([m], field(m, ^options.rank_field))
|> cs.repo.one(prefix: options.prefix)
|> case do
nil -> @min
min -> min
end
end
defp find_prev_two(cs, options) do
rank = get_field(cs, options.rank_field)
results =
finder(cs, options)
|> where([f], field(f, ^options.rank_field) < ^rank)
|> order_by(desc: ^options.rank_field)
|> limit(2)
|> select([f], field(f, ^options.rank_field))
|> cs.repo.all(prefix: options.prefix)
case results do
[] -> nil
[upper] -> {@min, upper}
[upper, lower] -> {lower, upper}
end
end
defp find_next_two(cs, options) do
rank = get_field(cs, options.rank_field)
results =
finder(cs, options)
|> where([f], field(f, ^options.rank_field) > ^rank)
|> order_by(asc: ^options.rank_field)
|> limit(2)
|> select([f], field(f, ^options.rank_field))
|> cs.repo.all(prefix: options.prefix)
case results do
[] -> nil
[lower] -> {lower, @max}
[lower, upper] -> {lower, upper}
end
end
defp finder(cs, options) do
query =
options.module
|> scope_query(cs, options.scope_field)
if cs.data.id do
query |> where([m], m.id != ^cs.data.id)
else
query
end
end
defp scope_query(query, cs, scope_field) when is_list(scope_field) do
Enum.reduce(scope_field, query, fn field, acc ->
scope_query(acc, cs, field)
end)
end
defp scope_query(query, cs, scope_field) do
if scope_field do
scope = get_field(cs, scope_field)
if scope do
query |> where([q], field(q, ^scope_field) == ^scope)
else
query |> where([q], is_nil(field(q, ^scope_field)))
end
else
query
end
end
end