From 6a42de73d124069734a9b51bed25c39ab2c9f94e Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Thu, 2 Apr 2020 21:37:51 +0300 Subject: [PATCH] Check if constraint exists before trying to delete --- .../2019-05-16-message-delete-cascade.go | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/database/upgrades/2019-05-16-message-delete-cascade.go b/database/upgrades/2019-05-16-message-delete-cascade.go index df94238..3fb8513 100644 --- a/database/upgrades/2019-05-16-message-delete-cascade.go +++ b/database/upgrades/2019-05-16-message-delete-cascade.go @@ -10,15 +10,21 @@ func init() { // SQLite doesn't support constraint updates, but it isn't that careful with constraints anyway. return nil } - _, err := tx.Exec("ALTER TABLE message DROP CONSTRAINT message_chat_jid_fkey") - if err != nil { - return nil - } - _, err = tx.Exec(`ALTER TABLE message ADD CONSTRAINT message_chat_jid_fkey + res, _ := tx.Query(`SELECT EXISTS(SELECT constraint_name FROM information_schema.table_constraints + WHERE table_name='message' AND constraint_name='message_chat_jid_fkey');`) + var exists bool + _ = res.Scan(&exists) + if exists { + _, err := tx.Exec("ALTER TABLE message DROP CONSTRAINT IF EXISTS message_chat_jid_fkey") + if err != nil { + return err + } + _, err = tx.Exec(`ALTER TABLE message ADD CONSTRAINT message_chat_jid_fkey FOREIGN KEY (chat_jid, chat_receiver) REFERENCES portal(jid, receiver) ON DELETE CASCADE`) - if err != nil { - return err + if err != nil { + return err + } } return nil }}