Make purchase order deterministic

Avoids ordering issues when records have the same purchased_at datetime
(which is what happens when they're scanned in batches).
This commit is contained in:
Claudio Ortolina
2025-05-04 09:20:45 +01:00
parent 0aa1a526b2
commit 93e1fad88e
2 changed files with 16 additions and 7 deletions
+13 -6
View File
@@ -47,6 +47,14 @@ defmodule MusicLibrary.Records do
Repo.aggregate(search, :count)
end
defmacro order_alphabetically do
quote do
fragment(
"unaccent(json_extract(artists, '$[0].sort_name')) COLLATE NOCASE ASC, unaccent(title) COLLATE NOCASE ASC"
)
end
end
defp build_search(initial_search, query, order \\ :alphabetical) do
{:ok, parsed_query} = SearchParser.parse(query)
@@ -54,15 +62,14 @@ defmodule MusicLibrary.Records do
case order do
:alphabetical ->
initial_search
|> order_by(
fragment(
"unaccent(json_extract(artists, '$[0].sort_name')) COLLATE NOCASE ASC, unaccent(title) COLLATE NOCASE ASC"
)
)
|> order_by(order_alphabetically())
:purchase ->
initial_search
|> order_by([r], {:desc, r.purchased_at})
|> order_by([r], [
{:desc, r.purchased_at},
order_alphabetically()
])
end
Enum.reduce(parsed_query, search_with_order, fn