fix(db): add FK constraint on usage_snapshots.agent_id [#1244]

This commit is contained in:
admin committed 2026-06-28 15:05:37 -04:00
1 parent 4675aa3fd4
commit adde5c6bc9
3 files changed
+20 -1

No files matched your search

+1 -1
View File
@@ -2,4 +2,4 @@ package upgrade
// RequiredSchemaVersion is the schema migration version this binary requires.
// Bump this whenever adding a new SQL migration file.
const RequiredSchemaVersion uint = 86
const RequiredSchemaVersion uint = 87
@@ -0,0 +1,2 @@
-- Rollback migration 087
ALTER TABLE usage_snapshots DROP CONSTRAINT IF EXISTS fk_usage_snapshots_agent_id;
@@ -0,0 +1,17 @@
-- Migration 087: FK constraint for usage_snapshots.agent_id
--
-- Pre-check audit (should return 0 violations on a clean DB):
-- SELECT COUNT(*) FROM usage_snapshots
-- WHERE agent_id IS NOT NULL
-- AND agent_id NOT IN (SELECT id FROM agents);
--
-- Orphan cleanup (idempotent guard):
DELETE FROM usage_snapshots
WHERE agent_id IS NOT NULL
AND agent_id NOT IN (SELECT id FROM agents);
-- Add FK constraint: usage_snapshots.agent_id → agents(id) ON DELETE SET NULL
-- agent_id is nullable — rows with NULL remain for aggregate/rollup totals.
ALTER TABLE usage_snapshots
ADD CONSTRAINT fk_usage_snapshots_agent_id
FOREIGN KEY (agent_id) REFERENCES agents(id) ON DELETE SET NULL;