description: 當(dāng)數(shù)據(jù)庫(kù)需要頻繁更新結(jié)構(gòu)時(shí),代碼與數(shù)據(jù)庫(kù)難以保持一致是煩人的問(wèn)題.而golang的gorm庫(kù),有Auto Migration功能,可以根據(jù)go里的struct tag自動(dòng)更新數(shù)據(jù)庫(kù)結(jié)構(gòu), 非常方便.
最近在寫(xiě)測(cè)試, 很明顯每一個(gè)單元測(cè)試最好就在運(yùn)行時(shí)自動(dòng)清空數(shù)據(jù)庫(kù). gorm的Auto Migration功能就可以滿足此功能.
Auto Migration
Automatically migrate your schema, to keep your schema update to date.
WARNING: AutoMigrate will ONLY create tables, missing columns and missing indexes, and WON'T change existing column's type or delete unused columns to protect your data.
最重要的是, 索引(index), 約束(constrants), 類型(type)還有默認(rèn)值(default)都可以設(shè)置,但是文檔并沒(méi)有詳細(xì)的介紹,經(jīng)過(guò)我的搜索與測(cè)試,終于摸清所有的關(guān)系.
AutoMigration只會(huì)根據(jù)struct tag建立新表, 沒(méi)有的列以及索引, 不會(huì)改變已經(jīng)存在的列的類型或者刪除沒(méi)有用到的列. 所以需要?jiǎng)討B(tài)更新的話,還是需要在auto migration前DROP TABLE
刪除整個(gè)表再重建. 如:
func clearDatebase() {
db := GetTestClient().NewConn()
db.Exec("DROP TABLE books")
db.AutoMigrate(&mystructtag.books{})
db.Exec("DROP TABLE book_users")
db.AutoMigrate(&mystructtag.book_users{})
}
gorm:
- primary_key 設(shè)置主鍵
- not null 非空約束
- size:64 類型大小,通常是指varchar
以上主要就是size和not null并沒(méi)有在文檔上出現(xiàn), 其他都可以從例子找到, 自己意會(huì)啦.
type User struct {
gorm.Model
Birthday time.Time
Age int
Name string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
Num int `gorm:"AUTO_INCREMENT"`
CreditCard CreditCard // One-To-One relationship (has one - use CreditCard's UserID as foreign key)
Emails []Email // One-To-Many relationship (has many - use Email's UserID as foreign key)
BillingAddress Address // One-To-One relationship (belongs to - use BillingAddressID as foreign key)
BillingAddressID sql.NullInt64
ShippingAddress Address // One-To-One relationship (belongs to - use ShippingAddressID as foreign key)
ShippingAddressID int
IgnoreMe int `gorm:"-"` // Ignore this field
Languages []Language `gorm:"many2many:user_languages;"` // Many-To-Many relationship, 'user_languages' is join table
}