Add migrator tests for mysql

This commit is contained in:
Jinzhu 2020-02-22 23:08:20 +08:00
parent 6d58b62fd4
commit 1895d281bf
7 changed files with 54 additions and 28 deletions

View File

@ -23,9 +23,8 @@ func Open(dsn string) gorm.Dialector {
func (dialector Dialector) Initialize(db *gorm.DB) (err error) { func (dialector Dialector) Initialize(db *gorm.DB) (err error) {
// register callbacks // register callbacks
callbacks.RegisterDefaultCallbacks(db) callbacks.RegisterDefaultCallbacks(db)
db.DB, err = sql.Open("sqlite3", dialector.DSN) db.DB, err = sql.Open("mysql", dialector.DSN)
return
return nil
} }
func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator { func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
@ -75,9 +74,13 @@ func (dialector Dialector) DataTypeOf(field *schema.Field) string {
return "double" return "double"
case schema.String: case schema.String:
size := field.Size size := field.Size
if field.PrimaryKey {
size = 256
}
if size >= 65536 && size <= int(math.Pow(2, 24)) { if size >= 65536 && size <= int(math.Pow(2, 24)) {
return "mediumtext" return "mediumtext"
} else if size > int(math.Pow(2, 24)) || size < 0 { } else if size > int(math.Pow(2, 24)) || size <= 0 {
return "longtext" return "longtext"
} }
return fmt.Sprintf("varchar(%d)", size) return fmt.Sprintf("varchar(%d)", size)

View File

@ -1,12 +1,33 @@
package mysql_test package mysql_test
import ( import (
"fmt"
"testing" "testing"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/dialects/mysql" "github.com/jinzhu/gorm/dialects/mysql"
"github.com/jinzhu/gorm/tests"
) )
func TestOpen(t *testing.T) { func TestOpen(t *testing.T) {
gorm.Open(mysql.Open("gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True"), nil) gorm.Open(mysql.Open("gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True"), nil)
} }
var (
DB *gorm.DB
err error
)
func init() {
if DB, err = gorm.Open(mysql.Open("gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True"), &gorm.Config{}); err != nil {
panic(fmt.Sprintf("failed to initialize database, got error %v", err))
}
}
func TestCURD(t *testing.T) {
tests.RunTestsSuit(t, DB)
}
func TestMigrate(t *testing.T) {
tests.TestMigrate(t, DB)
}

View File

@ -21,7 +21,6 @@ func Open(dsn string) gorm.Dialector {
func (dialector Dialector) Initialize(db *gorm.DB) (err error) { func (dialector Dialector) Initialize(db *gorm.DB) (err error) {
// register callbacks // register callbacks
callbacks.RegisterDefaultCallbacks(db) callbacks.RegisterDefaultCallbacks(db)
db.DB, err = sql.Open("sqlite3", dialector.DSN) db.DB, err = sql.Open("sqlite3", dialector.DSN)
return return
} }

View File

@ -140,7 +140,7 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
} }
}() }()
err = fc(tx) err = fc(tx.Session(&Session{}))
if err == nil { if err == nil {
err = tx.Commit().Error err = tx.Commit().Error

View File

@ -19,6 +19,7 @@ type Migrator struct {
// Config schema config // Config schema config
type Config struct { type Config struct {
CreateIndexAfterCreateTable bool CreateIndexAfterCreateTable bool
AllowDeferredConstraintsWhenAutoMigrate bool
DB *gorm.DB DB *gorm.DB
gorm.Dialector gorm.Dialector
} }
@ -47,17 +48,17 @@ func (m Migrator) DataTypeOf(field *schema.Field) string {
// AutoMigrate // AutoMigrate
func (m Migrator) AutoMigrate(values ...interface{}) error { func (m Migrator) AutoMigrate(values ...interface{}) error {
// TODO smart migrate data type // TODO smart migrate data type
for _, value := range values { for _, value := range values {
if !m.DB.Migrator().HasTable(value) { tx := m.DB.Session(&gorm.Session{})
if err := m.DB.Migrator().CreateTable(value); err != nil { if !tx.Migrator().HasTable(value) {
if err := tx.Migrator().CreateTable(value); err != nil {
return err return err
} }
} else { } else {
if err := m.RunWithValue(value, func(stmt *gorm.Statement) error { if err := m.RunWithValue(value, func(stmt *gorm.Statement) error {
for _, field := range stmt.Schema.FieldsByDBName { for _, field := range stmt.Schema.FieldsByDBName {
if !m.DB.Migrator().HasColumn(value, field.DBName) { if !tx.Migrator().HasColumn(value, field.DBName) {
if err := m.DB.Migrator().AddColumn(value, field.DBName); err != nil { if err := tx.Migrator().AddColumn(value, field.DBName); err != nil {
return err return err
} }
} }
@ -65,16 +66,16 @@ func (m Migrator) AutoMigrate(values ...interface{}) error {
for _, rel := range stmt.Schema.Relationships.Relations { for _, rel := range stmt.Schema.Relationships.Relations {
if constraint := rel.ParseConstraint(); constraint != nil { if constraint := rel.ParseConstraint(); constraint != nil {
if !m.DB.Migrator().HasConstraint(value, constraint.Name) { if !tx.Migrator().HasConstraint(value, constraint.Name) {
if err := m.DB.Migrator().CreateConstraint(value, constraint.Name); err != nil { if err := tx.Migrator().CreateConstraint(value, constraint.Name); err != nil {
return err return err
} }
} }
} }
for _, chk := range stmt.Schema.ParseCheckConstraints() { for _, chk := range stmt.Schema.ParseCheckConstraints() {
if !m.DB.Migrator().HasConstraint(value, chk.Name) { if !tx.Migrator().HasConstraint(value, chk.Name) {
if err := m.DB.Migrator().CreateConstraint(value, chk.Name); err != nil { if err := tx.Migrator().CreateConstraint(value, chk.Name); err != nil {
return err return err
} }
} }
@ -83,8 +84,8 @@ func (m Migrator) AutoMigrate(values ...interface{}) error {
// create join table // create join table
if rel.JoinTable != nil { if rel.JoinTable != nil {
joinValue := reflect.New(rel.JoinTable.ModelType).Interface() joinValue := reflect.New(rel.JoinTable.ModelType).Interface()
if !m.DB.Migrator().HasTable(joinValue) { if !tx.Migrator().HasTable(joinValue) {
defer m.DB.Migrator().CreateTable(joinValue) defer tx.Migrator().CreateTable(joinValue)
} }
} }
} }
@ -100,6 +101,7 @@ func (m Migrator) AutoMigrate(values ...interface{}) error {
func (m Migrator) CreateTable(values ...interface{}) error { func (m Migrator) CreateTable(values ...interface{}) error {
for _, value := range values { for _, value := range values {
tx := m.DB.Session(&gorm.Session{})
if err := m.RunWithValue(value, func(stmt *gorm.Statement) error { if err := m.RunWithValue(value, func(stmt *gorm.Statement) error {
var ( var (
createTableSQL = "CREATE TABLE ? (" createTableSQL = "CREATE TABLE ? ("
@ -144,10 +146,10 @@ func (m Migrator) CreateTable(values ...interface{}) error {
for _, idx := range stmt.Schema.ParseIndexes() { for _, idx := range stmt.Schema.ParseIndexes() {
if m.CreateIndexAfterCreateTable { if m.CreateIndexAfterCreateTable {
m.DB.Migrator().CreateIndex(value, idx.Name) tx.Migrator().CreateIndex(value, idx.Name)
} else { } else {
createTableSQL += "INDEX ? ?," createTableSQL += "INDEX ? ?,"
values = append(values, clause.Expr{SQL: idx.Name}, m.DB.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt)) values = append(values, clause.Expr{SQL: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt))
} }
} }
@ -161,8 +163,8 @@ func (m Migrator) CreateTable(values ...interface{}) error {
// create join table // create join table
if rel.JoinTable != nil { if rel.JoinTable != nil {
joinValue := reflect.New(rel.JoinTable.ModelType).Interface() joinValue := reflect.New(rel.JoinTable.ModelType).Interface()
if !m.DB.Migrator().HasTable(joinValue) { if !tx.Migrator().HasTable(joinValue) {
defer m.DB.Migrator().CreateTable(joinValue) defer tx.Migrator().CreateTable(joinValue)
} }
} }
} }
@ -175,7 +177,7 @@ func (m Migrator) CreateTable(values ...interface{}) error {
createTableSQL = strings.TrimSuffix(createTableSQL, ",") createTableSQL = strings.TrimSuffix(createTableSQL, ",")
createTableSQL += ")" createTableSQL += ")"
return m.DB.Exec(createTableSQL, values...).Error return tx.Exec(createTableSQL, values...).Error
}); err != nil { }); err != nil {
return err return err
} }
@ -185,8 +187,9 @@ func (m Migrator) CreateTable(values ...interface{}) error {
func (m Migrator) DropTable(values ...interface{}) error { func (m Migrator) DropTable(values ...interface{}) error {
for _, value := range values { for _, value := range values {
tx := m.DB.Session(&gorm.Session{})
if err := m.RunWithValue(value, func(stmt *gorm.Statement) error { if err := m.RunWithValue(value, func(stmt *gorm.Statement) error {
return m.DB.Exec("DROP TABLE ?", clause.Table{Name: stmt.Table}).Error return tx.Exec("DROP TABLE ?", clause.Table{Name: stmt.Table}).Error
}); err != nil { }); err != nil {
return err return err
} }

View File

@ -7,7 +7,7 @@ import (
) )
func TestMigrate(t *testing.T, db *gorm.DB) { func TestMigrate(t *testing.T, db *gorm.DB) {
allModels := []interface{}{&User{}, &Account{}, &Pet{}, &Toy{}, &Company{}, &Language{}} allModels := []interface{}{&User{}, &Account{}, &Pet{}, &Company{}, &Toy{}, &Language{}}
for _, m := range allModels { for _, m := range allModels {
if db.Migrator().HasTable(m) { if db.Migrator().HasTable(m) {

View File

@ -21,7 +21,7 @@ type User struct {
Toys []Toy `gorm:"polymorphic:Owner"` Toys []Toy `gorm:"polymorphic:Owner"`
CompanyID *int CompanyID *int
Company Company Company Company
ManagerID int ManagerID uint
Manager *User Manager *User
Team []User `gorm:"foreignkey:ManagerID"` Team []User `gorm:"foreignkey:ManagerID"`
Languages []Language `gorm:"many2many:UserSpeak"` Languages []Language `gorm:"many2many:UserSpeak"`
@ -49,7 +49,7 @@ type Toy struct {
} }
type Company struct { type Company struct {
ID uint ID int
Name string Name string
} }