2019-05-16-message-delete-cascade.go 918 B

12345678910111213141516171819202122232425262728293031
  1. package upgrades
  2. import (
  3. "database/sql"
  4. )
  5. func init() {
  6. upgrades[1] = upgrade{"Add ON DELETE CASCADE to message table", func(tx *sql.Tx, ctx context) error {
  7. if ctx.dialect == SQLite {
  8. // SQLite doesn't support constraint updates, but it isn't that careful with constraints anyway.
  9. return nil
  10. }
  11. res, _ := ctx.db.Query(`SELECT EXISTS(SELECT constraint_name FROM information_schema.table_constraints
  12. WHERE table_name='message' AND constraint_name='message_chat_jid_fkey')`)
  13. var exists bool
  14. _ = res.Scan(&exists)
  15. if exists {
  16. _, err := tx.Exec("ALTER TABLE message DROP CONSTRAINT IF EXISTS message_chat_jid_fkey")
  17. if err != nil {
  18. return err
  19. }
  20. _, err = tx.Exec(`ALTER TABLE message ADD CONSTRAINT message_chat_jid_fkey
  21. FOREIGN KEY (chat_jid, chat_receiver) REFERENCES portal(jid, receiver)
  22. ON DELETE CASCADE`)
  23. if err != nil {
  24. return err
  25. }
  26. }
  27. return nil
  28. }}
  29. }