move to 2.5.5
[anni] / priv / repo / migrations / 20181218172826_users_and_activities_flake_id.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.UsersAndActivitiesFlakeId do
6   use Ecto.Migration
7   alias Pleroma.Clippy
8   require Integer
9   import Ecto.Query
10   alias Pleroma.Repo
11
12   # This migrates from int serial IDs to custom Flake:
13   #   1- create a temporary uuid column
14   #   2- fill this column with compatibility ids (see below)
15   #   3- remove pkeys constraints
16   #   4- update relation pkeys with the new ids
17   #   5- rename the temporary column to id
18   #   6- re-create the constraints
19   def up do
20     # Old serial int ids are transformed to 128bits with extra padding.
21     # The application (in `Pleroma.FlakeId`) handles theses IDs properly as integers; to keep compatibility
22     # with previously issued ids.
23     # execute "update activities set external_id = CAST( LPAD( TO_HEX(id), 32, '0' ) AS uuid);"
24     # execute "update users set external_id = CAST( LPAD( TO_HEX(id), 32, '0' ) AS uuid);"
25
26     clippy = start_clippy_heartbeats()
27
28     # Lock both tables to avoid a running server to meddling with our transaction
29     execute("LOCK TABLE activities;")
30     execute("LOCK TABLE users;")
31
32     execute("""
33       ALTER TABLE activities
34       DROP CONSTRAINT activities_pkey CASCADE,
35       ALTER COLUMN id DROP default,
36       ALTER COLUMN id SET DATA TYPE uuid USING CAST( LPAD( TO_HEX(id), 32, '0' ) AS uuid),
37       ADD PRIMARY KEY (id);
38     """)
39
40     execute("""
41     ALTER TABLE users
42     DROP CONSTRAINT users_pkey CASCADE,
43     ALTER COLUMN id DROP default,
44     ALTER COLUMN id SET DATA TYPE uuid USING CAST( LPAD( TO_HEX(id), 32, '0' ) AS uuid),
45     ADD PRIMARY KEY (id);
46     """)
47
48     execute(
49       "UPDATE users SET info = jsonb_set(info, '{pinned_activities}', array_to_json(ARRAY(select jsonb_array_elements_text(info->'pinned_activities')))::jsonb);"
50     )
51
52     # Fkeys:
53     # Activities - Referenced by:
54     #   TABLE "notifications" CONSTRAINT "notifications_activity_id_fkey" FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE
55     # Users - Referenced by:
56     #  TABLE "filters" CONSTRAINT "filters_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
57     #  TABLE "lists" CONSTRAINT "lists_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
58     #  TABLE "notifications" CONSTRAINT "notifications_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
59     #  TABLE "oauth_authorizations" CONSTRAINT "oauth_authorizations_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
60     #  TABLE "oauth_tokens" CONSTRAINT "oauth_tokens_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
61     #  TABLE "password_reset_tokens" CONSTRAINT "password_reset_tokens_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
62     #  TABLE "push_subscriptions" CONSTRAINT "push_subscriptions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
63     #  TABLE "websub_client_subscriptions" CONSTRAINT "websub_client_subscriptions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id)
64
65     execute("""
66     ALTER TABLE notifications
67     ALTER COLUMN activity_id SET DATA TYPE uuid USING CAST( LPAD( TO_HEX(activity_id), 32, '0' ) AS uuid),
68     ADD CONSTRAINT notifications_activity_id_fkey FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE;
69     """)
70
71     for table <-
72           ~w(notifications filters lists oauth_authorizations oauth_tokens password_reset_tokens push_subscriptions websub_client_subscriptions) do
73       execute("""
74       ALTER TABLE #{table}
75       ALTER COLUMN user_id SET DATA TYPE uuid USING CAST( LPAD( TO_HEX(user_id), 32, '0' ) AS uuid),
76       ADD CONSTRAINT #{table}_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
77       """)
78     end
79
80     flush()
81
82     stop_clippy_heartbeats(clippy)
83   end
84
85   def down, do: :ok
86
87   defp start_clippy_heartbeats() do
88     count = from(a in "activities", select: count(a.id)) |> Repo.one!()
89
90     if count > 5000 do
91       heartbeat_interval = :timer.minutes(2) + :timer.seconds(30)
92
93       all_tips =
94         Clippy.tips() ++
95           [
96             "The migration is still running, maybe it's time for another “tea”?",
97             "Happy rabbits practice a cute behavior known as a\n“binky:” they jump up in the air\nand twist\nand spin around!",
98             "Nothing and everything.\n\nI still work.",
99             "Pleroma runs on a Raspberry Pi!\n\n  … but this migration will take forever if you\nactually run on a raspberry pi",
100             "Status? Stati? Post? Note? Toot?\nRepeat? Reboost? Boost? Retweet? Retoot??\n\nI-I'm confused."
101           ]
102
103       heartbeat = fn heartbeat, runs, all_tips, tips ->
104         tips =
105           if Integer.is_even(runs) do
106             tips = if tips == [], do: all_tips, else: tips
107             [tip | tips] = Enum.shuffle(tips)
108             Clippy.puts(tip)
109             tips
110           else
111             IO.puts(
112               "\n -- #{DateTime.to_string(DateTime.utc_now())} Migration still running, please wait…\n"
113             )
114
115             tips
116           end
117
118         :timer.sleep(heartbeat_interval)
119         heartbeat.(heartbeat, runs + 1, all_tips, tips)
120       end
121
122       Clippy.puts([
123         [:red, :bright, "It looks like you are running an older instance!"],
124         [""],
125         [:bright, "This migration may take a long time", :reset, " -- so you probably should"],
126         ["go drink a cofe, or a tea, or a beer, a whiskey, a vodka,"],
127         ["while it runs to deal with your temporary fediverse pause!"]
128       ])
129
130       :timer.sleep(heartbeat_interval)
131       spawn_link(fn -> heartbeat.(heartbeat, 1, all_tips, []) end)
132     end
133   end
134
135   defp stop_clippy_heartbeats(pid) do
136     if pid do
137       Process.unlink(pid)
138       Process.exit(pid, :kill)
139       Clippy.puts([[:green, :bright, "Hurray!!", "", "", "Migration completed!"]])
140     end
141   end
142 end