fix(db): correct channel contact merged_id foreign key (#1290)

Co-authored-by: GoClaw Operator <operator@goclaw>
This commit is contained in:
nguyenha935andGoClaw Operator authored and GitHub committed 2026-06-27 21:24:52 +07:00
1 parent 24a6b02506
commit b72959b34c
4 files changed
+34 -5

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 = 85
const RequiredSchemaVersion uint = 86
@@ -0,0 +1,8 @@
-- Roll back only the corrective FK.
-- Do not recreate the old self-reference FK because it is incompatible with valid data.
BEGIN;
ALTER TABLE channel_contacts
DROP CONSTRAINT IF EXISTS fk_channel_contacts_merged_id;
COMMIT;
@@ -0,0 +1,14 @@
-- Fix channel_contacts.merged_id FK.
-- merged_id stores tenant_users.id, not channel_contacts.id.
BEGIN;
ALTER TABLE channel_contacts
DROP CONSTRAINT IF EXISTS fk_channel_contacts_merged_id;
ALTER TABLE channel_contacts
ADD CONSTRAINT fk_channel_contacts_merged_id
FOREIGN KEY (merged_id)
REFERENCES tenant_users(id)
ON DELETE SET NULL;
COMMIT;
+11 -4
View File
@@ -66,11 +66,18 @@ FROM webhooks w
LEFT JOIN channel_instances ci ON ci.id = w.channel_id
WHERE w.channel_id IS NOT NULL AND ci.id IS NULL;
-- channel_contacts: merged_id self-ref orphans
SELECT 'channel_contacts.merged_id orphans' AS check_name, COUNT(*) AS violations
-- channel_contacts: merged_id tenant_users orphans
SELECT 'channel_contacts.merged_id tenant_users orphans' AS check_name, COUNT(*) AS violations
FROM channel_contacts cc
LEFT JOIN channel_contacts cc2 ON cc2.id = cc.merged_id
WHERE cc.merged_id IS NOT NULL AND cc2.id IS NULL;
LEFT JOIN tenant_users tu ON tu.id = cc.merged_id
WHERE cc.merged_id IS NOT NULL AND tu.id IS NULL;
-- channel_contacts: merged_id tenant drift
SELECT 'channel_contacts.merged_id tenant drift' AS check_name, COUNT(*) AS violations
FROM channel_contacts cc
JOIN tenant_users tu ON tu.id = cc.merged_id
WHERE cc.merged_id IS NOT NULL
AND cc.tenant_id <> tu.tenant_id;
-- traces: parent_trace_id self-ref orphans
SELECT 'traces.parent_trace_id orphans' AS check_name, COUNT(*) AS violations