From b87f024d0e3d00c24b87e8e2b3d2f19a9f1eea31 Mon Sep 17 00:00:00 2001 From: black-06 Date: Tue, 6 Feb 2024 19:33:22 +0800 Subject: [PATCH] fix: migrator for mysql 5.6 (#141) --- migrator.go | 23 +++++++++++++++++++++++ mysql.go | 7 +++++++ 2 files changed, 30 insertions(+) diff --git a/migrator.go b/migrator.go index cd492b2..790a014 100644 --- a/migrator.go +++ b/migrator.go @@ -224,6 +224,29 @@ func (m Migrator) RenameColumn(value interface{}, oldName, newName string) error }) } +func (m Migrator) DropConstraint(value interface{}, name string) error { + if !m.Dialector.Config.DontSupportDropConstraint { + return m.Migrator.DropConstraint(value, name) + } + + return m.RunWithValue(value, func(stmt *gorm.Statement) error { + constraint, table := m.GuessConstraintInterfaceAndTable(stmt, name) + if constraint != nil { + name = constraint.GetName() + switch constraint.(type) { + case *schema.Constraint: + return m.DB.Exec("ALTER TABLE ? DROP FOREIGN KEY ?", clause.Table{Name: table}, clause.Column{Name: name}).Error + case *schema.CheckConstraint: + return m.DB.Exec("ALTER TABLE ? DROP CHECK ?", clause.Table{Name: table}, clause.Column{Name: name}).Error + } + } + if m.HasIndex(value, name) { + return m.DB.Exec("ALTER TABLE ? DROP INDEX ?", clause.Table{Name: table}, clause.Column{Name: name}).Error + } + return nil + }) +} + func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error { if !m.Dialector.DontSupportRenameIndex { return m.RunWithValue(value, func(stmt *gorm.Statement) error { diff --git a/mysql.go b/mysql.go index 68d02e8..c58de24 100644 --- a/mysql.go +++ b/mysql.go @@ -41,6 +41,10 @@ type Config struct { DontSupportForShareClause bool DontSupportNullAsDefaultValue bool DontSupportRenameColumnUnique bool + // As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax + // for dropping and altering existing constraints of any type. + // see https://dev.mysql.com/doc/refman/8.0/en/alter-table.html + DontSupportDropConstraint bool } type Dialector struct { @@ -136,14 +140,17 @@ func (dialector Dialector) Initialize(db *gorm.DB) (err error) { dialector.Config.DontSupportRenameIndex = true dialector.Config.DontSupportRenameColumn = true dialector.Config.DontSupportForShareClause = true + dialector.Config.DontSupportDropConstraint = true } else if strings.HasPrefix(dialector.ServerVersion, "5.7.") { dialector.Config.DontSupportRenameColumn = true dialector.Config.DontSupportForShareClause = true + dialector.Config.DontSupportDropConstraint = true } else if strings.HasPrefix(dialector.ServerVersion, "5.") { dialector.Config.DisableDatetimePrecision = true dialector.Config.DontSupportRenameIndex = true dialector.Config.DontSupportRenameColumn = true dialector.Config.DontSupportForShareClause = true + dialector.Config.DontSupportDropConstraint = true } if strings.Contains(dialector.ServerVersion, "TiDB") {