feat(documents): schema for hub split + entity-folder lifecycle

Adds system_managed / entity_type / entity_id / archived_at to
document_folders for the three system roots (Clients/Companies/
Yachts) + per-entity auto-subfolders. Adds files.folder_id so a
file's home is a first-class field (not derived from storagePath
prefix). Partial unique index uniq_document_folders_entity dedupes
entity subfolders per port; chk_system_folder_shape pins the shape
of system rows. Migration is idempotent and ships without backfill —
the backfill script runs as a separate deploy step.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-11 11:00:40 +02:00
parent 40e3db237d
commit 48f6fb94a7
2 changed files with 64 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
-- Wave 11.B+: documents hub split + auto-filed client folders.
-- Adds system-managed folder lifecycle columns to document_folders
-- (Clients/Companies/Yachts roots + per-entity subfolders), adds the
-- folder_id pointer to files, and backfills the structure for every
-- existing port + file. Idempotent — safe to re-run.
-- ─── document_folders: lifecycle columns ──────────────────────────────────
ALTER TABLE "document_folders"
ADD COLUMN IF NOT EXISTS "system_managed" boolean NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS "entity_type" text,
ADD COLUMN IF NOT EXISTS "entity_id" text,
ADD COLUMN IF NOT EXISTS "archived_at" timestamp with time zone;
-- Shape guard: system_managed=true implies a known shape.
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'chk_system_folder_shape'
) THEN
ALTER TABLE "document_folders"
ADD CONSTRAINT "chk_system_folder_shape" CHECK (
NOT system_managed
OR entity_type = 'root'
OR (entity_type IN ('client','company','yacht') AND entity_id IS NOT NULL)
);
END IF;
END $$;
-- Partial unique index: one subfolder per (port, entity_type, entity_id).
CREATE UNIQUE INDEX IF NOT EXISTS "uniq_document_folders_entity"
ON "document_folders" ("port_id", "entity_type", "entity_id")
WHERE "entity_id" IS NOT NULL;
-- ─── files: folder pointer ────────────────────────────────────────────────
ALTER TABLE "files"
ADD COLUMN IF NOT EXISTS "folder_id" text REFERENCES "document_folders" ("id")
ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS "idx_files_folder" ON "files" ("folder_id");
CREATE INDEX IF NOT EXISTS "idx_files_port_folder" ON "files" ("port_id", "folder_id");