Skip to content

Instantly share code, notes, and snippets.

@sumitasok
Last active September 9, 2021 03:22
Show Gist options
  • Save sumitasok/3ec6818a119e38860cbf9b7399be36fe to your computer and use it in GitHub Desktop.
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.
package migration
type Migrator interface {
Migrate() error
}
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{})
}
package modals
type Missions struct {
Name string `gorm:"size:50;not null;" json:"name"`
}
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