2020-02-22 12:53:57 +03:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/jinzhu/gorm"
|
|
|
|
"github.com/jinzhu/gorm/clause"
|
|
|
|
"github.com/jinzhu/gorm/migrator"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Migrator struct {
|
|
|
|
migrator.Migrator
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Migrator) AlterColumn(value interface{}, field string) error {
|
|
|
|
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
|
|
|
|
if field := stmt.Schema.LookUpField(field); field != nil {
|
|
|
|
return m.DB.Exec(
|
2020-05-31 05:38:01 +03:00
|
|
|
"ALTER TABLE ? MODIFY COLUMN ? ?",
|
|
|
|
clause.Table{Name: stmt.Table}, clause.Column{Name: field.DBName}, m.FullDataTypeOf(field),
|
2020-02-22 12:53:57 +03:00
|
|
|
).Error
|
|
|
|
}
|
|
|
|
return fmt.Errorf("failed to look up field with name: %s", field)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-06-02 02:28:29 +03:00
|
|
|
func (m Migrator) DropTable(values ...interface{}) error {
|
|
|
|
values = m.ReorderModels(values, false)
|
|
|
|
tx := m.DB.Session(&gorm.Session{})
|
|
|
|
tx.Exec("SET FOREIGN_KEY_CHECKS = 0;")
|
|
|
|
for i := len(values) - 1; i >= 0; i-- {
|
|
|
|
if err := m.RunWithValue(values[i], func(stmt *gorm.Statement) error {
|
|
|
|
return tx.Exec("DROP TABLE IF EXISTS ? CASCADE", clause.Table{Name: stmt.Table}).Error
|
|
|
|
}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tx.Exec("SET FOREIGN_KEY_CHECKS = 1;")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-22 12:53:57 +03:00
|
|
|
func (m Migrator) DropConstraint(value interface{}, name string) error {
|
|
|
|
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
|
|
|
|
for _, chk := range stmt.Schema.ParseCheckConstraints() {
|
|
|
|
if chk.Name == name {
|
|
|
|
return m.DB.Exec(
|
|
|
|
"ALTER TABLE ? DROP CHECK ?",
|
|
|
|
clause.Table{Name: stmt.Table}, clause.Column{Name: name},
|
|
|
|
).Error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return m.DB.Exec(
|
|
|
|
"ALTER TABLE ? DROP FOREIGN KEY ?",
|
|
|
|
clause.Table{Name: stmt.Table}, clause.Column{Name: name},
|
|
|
|
).Error
|
|
|
|
})
|
|
|
|
}
|