move to 2.5.5
[anni] / priv / repo / migrations / 20210128092834_remove_duplicates_from_activity_expiration_queue.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Repo.Migrations.RemoveDuplicatesFromActivityExpirationQueue do
6   use Ecto.Migration
7
8   import Ecto.Query, only: [from: 2]
9
10   def up do
11     duplicate_ids =
12       from(j in Oban.Job,
13         where: j.queue == "activity_expiration",
14         where: j.worker == "Pleroma.Workers.PurgeExpiredActivity",
15         where: j.state == "scheduled",
16         select:
17           {fragment("(?)->>'activity_id'", j.args), fragment("array_agg(?)", j.id), count(j.id)},
18         group_by: fragment("(?)->>'activity_id'", j.args),
19         having: count(j.id) > 1
20       )
21       |> Pleroma.Repo.all()
22       |> Enum.map(fn {_, ids, _} ->
23         max_id = Enum.max(ids)
24         List.delete(ids, max_id)
25       end)
26       |> List.flatten()
27
28     from(j in Oban.Job, where: j.id in ^duplicate_ids)
29     |> Pleroma.Repo.delete_all()
30   end
31
32   def down, do: :noop
33 end