lemmy/replaceable_schema.sql

50 lines
1.8 KiB
MySQL
Raw Normal View History

2023-12-23 00:29:04 +00:00
-- This sets up the `r` schema, which contains things that can be safely dropped and replaced instead of being
-- changed using migrations.
2023-12-22 22:47:21 +00:00
--
2023-12-23 00:29:04 +00:00
-- Statements in this file may not create or modify things outside of the `r` schema (indicated by the `r.` prefix),
-- except for these things, which are associated with something other than a schema (usually a table):
2023-12-22 23:16:05 +00:00
-- * A trigger if the function name after `EXECUTE FUNCTION` is in `r` (dropping `r` drops the trigger)
--
2023-12-23 00:29:04 +00:00
-- The default schema is not temporarily set to `r` because it would not affect some things (such as triggers) which
2023-12-22 23:22:53 +00:00
-- makes it hard to tell if the rule above is being followed.
--
2023-12-23 00:29:04 +00:00
-- If you add something here that depends on something (such as a table) created in a new migration, then down.sql must use
-- `CASCADE` when dropping it. This doesn't need to be fixed in old migrations because the "replaceable-schema" migration
-- runs `DROP SCHEMA IF EXISTS r CASCADE` in down.sql.
2023-12-22 22:47:21 +00:00
BEGIN;
DROP SCHEMA IF EXISTS r CASCADE;
2023-12-22 23:16:05 +00:00
CREATE SCHEMA r;
2023-12-22 22:47:21 +00:00
2023-12-23 06:08:40 +00:00
-- These triggers create and update rows in each aggregates table to match its associated table's rows.
-- Deleting rows and updating IDs are already handled by `CASCADE` in foreign key constraints.
2023-12-22 22:47:21 +00:00
2023-12-23 06:08:40 +00:00
CREATE FUNCTION r.upsert_community_aggregates_from_community () RETURNS trigger
2023-12-22 22:47:21 +00:00
LANGUAGE plpgsql
AS $$
BEGIN
2023-12-23 06:08:40 +00:00
INSERT INTO
community_aggregates (community_id, published)
2023-12-22 22:47:21 +00:00
SELECT
community_id,
2023-12-23 06:08:40 +00:00
published
2023-12-22 22:47:21 +00:00
FROM
2023-12-23 06:08:40 +00:00
new_community
ON CONFLICT DO UPDATE SET
published = excluded.published;
2023-12-22 22:47:21 +00:00
RETURN NULL;
END
$$;
2023-12-23 06:08:40 +00:00
CREATE TRIGGER upsert_aggregates
AFTER INSERT OR UPDATE OF published ON community
REFERENCING NEW TABLE AS new_community
FOR EACH STATEMENT
EXECUTE FUNCTION r.upsert_community_aggregates_from_community;
2023-12-22 22:47:21 +00:00
COMMIT;