Update replaceable_schema.sql

This commit is contained in:
dullbananas 2023-12-23 13:31:57 -07:00 committed by GitHub
parent e330194b1c
commit 1cd6ed14ae
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -220,39 +220,44 @@ CREATE TRIGGER aggregates
-- These triggers update aggregates in response to votes. -- These triggers update aggregates in response to votes.
CREATE FUNCTION comment_aggregates_from_like() CREATE PROCEDURE aggregates_from_like (target_name text)
LANGUAGE plpgsql
AS $a$
BEGIN
EXECUTE format($b$
CREATE FUNCTION %1$s_aggregates_from_like ()
RETURNS trigger RETURNS trigger
LANGUAGE plpgsql LANGUAGE plpgsql
AS $$ AS $$
BEGIN BEGIN
WITH WITH
any_like (comment_id, score, added) AS ( any_like (target_id, score, added) AS (
SELECT SELECT
comment_id, %1$s_id,
score, score,
-1 -1
FROM FROM
old_like old_like
UNION ALL UNION ALL
SELECT SELECT
comment_id, %1$s_id,
score, score,
1 1
FROM FROM
new_like new_like
), ),
added_to_comment (comment_id, added_upvotes, added_downvotes) AS ( added_to_target (target_id, added_upvotes, added_downvotes) AS (
SELECT SELECT
comment_id, target_id,
sum(added) FILTER (WHERE score = 1), sum(added) FILTER (WHERE score = 1),
sum(added) FILTER (WHERE score = -1) sum(added) FILTER (WHERE score = -1)
FROM FROM
any_like any_like
GROUP BY GROUP BY
comment_id target_id
) )
UPDATE UPDATE
comment_aggregates %1$s_aggregates AS aggregates
SET SET
score = score + added_upvotes - added_downvotes, score = score + added_upvotes - added_downvotes,
upvotes = upvotes + added_upvotes, upvotes = upvotes + added_upvotes,
@ -262,13 +267,21 @@ BEGIN
(downvotes + added_downvotes)::numeric (downvotes + added_downvotes)::numeric
) )
FROM FROM
added_to_comment added_to_target
WHERE WHERE
comment_aggregates.comment_id = added_to_comment.comment_id; aggregates.comment_id = added_to_comment.comment_id;
RETURN NULL; RETURN NULL;
END END
$$; $$;
$b$,
target_name);
END
$a$;
CALL aggregates_from_like ('comment');
CALL aggregates_from_like ('post');
COMMIT; COMMIT;