diff --git a/backend/migrations/001_init.sql b/backend/migrations/001_init.sql index 9f57b74..3f56509 100644 --- a/backend/migrations/001_init.sql +++ b/backend/migrations/001_init.sql @@ -104,7 +104,6 @@ ALTER TABLE audit_log ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS ip_address TEXT; --- details existed already, but make it safer for newer code ALTER TABLE audit_log ALTER COLUMN details SET DEFAULT '{}'; @@ -114,17 +113,41 @@ SET local_part = split_part(email_address, '@', 1) WHERE local_part IS NULL AND email_address LIKE '%@%'; --- Keep old and new usage timestamp columns in sync initially -UPDATE mailboxes -SET usage_scanned_at = last_usage_scan_at -WHERE usage_scanned_at IS NULL - AND last_usage_scan_at IS NOT NULL; +-- Keep old and new usage timestamp columns in sync initially. +-- This must be guarded because older/newer MVP databases may not have last_usage_scan_at. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name = 'mailboxes' + AND column_name = 'last_usage_scan_at' + ) THEN + UPDATE mailboxes + SET usage_scanned_at = last_usage_scan_at + WHERE usage_scanned_at IS NULL + AND last_usage_scan_at IS NOT NULL; + END IF; +END $$; --- Backfill new audit target columns from old target column -UPDATE audit_log -SET target_id = target -WHERE target_id IS NULL - AND target IS NOT NULL; +-- Backfill new audit target columns from old target column. +-- This must also be guarded because some installations may already use target_id only. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name = 'audit_log' + AND column_name = 'target' + ) THEN + UPDATE audit_log + SET target_id = target + WHERE target_id IS NULL + AND target IS NOT NULL; + END IF; +END $$; UPDATE audit_log SET target_type = 'unknown'