Last active
September 9, 2021 03:22
-
-
Save sumitasok/3ec6818a119e38860cbf9b7399be36fe to your computer and use it in GitHub Desktop.
sample of how to do database table creation and deletion for running tests and then cleaning up.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package migration | |
type Migrator interface { | |
Migrate() error | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package migration | |
import ( | |
"interfaces" | |
"models" | |
"gorm.io/gorm" | |
) | |
var _ interfaces.MigrateEntity = MissionMigrator{} | |
func NewMissionMigratorForGorm(db *gorm.DB) *MissionMigrator { | |
return &MissionMigrator{db: db} | |
} | |
type MissionMigrator struct { | |
db *gorm.DB | |
} | |
func (m MissionMigrator) Up() error { | |
err := m.db.AutoMigrate(&models.Missions{}) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
func (m MissionMigrator) Down() error { | |
return m.db.Migrator().DropTable(&models.Missions{}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package modals | |
type Missions struct { | |
Name string `gorm:"size:50;not null;" json:"name"` | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func TestMain(m *testing.M) { | |
_db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) | |
if err != nil { | |
panic(err) | |
} | |
db = _db | |
// database setup | |
mission := migration.NewMissionMigratorForGorm(db) | |
// handle error | |
err := mission.Up() | |
exitCode := m.Run() | |
// database teardown. | |
err = mission.Down() | |
// handle error | |
os.Exit(exitCode) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment