c9bc890aa4a6ae7af99377ab0c2728497fd048ae
[akkoma] / priv / repo / migrations / 20191008132217_migrate_following_relationships.exs
1 defmodule Pleroma.Repo.Migrations.MigrateFollowingRelationships do
2 use Ecto.Migration
3
4 def change do
5 execute(import_following_from_users(), "")
6 execute(import_following_from_activities(), restore_following_column())
7 end
8
9 defp import_following_from_users do
10 """
11 INSERT INTO following_relationships (follower_id, following_id, state, inserted_at, updated_at)
12 SELECT
13 relations.follower_id,
14 following.id,
15 'accept',
16 now(),
17 now()
18 FROM (
19 SELECT
20 users.id AS follower_id,
21 unnest(users.following) AS following_ap_id
22 FROM
23 users
24 WHERE
25 users.following != '{}'
26 AND users.local = false OR users.local = true AND users.email IS NOT NULL -- Exclude `internal/fetch` and `relay`
27 ) AS relations
28 JOIN users AS "following" ON "following".follower_address = relations.following_ap_id
29
30 WHERE relations.follower_id != following.id
31 ON CONFLICT DO NOTHING
32 """
33 end
34
35 defp import_following_from_activities do
36 """
37 INSERT INTO
38 following_relationships (
39 follower_id,
40 following_id,
41 state,
42 inserted_at,
43 updated_at
44 )
45 SELECT
46 followers.id,
47 following.id,
48 activities.data ->> 'state',
49 (activities.data ->> 'published') :: timestamp,
50 now()
51 FROM
52 activities
53 JOIN users AS followers ON (activities.actor = followers.ap_id)
54 JOIN users AS following ON (activities.data ->> 'object' = following.ap_id)
55 WHERE
56 activities.data ->> 'type' = 'Follow'
57 AND activities.data ->> 'state' IN ('accept', 'pending', 'reject')
58 AND NOT (followers.info ? 'deactivated' AND followers.info -> 'deactivated' @> 'true')
59 ORDER BY activities.updated_at DESC
60 ON CONFLICT DO NOTHING
61 """
62 end
63
64 defp restore_following_column do
65 """
66 UPDATE
67 users
68 SET
69 following = following_query.following_array,
70 updated_at = now()
71 FROM (
72 SELECT
73 follwer.id AS follower_id,
74 CASE follwer.local
75 WHEN TRUE THEN
76 array_prepend(follwer.follower_address, array_agg(following.follower_address))
77 ELSE
78 array_agg(following.follower_address)
79 END AS following_array
80 FROM
81 following_relationships
82 JOIN users AS follwer ON follwer.id = following_relationships.follower_id
83 JOIN users AS FOLLOWING ON following.id = following_relationships.following_id
84 GROUP BY
85 follwer.id) AS following_query
86 WHERE
87 following_query.follower_id = users.id
88 """
89 end
90 end