-- AlterTable ALTER TABLE "PublishedRule" ADD COLUMN "communityLocation" TEXT; ALTER TABLE "PublishedRule" ADD COLUMN "orgType" TEXT; ALTER TABLE "PublishedRule" ADD COLUMN "followUpEmailSentAt" TIMESTAMP(3); -- Copy place and group type already stored on the published document. UPDATE "PublishedRule" SET "communityLocation" = LEFT( NULLIF( BTRIM(REGEXP_REPLACE(COALESCE("document"->>'communityLocation', ''), '[[:space:]]+', ' ', 'g')), '' ), 200 ), "orgType" = CASE WHEN BTRIM(COALESCE("document"->>'orgType', '')) IN ( 'dao', 'forProfit', 'mutualAid', 'nonprofit', 'openSource', 'workersCoop' ) THEN BTRIM("document"->>'orgType') ELSE NULL END WHERE jsonb_typeof("document") = 'object'; -- Close follow-ups for Rules finished more than seven days before this mail -- existed. Newer unsent rows stay eligible until a run claims them. UPDATE "PublishedRule" SET "followUpEmailSentAt" = CURRENT_TIMESTAMP WHERE "createdAt" < CURRENT_TIMESTAMP - INTERVAL '7 days'; -- CreateIndex CREATE INDEX "PublishedRule_orgType_communityLocation_idx" ON "PublishedRule"("orgType", "communityLocation"); -- CreateIndex CREATE INDEX "PublishedRule_followUpEmailSentAt_createdAt_idx" ON "PublishedRule"("followUpEmailSentAt", "createdAt");