Files
simrsx-be/internal/interface/migration/migration.go
2025-08-13 14:23:51 +07:00

94 lines
1.9 KiB
Go

package migration
import (
"flag"
"fmt"
"log"
"os"
"reflect"
"gopkg.in/yaml.v3"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type DbConf struct {
Dsn string
Dialect string
}
// Migrate all tables at once, one time only for exam purpose
func Migrate() {
// use default config file location or use flat
cfgFile := "./config.yml"
flag.StringVar(&cfgFile, "config-file", "./config.yml", "Configuration path (default=./config.yaml)")
flag.Parse()
// read the config file
yamlFile, err := os.ReadFile(cfgFile)
if err != nil {
log.Fatalf("%v", err)
}
// parse into config struct
var dbConf DbConf
err = yaml.Unmarshal(yamlFile, &dbConf)
if err != nil {
log.Fatal(err)
}
log.Print("config is loaded successfully")
// create database connection
db, err := gorm.Open(postgres.Open(dbConf.Dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
NoLowerCase: true,
},
})
if err != nil {
log.Fatal(err)
}
log.Print("database-connection is established successfully")
// migrate all the tables
modelList := []any{
// &single.Single{}}, // example
}
argsWithProg := os.Args
if len(argsWithProg) > 1 {
if argsWithProg[1] == "gradually" {
for _, v := range modelList {
name := ""
if t := reflect.TypeOf(v); t.Kind() == reflect.Ptr {
name = "*" + t.Elem().Name()
} else {
name = t.Name()
}
fmt.Println("Migrating ", name)
db.AutoMigrate(v)
}
} else {
for _, v := range modelList {
name := ""
if t := reflect.TypeOf(v); t.Kind() == reflect.Ptr {
name = "*" + t.Elem().Name()
} else {
name = t.Name()
}
if name == argsWithProg[1] {
fmt.Println("Migrating ", name)
db.AutoMigrate(v)
}
}
}
} else {
fmt.Println("Migrating all tables")
db.AutoMigrate(modelList...)
}
log.Printf("migration is complete")
}