First
[anni] / priv / repo / migrations / 20191128153944_fix_missing_following_count.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.FixMissingFollowingCount do
6   use Ecto.Migration
7
8   def up do
9     """
10     UPDATE
11       users
12     SET
13       following_count = sub.count
14     FROM
15       (
16         SELECT
17           users.id AS sub_id
18           ,COUNT (following_relationships.id)
19         FROM
20           following_relationships
21           ,users
22         WHERE
23           users.id = following_relationships.follower_id
24         AND following_relationships.state = 'accept'
25         GROUP BY
26           users.id
27       ) AS sub
28     WHERE
29       users.id = sub.sub_id
30     AND users.local = TRUE
31     ;
32     """
33     |> execute()
34
35     """
36     UPDATE
37       users
38     SET
39       following_count = 0
40     WHERE
41       following_count IS NULL
42     """
43     |> execute()
44
45     execute("ALTER TABLE users
46       ALTER COLUMN following_count SET DEFAULT 0,
47       ALTER COLUMN following_count SET NOT NULL
48     ")
49   end
50
51   def down do
52     execute("ALTER TABLE users
53       ALTER COLUMN following_count DROP DEFAULT,
54       ALTER COLUMN following_count DROP NOT NULL
55     ")
56   end
57 end