summaryrefslogtreecommitdiff
path: root/priv/repo/migrations/20191128153944_fix_missing_following_count.exs
blob: 3236de7a44514bd9384c9746490e585ff44fd6d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
defmodule Pleroma.Repo.Migrations.FixMissingFollowingCount do
  use Ecto.Migration

  def up do
    """
    UPDATE
      users
    SET
      following_count = sub.count
    FROM
      (
        SELECT
          users.id AS sub_id
          ,COUNT (following_relationships.id)
        FROM
          following_relationships
          ,users
        WHERE
          users.id = following_relationships.follower_id
        AND following_relationships.state = 'accept'
        GROUP BY
          users.id
      ) AS sub
    WHERE
      users.id = sub.sub_id
    AND users.local = TRUE
    ;
    """
    |> execute()

    """
    UPDATE
      users
    SET
      following_count = 0
    WHERE
      following_count IS NULL
    """
    |> execute()

    execute("ALTER TABLE users
      ALTER COLUMN following_count SET DEFAULT 0,
      ALTER COLUMN following_count SET NOT NULL
    ")
  end

  def down do
    execute("ALTER TABLE users
      ALTER COLUMN following_count DROP DEFAULT,
      ALTER COLUMN following_count DROP NOT NULL
    ")
  end
end