Merge pull request 'Manually define PATH for Arch Linux users in systemd unit' (...
[akkoma] / priv / repo / migrations / 20200415181818_update_markers.exs
1 defmodule Pleroma.Repo.Migrations.UpdateMarkers do
2 use Ecto.Migration
3 import Ecto.Query
4 alias Pleroma.Repo
5
6 def up do
7 update_markers()
8 end
9
10 def down do
11 :ok
12 end
13
14 defp update_markers do
15 now = NaiveDateTime.utc_now()
16
17 markers_attrs =
18 from(q in "notifications",
19 select: %{
20 timeline: "notifications",
21 user_id: q.user_id,
22 last_read_id:
23 type(fragment("MAX( CASE WHEN seen = true THEN id ELSE null END )"), :string)
24 },
25 group_by: [q.user_id]
26 )
27 |> Repo.all()
28 |> Enum.map(fn %{last_read_id: last_read_id} = attrs ->
29 attrs
30 |> Map.put(:last_read_id, last_read_id || "")
31 |> Map.put_new(:inserted_at, now)
32 |> Map.put_new(:updated_at, now)
33 end)
34
35 markers_attrs
36 |> Enum.chunk_every(1000)
37 |> Enum.each(fn markers_attrs_chunked ->
38 Repo.insert_all("markers", markers_attrs_chunked,
39 on_conflict: {:replace, [:last_read_id]},
40 conflict_target: [:user_id, :timeline]
41 )
42 end)
43 end
44 end