]> Untitled Git - lemmy.git/blob - migrations/2023-06-19-120700_no_double_deletion/up.sql
Revert "Attempt to fix CI building wrong commits (#3830)"
[lemmy.git] / migrations / 2023-06-19-120700_no_double_deletion / up.sql
1 -- Deleting after removing should not decrement the count twice.
2 CREATE OR REPLACE FUNCTION was_removed_or_deleted (TG_OP text, OLD record, NEW record)
3     RETURNS boolean
4     LANGUAGE plpgsql
5     AS $$
6 BEGIN
7     IF (TG_OP = 'INSERT') THEN
8         RETURN FALSE;
9     END IF;
10     IF (TG_OP = 'DELETE' AND OLD.deleted = 'f' AND OLD.removed = 'f') THEN
11         RETURN TRUE;
12     END IF;
13     RETURN TG_OP = 'UPDATE'
14         AND ((OLD.deleted = 'f'
15                 AND NEW.deleted = 't')
16             OR (OLD.removed = 'f'
17                 AND NEW.removed = 't'));
18 END
19 $$;
20
21 -- Recalculate proper comment count.
22 UPDATE
23     person_aggregates
24 SET
25     comment_count = cnt.count
26 FROM (
27     SELECT
28         creator_id,
29         count(*) AS count
30     FROM
31         comment
32     WHERE
33         deleted = 'f'
34         AND removed = 'f'
35     GROUP BY
36         creator_id) cnt
37 WHERE
38     person_aggregates.person_id = cnt.creator_id;
39
40 -- Recalculate proper comment score.
41 UPDATE
42     person_aggregates ua
43 SET
44     comment_score = cd.score
45 FROM (
46     SELECT
47         u.id AS creator_id,
48         coalesce(0, sum(cl.score)) AS score
49         -- User join because comments could be empty
50     FROM
51         person u
52     LEFT JOIN comment c ON u.id = c.creator_id
53         AND c.deleted = 'f'
54         AND c.removed = 'f'
55     LEFT JOIN comment_like cl ON c.id = cl.comment_id
56 GROUP BY
57     u.id) cd
58 WHERE
59     ua.person_id = cd.creator_id;
60
61 -- Recalculate proper post count.
62 UPDATE
63     person_aggregates
64 SET
65     post_count = cnt.count
66 FROM (
67     SELECT
68         creator_id,
69         count(*) AS count
70     FROM
71         post
72     WHERE
73         deleted = 'f'
74         AND removed = 'f'
75     GROUP BY
76         creator_id) cnt
77 WHERE
78     person_aggregates.person_id = cnt.creator_id;
79
80 -- Recalculate proper post score.
81 UPDATE
82     person_aggregates ua
83 SET
84     post_score = pd.score
85 FROM (
86     SELECT
87         u.id AS creator_id,
88         coalesce(0, sum(pl.score)) AS score
89         -- User join because posts could be empty
90     FROM
91         person u
92     LEFT JOIN post p ON u.id = p.creator_id
93         AND p.deleted = 'f'
94         AND p.removed = 'f'
95     LEFT JOIN post_like pl ON p.id = pl.post_id
96 GROUP BY
97     u.id) pd
98 WHERE
99     ua.person_id = pd.creator_id;
100