From 32db24a4b0b47ad3395cb67e79ba80201feaf36d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Aug 2026 09:48:35 -0400 Subject: [PATCH] perf: Make the personalOwnerId migration safe on large tables The index builds with CONCURRENTLY and the check constraint is added NOT VALID then validated separately, so neither blocks writes to documents. Co-Authored-By: Claude Fable 5 --- ...60816120000-add-documents-personal-owner-id.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/server/migrations/20260816120000-add-documents-personal-owner-id.js b/server/migrations/20260816120000-add-documents-personal-owner-id.js index 3e6a9dac6a..9e8a9cd70d 100644 --- a/server/migrations/20260816120000-add-documents-personal-owner-id.js +++ b/server/migrations/20260816120000-add-documents-personal-owner-id.js @@ -3,6 +3,8 @@ /** @type {import('sequelize-cli').Migration} */ module.exports = { async up(queryInterface, Sequelize) { + // Adding a nullable column with a foreign key takes only a brief lock, as + // there are no existing rows to validate. await queryInterface.addColumn("documents", "personalOwnerId", { type: Sequelize.UUID, allowNull: true, @@ -13,21 +15,30 @@ module.exports = { onDelete: "set null", }); + // CONCURRENTLY so the build does not block writes to the table. It cannot + // run inside a transaction. await queryInterface.sequelize.query(` - CREATE INDEX documents_personal_owner_id + CREATE INDEX CONCURRENTLY IF NOT EXISTS documents_personal_owner_id ON documents ("personalOwnerId") WHERE "personalOwnerId" IS NOT NULL AND "deletedAt" IS NULL `); // A published document lives in exactly one place: a collection, or a // person's own space. Drafts and templates live in neither. + // + // NOT VALID makes the ADD CONSTRAINT a metadata-only change, and the + // separate VALIDATE scans existing rows under a lock that does not block + // reads or writes. await queryInterface.sequelize.query(` ALTER TABLE documents ADD CONSTRAINT documents_single_home CHECK ( "publishedAt" IS NULL OR template = true OR (("collectionId" IS NULL) <> ("personalOwnerId" IS NULL)) - ) + ) NOT VALID `); + await queryInterface.sequelize.query( + `ALTER TABLE documents VALIDATE CONSTRAINT documents_single_home` + ); }, async down(queryInterface) {