Add functions to db test utils.
@@ -42,3 +42,46 @@ func TestDB() *gorm.DB {
return db
}
+
+// ResetDBTables reset given tables.
+func ResetDBTables(db *gorm.DB, tables ...interface{}) {
+ Truncate(db, tables...)
+ AutoMigrate(db, tables...)
+}
+
+// Truncate receives table arguments and truncate their content in database.
+func Truncate(db *gorm.DB, givenTables ...interface{}) {
+ // We need to iterate throught the list in reverse order of
+ // creation, since later tables may have constraints or
+ // dependencies on earlier tables.
+ len := len(givenTables)
+ for i := range givenTables {
+ table := givenTables[len-i-1]
+ db.DropTableIfExists(table)
+ }
+}
+
+// AutoMigrate receives table arguments and create or update their
+// table structure in database.
+func AutoMigrate(db *gorm.DB, givenTables ...interface{}) {
+ for _, table := range givenTables {
+ db.AutoMigrate(table)
+ if migratable, ok := table.(Migratable); ok {
+ exec(func() error { return migratable.AfterMigrate(db) })
+ }
+ }
+}
+
+// Migratable defines interface for implementing post-migration
+// actions such as adding constraints that arent's supported by Gorm's
+// struct tags. This function must be idempotent, since it will most
+// likely be executed multiple times.
+type Migratable interface {
+ AfterMigrate(db *gorm.DB) error
+}
+
+func exec(c func() error) {
+ if err := c(); err != nil {
+ panic(err)
+ }
+}
