Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
-- Absences become rows of their own, belonging to the person: their record when the account that declared them has
-- one, the account otherwise. No change in what anyone sees: every reader still reads the day-off events, and the new
-- image writes both until the readers move over. Each row keeps the event it was copied from until the events are
-- dropped.
--
-- During the rollout the previous image keeps serving: it declares and deletes day-off events without their rows (a
-- later migration copies the missing ones and drops the rows whose event is gone, before the events are), and it
-- cannot delete an account without a record that has absences — its rows name the account, which is Restrict. The new
-- image lets go of them first.
--
-- 1. The table, its CHECK and the standard tenant policy.
CREATE TABLE IF NOT EXISTS "Absence" (
"id" SERIAL NOT NULL,
"startDate" TIMESTAMP(3) NOT NULL,
"endDate" TIMESTAMP(3) NOT NULL,
"note" TEXT NOT NULL DEFAULT '',
"memberId" INTEGER,
"accountId" INTEGER,
"legacyEventId" INTEGER,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"congregationId" INTEGER NOT NULL,

CONSTRAINT "Absence_pkey" PRIMARY KEY ("id")
);

-- Somebody's: the person's record, or the account that declared it when there is none.
ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_owner_check";
ALTER TABLE "Absence" ADD CONSTRAINT "Absence_owner_check" CHECK ("memberId" IS NOT NULL OR "accountId" IS NOT NULL);

CREATE UNIQUE INDEX IF NOT EXISTS "Absence_legacyEventId_key" ON "Absence"("legacyEventId");
CREATE UNIQUE INDEX IF NOT EXISTS "Absence_id_congregationId_key" ON "Absence"("id", "congregationId");
CREATE INDEX IF NOT EXISTS "Absence_congregationId_startDate_idx" ON "Absence"("congregationId", "startDate");
CREATE INDEX IF NOT EXISTS "Absence_memberId_idx" ON "Absence"("memberId");
CREATE INDEX IF NOT EXISTS "Absence_accountId_idx" ON "Absence"("accountId");

ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_memberId_fkey";
ALTER TABLE "Absence" ADD CONSTRAINT "Absence_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- Restrict: deleting an account lets go of its absences explicitly (releaseAccountEvents); any other path fails
-- clearly instead of breaking the CHECK.
ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_accountId_fkey";
ALTER TABLE "Absence" ADD CONSTRAINT "Absence_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "UserAccount"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_congregationId_fkey";
ALTER TABLE "Absence" ADD CONSTRAINT "Absence_congregationId_fkey" FOREIGN KEY ("congregationId") REFERENCES "Congregation"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "Absence" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "Absence" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS tenant_isolation ON "Absence";
CREATE POLICY tenant_isolation ON "Absence" FOR ALL
USING (
CASE
WHEN NULLIF(current_setting('app.congregation_id', true), '') IS NULL THEN true
ELSE "congregationId" = current_setting('app.congregation_id', true)::int
END
);

-- 2. One row per day-off event, as it is: its dates and note, the account that declared it, that account's record when
-- it has one. No path leaves a day-off without its account (deleting one takes its absences or is refused); one
-- without would break the CHECK, so it is left out. Idempotent: run again, as the later catch-up does, it copies
-- only what it has not copied yet.
INSERT INTO "Absence" ("startDate", "endDate", "note", "memberId", "accountId", "legacyEventId", "createdAt", "congregationId")
SELECT event."startDate", event."endDate", event."description", account."memberId", event."createdById", event."id",
event."createdAt", event."congregationId"
FROM "Event" AS event
JOIN "EventTemplate" AS template
ON template."id" = event."templateId" AND template."congregationId" = event."congregationId" AND template."key" = 'day-off'
JOIN "UserAccount" AS account ON account."id" = event."createdById"
ON CONFLICT ("legacyEventId") DO NOTHING;
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
-- The empty meetings the previous image created while 20261119120000_add_event_origin rolled out get their origin.
-- Contract: no event someone made or touched changes.
--
-- That migration gave « job » to the empty meetings that existed, but the running image kept serving until the new one
-- rolled out, and its recurring-events job wrote the column's default, « manual »: those meetings stopped moving with
-- their template. Its backfill cannot simply run again: since then, deleting an account clears the author of what it
-- made, and a hand-made event left without an author looks the same.
--
-- Only events that are all of: no author, nothing on them (no part, no service, no attendance), of a template (the job
-- only creates those), still
-- « manual », created after that migration finished, and never written since (`updatedAt` within seconds of
-- `createdAt`) — clearing an author is a write, so a hand-made event whose account went keeps « manual ».
UPDATE "Event" AS event
SET "origin" = 'job'
WHERE event."origin" = 'manual'
AND event."createdById" IS NULL
AND event."templateId" IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM "EventPart" part WHERE part."eventId" = event."id")
AND NOT EXISTS (SELECT 1 FROM "EventServicePart" service WHERE service."eventId" = event."id")
AND NOT EXISTS (SELECT 1 FROM "Attendance" attendance WHERE attendance."eventId" = event."id")
-- max() over finished, not rolled-back rows: a migration that failed and was applied again leaves two rows. A
-- database with none (baselined history) gets no repair rather than a guess.
AND event."createdAt" >= (
SELECT max(m."finished_at") FROM "_prisma_migrations" AS m
WHERE m."migration_name" = '20261119120000_add_event_origin'
AND m."finished_at" IS NOT NULL
AND m."rolled_back_at" IS NULL
)
AND event."updatedAt" <= event."createdAt" + INTERVAL '5 seconds';
243 changes: 243 additions & 0 deletions app/database/migrations/add-absences.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { PrismaPg } from '@prisma/adapter-pg'
import { afterAll, describe, expect, it } from 'vitest'
import { PrismaClient } from '~/database/generated/client'

