kemono2/db/migrations/20231014_02_2a1d34-post-added-max.py
2024-07-04 22:08:17 +02:00

43 lines
1.1 KiB
Python

"""
This didnt exist in yoyo migrations but we had it in production, mock this migration in production
"""
from yoyo import step
__depends__ = {"20210118_01_1Jlkq-add-unique-constraint-to-service-and-post-fields"}
steps = [
step(
"""
CREATE TABLE IF NOT EXISTS public.posts_added_max (
"user" varchar NOT NULL,
service varchar NOT NULL,
added timestamp NOT NULL,
CONSTRAINT posts_added_max_pkey PRIMARY KEY ("user", service)
);
"""
),
step(
"""
CREATE OR REPLACE FUNCTION public.posts_added_max() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO posts_added_max AS pam ("user", service, added)
SELECT "user", service, max(added) AS added FROM posts
WHERE posts.service = NEW.service
AND posts."user" = NEW."user"
GROUP BY "user", service
ON CONFLICT (service, "user")
DO UPDATE SET added = EXCLUDED.added
WHERE EXCLUDED.added > pam.added;
RETURN NULL;
END;
$$;
"""
),
step(
"CREATE TRIGGER posts_added_max AFTER INSERT OR UPDATE ON public.posts FOR EACH ROW EXECUTE FUNCTION public.posts_added_max();"
),
]