Skip to content

Commit

Permalink
fix: migrator for mysql 5.6 (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
black-06 committed Feb 6, 2024
1 parent e05761b commit b87f024
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions migrator.go
Expand Up @@ -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 {
Expand Down
7 changes: 7 additions & 0 deletions mysql.go
Expand Up @@ -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 {
Expand Down Expand Up @@ -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") {
Expand Down

0 comments on commit b87f024

Please sign in to comment.