// Runs against DB_URL rather than DB_RUNTIME_URL: a migration executes as the schema owner. Its statements are read from
// the shipped file and run inside a rolled-back transaction.
const adapter = new PrismaPg({ connectionString: process.env.DB_URL, max: 3, connectionTimeoutMillis: 5000 })
const testDb = new PrismaClient({ adapter })

const STATEMENTS = readFileSync(join(import.meta.dirname, '20261120090000_add_absences', 'migration.sql'), 'utf8')
.split('\n')
.filter(line => !line.trimStart().startsWith('--'))
.join('\n')
.split(';')
.map(statement => statement.trim())
.filter(statement => statement.length > 0)

class Rollback extends Error {}

interface AbsenceRow {
legacyEventId: number | null
startDate: Date
endDate: Date
note: string
memberId: number | null
accountId: number | null
createdAt: Date
}

interface Result {
ids: Record<string, number>
first: AbsenceRow[]
second: AbsenceRow[]
/** The other congregation's rows after both runs, by event: its own absence, and nothing for the stray one. */
otherCongregation: { legacyEventId: number | null; congregationId: number }[]
ownerlessRefused: boolean
}

let memo: Promise<Result> | undefined

/**
* Day-off events as the previous image leaves them, at the moment the migration runs: some declared from an account
* with a record, one from an account without, a meeting that is no absence, and one absence already copied — then a
* new absence declared before the second run.
*/
function snapshot(): Promise<Result> {
memo ??= (async () => {
let result: Result | undefined
try {
await testDb.$transaction(async tx => {
const stamp = `absences-${process.pid}-${globalThis.performance.now().toString().replace('.', '')}`
const congregationId = (await tx.congregation.create({ data: { name: stamp, slug: stamp, active: true } })).id
const dayOff = await tx.eventTemplate.create({ data: { name: 'Absence', key: 'day-off', congregationId } })
const meeting = await tx.eventTemplate.create({
data: { name: 'Réunion', key: `midweek-${stamp}`, congregationId },
})
const member = await tx.member.create({ data: { firstname: 'Paul', lastname: 'MARTIN', congregationId } })
const withRecord = await tx.userAccount.create({
data: { email: `paul-${stamp}@test.com`, password: 'x', memberId: member.id, congregationId },
})
const withoutRecord = await tx.userAccount.create({
data: { email: `sans-${stamp}@test.com`, password: 'x', congregationId },
})
const event = (
templateId: number,
createdById: number | null,
day: string,
description = '',
inCongregation = congregationId,
) =>
tx.event.create({
data: {
name: 'Absence',
description,
startDate: new Date(`${day}T00:00:00Z`),
endDate: new Date(`${day}T23:59:00Z`),
status: 'released',
templateId,
createdById,
createdAt: new Date('2026-10-01T08:00:00Z'),
congregationId: inCongregation,
},
})
// Another congregation, with its own absence template and one genuine absence.
const otherId = (
await tx.congregation.create({ data: { name: `${stamp}-b`, slug: `${stamp}-b`, active: true } })
).id
const otherDayOff = await tx.eventTemplate.create({
data: { name: 'Absence', key: 'day-off', congregationId: otherId },
})
const otherAccount = await tx.userAccount.create({
data: { email: `autre-${stamp}@test.com`, password: 'x', congregationId: otherId },
})

const ids: Record<string, number> = {
withRecord: (await event(dayOff.id, withRecord.id, '2027-01-04', 'Vacances')).id,
withoutRecord: (await event(dayOff.id, withoutRecord.id, '2027-01-11')).id,
meeting: (await event(meeting.id, withRecord.id, '2027-01-12')).id,
copied: (await event(dayOff.id, withRecord.id, '2027-02-01')).id,
// No author: it would break the CHECK, so it is left out (no path leaves one today).
noAuthor: (await event(dayOff.id, null, '2027-02-08')).id,
// An event of this congregation pointing at the other one's absence template: not an absence here.
stray: (await event(otherDayOff.id, withRecord.id, '2027-02-15')).id,
otherAbsence: (await event(otherDayOff.id, otherAccount.id, '2027-02-22', '', otherId)).id,
otherCongregation: otherId,
member: member.id,
withRecordAccount: withRecord.id,
withoutRecordAccount: withoutRecord.id,
}
// Copied already, with a note of its own: a run neither doubles nor overwrites it.
await tx.absence.create({
data: {
startDate: new Date('2027-02-01T00:00:00Z'),
endDate: new Date('2027-02-01T23:59:00Z'),
note: 'déjà là',
accountId: withRecord.id,
legacyEventId: ids.copied,
congregationId,
},
})

const read = () =>
tx.absence.findMany({
where: { congregationId },
select: {
legacyEventId: true,
startDate: true,
endDate: true,
note: true,
memberId: true,
accountId: true,
createdAt: true,
},
orderBy: { legacyEventId: 'asc' },
})

for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement)
const first = await read()
// Declared by the previous image after the first run: no Absence row of its own yet.
ids.late = (await event(dayOff.id, withoutRecord.id, '2027-03-01')).id
for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement)
const second = await read()

let ownerlessRefused = false
try {
await tx.$executeRawUnsafe('SAVEPOINT ownerless')
await tx.$executeRawUnsafe(
`INSERT INTO "Absence" ("startDate", "endDate", "congregationId") VALUES (now(), now(), ${congregationId})`,
)
} catch {
ownerlessRefused = true
} finally {
await tx.$executeRawUnsafe('ROLLBACK TO SAVEPOINT ownerless')
}

const otherCongregation = await tx.absence.findMany({
where: { legacyEventId: { in: [ids.stray, ids.otherAbsence] } },
select: { legacyEventId: true, congregationId: true },
})
result = { ids, first, second, otherCongregation, ownerlessRefused }
throw new Rollback()
})
} catch (error) {
if (!(error instanceof Rollback)) throw error
}
return result as Result
})()
return memo
}

