Fix month close migration constraints

This commit is contained in:
michael committed 2026-08-14 12:25:50 +02:00
1 parent a760f423a4
commit 4f0020a61d
2 files changed
+19 -3

No files matched your search

+16
View File
@@ -7,9 +7,25 @@ async function findMigrationAdmin() {
async function ensureClosureOwnership(table: string, column: string, primaryKeyColumns: string[], adminId: string | null) {
await query(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS user_id BIGINT REFERENCES users(id);`);
if (adminId) {
await query(`UPDATE ${table} SET user_id = $1 WHERE user_id IS NULL;`, [adminId]);
}
const duplicateMatchers = [...primaryKeyColumns, "user_id"]
.map((key) => `older.${key} IS NOT DISTINCT FROM newer.${key}`)
.join(" AND ");
await query(`
DELETE FROM ${table} older
USING ${table} newer
WHERE ${duplicateMatchers}
AND (
older.closed_at < newer.closed_at
OR (older.closed_at = newer.closed_at AND older.ctid < newer.ctid)
);
`);
await query(`
DO $$
BEGIN