First
[anni] / priv / repo / migrations / 20200415181818_update_markers.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.UpdateMarkers do
6   use Ecto.Migration
7   import Ecto.Query
8   alias Pleroma.Repo
9
10   def up do
11     update_markers()
12   end
13
14   def down do
15     :ok
16   end
17
18   defp update_markers do
19     now = NaiveDateTime.utc_now()
20
21     markers_attrs =
22       from(q in "notifications",
23         select: %{
24           timeline: "notifications",
25           user_id: q.user_id,
26           last_read_id:
27             type(fragment("MAX( CASE WHEN seen = true THEN id ELSE null END )"), :string)
28         },
29         group_by: [q.user_id]
30       )
31       |> Repo.all()
32       |> Enum.map(fn %{last_read_id: last_read_id} = attrs ->
33         attrs
34         |> Map.put(:last_read_id, last_read_id || "")
35         |> Map.put_new(:inserted_at, now)
36         |> Map.put_new(:updated_at, now)
37       end)
38
39     markers_attrs
40     |> Enum.chunk_every(1000)
41     |> Enum.each(fn markers_attrs_chunked ->
42       Repo.insert_all("markers", markers_attrs_chunked,
43         on_conflict: {:replace, [:last_read_id]},
44         conflict_target: [:user_id, :timeline]
45       )
46     end)
47   end
48 end