afterAll(async () => {
await testDb.$disconnect()
})

describe('20261120090000_add_absences', () => {
it('copies every day-off once, as it is, with its owner’s record when the account has one', async () => {
const { ids, first } = await snapshot()

expect(first).toEqual([
{
legacyEventId: ids.withRecord,
startDate: new Date('2027-01-04T00:00:00Z'),
endDate: new Date('2027-01-04T23:59:00Z'),
note: 'Vacances',
memberId: ids.member,
accountId: ids.withRecordAccount,
createdAt: new Date('2026-10-01T08:00:00Z'),
},
{
legacyEventId: ids.withoutRecord,
startDate: new Date('2027-01-11T00:00:00Z'),
endDate: new Date('2027-01-11T23:59:00Z'),
note: '',
memberId: null,
accountId: ids.withoutRecordAccount,
createdAt: new Date('2026-10-01T08:00:00Z'),
},
expect.objectContaining({ legacyEventId: ids.copied, note: 'déjà là', memberId: null }),
])
})

it('leaves out an event that is no absence', async () => {
const { ids, first } = await snapshot()

expect(first.map(row => row.legacyEventId)).not.toContain(ids.meeting)
})

it('copies on a second run only the absences declared since', async () => {
const { ids, first, second } = await snapshot()

expect(second).toEqual([...first, expect.objectContaining({ legacyEventId: ids.late, memberId: null })])
})

it('refuses an absence that is nobody’s', async () => {
const { ownerlessRefused } = await snapshot()

expect(ownerlessRefused).toBe(true)
})

it('isolates absences by congregation', async () => {
const rows = await testDb.$queryRaw<{ forced: boolean; policies: bigint }[]>`
SELECT c.relforcerowsecurity AS forced,
(SELECT COUNT(*) FROM pg_policies p WHERE p.tablename = 'Absence' AND p.policyname = 'tenant_isolation') AS policies
FROM pg_class c WHERE c.relname = 'Absence'`
expect(rows).toEqual([{ forced: true, policies: 1n }])
})

it('leaves out an absence without an author, and an event pointing at another congregation’s template', async () => {
const { ids, second } = await snapshot()
const copied = second.map(row => row.legacyEventId)

expect(copied).not.toContain(ids.noAuthor)
expect(copied).not.toContain(ids.stray)
})

it('copies the other congregation’s absence under that congregation', async () => {
const { ids, otherCongregation } = await snapshot()

expect(otherCongregation).toEqual([{ legacyEventId: ids.otherAbsence, congregationId: ids.otherCongregation }])
})
})
Loading