BEGIN; CREATE TABLE "attachment_outbox" ( "attachment_id" UUID NOT NULL REFERENCES "attachments" ("id") ON DELETE RESTRICT ON UPDATE CASCADE, "generation" INTEGER NOT NULL, "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY ("attachment_id", "generation") ); CREATE INDEX "attachment_outbox_created_at_attachment_id_generation_idx" ON "attachment_outbox" ("created_at", "attachment_id", "generation"); -- Insertion and explicit replay both enqueue work in the surrounding transaction. CREATE FUNCTION enqueue_attachment_outbox() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.status = 'queued' AND (TG_OP = 'INSERT' OR NEW.generation IS DISTINCT FROM OLD.generation) THEN INSERT INTO attachment_outbox (attachment_id, generation) VALUES (NEW.id, NEW.generation); END IF; RETURN NEW; END; $$; CREATE TRIGGER attachment_outbox_enqueue AFTER INSERT OR UPDATE OF generation ON "attachments" FOR EACH ROW EXECUTE FUNCTION enqueue_attachment_outbox(); INSERT INTO "attachment_outbox" ("attachment_id", "generation", "created_at") SELECT "id", "generation", "created_at" FROM "attachments" WHERE "status" = 'queued' AND "published_at" IS NULL; DROP INDEX "attachments_pending_publish_idx"; COMMIT;