Apply suggestion to priv/repo/migrations/20200406100225_users_add_emoji.exs
[akkoma] / priv / repo / migrations / 20200406100225_users_add_emoji.exs
1 defmodule Pleroma.Repo.Migrations.UsersPopulateEmoji do
2 use Ecto.Migration
3
4 import Ecto.Query
5
6 alias Pleroma.User
7 alias Pleroma.Repo
8
9 def up do
10 execute("ALTER TABLE users ALTER COLUMN emoji SET DEFAULT '{}'::jsonb")
11 execute("UPDATE users SET emoji = DEFAULT WHERE emoji = '[]'::jsonb")
12
13 from(u in User)
14 |> select([u], struct(u, [:id, :ap_id, :source_data]))
15 |> Repo.stream()
16 |> Enum.each(fn user ->
17 emoji =
18 user.source_data
19 |> Map.get("tag", [])
20 |> Enum.filter(fn
21 %{"type" => "Emoji"} -> true
22 _ -> false
23 end)
24 |> Enum.reduce(%{}, fn %{"icon" => %{"url" => url}, "name" => name}, acc ->
25 Map.put(acc, String.trim(name, ":"), url)
26 end)
27
28 user
29 |> Ecto.Changeset.cast(%{emoji: emoji}, [:emoji])
30 |> Repo.update()
31 end)
32 end
33
34 def down do
35 execute("ALTER TABLE users ALTER COLUMN emoji SET DEFAULT '[]'::jsonb")
36 execute("UPDATE users SET emoji = DEFAULT WHERE emoji = '{}'::jsonb")
37 end
38 end