This commit is contained in:
dpurbosakti
2025-08-15 12:12:33 +07:00
parent 61d0f91c3f
commit db6af776a3
4 changed files with 65 additions and 4 deletions
+1
View File
@@ -27,6 +27,7 @@ go.work.sum
# env file
.env
config.yml
cmd/migration/atlas.hcl
# Editor/IDE
# .idea/
+2 -1
View File
@@ -9,10 +9,11 @@ data "external_schema" "gorm" {
env "gorm" {
src = data.external_schema.gorm.url
dev = "postgres://moko:password@localhost:5432/simrs_vx1?sslmode=disable"
dev = "postgres://moko:password@localhost:5432/simrs_vx3?sslmode=disable"
migration {
dir = "file://migrations"
}
url = "postgres://moko:password@localhost:5432/simrs_vx1?sslmode=disable"
format {
migrate {
diff = "{{ sql . \" \" }}"
+22
View File
@@ -0,0 +1,22 @@
data "external_schema" "gorm" {
program = [
"go",
"run",
"-mod=mod",
".",
]
}
env "gorm" {
src = data.external_schema.gorm.url
dev = "" // dsn db to check the diff
migration {
dir = "file://migrations"
}
url = "" // dsn db to apply
format {
migrate {
diff = "{{ sql . \" \" }}"
}
}
}
+40 -3
View File
@@ -4,9 +4,12 @@ import (
"fmt"
"io"
"os"
"os/exec"
eu "simrs-vx/internal/domain/main-entities/user"
"ariga.io/atlas-provider-gorm/gormschema"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type Config struct {
@@ -20,8 +23,14 @@ type DbConf struct {
MaxIdleTime int `yaml:"maxIdleTime"`
}
func Migrate() {
stmts, err := gormschema.New("postgres").Load(getEntities()...)
func Loader() {
gormCfg := &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
NoLowerCase: true,
},
}
stmts, err := gormschema.New("postgres", gormschema.WithConfig(gormCfg)).Load(GetEntities()...)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to load gorm schema: %v\n", err)
os.Exit(1)
@@ -29,8 +38,36 @@ func Migrate() {
_, _ = io.WriteString(os.Stdout, stmts)
}
func getEntities() []any {
func GetEntities() []any {
return []any{
&eu.User{},
}
}
func runAtlas(args ...string) error {
cmd := exec.Command("atlas", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func logMsg(msg string) {
fmt.Fprintln(os.Stderr, msg)
}
func Migrate() {
Loader()
logMsg("Running atlas migrate diff...")
if err := runAtlas("migrate", "diff", "--env", "gorm"); err != nil {
logMsg(fmt.Sprintf("Failed to run diff: %v", err))
return
}
logMsg("Running atlas migrate apply...")
if err := runAtlas("migrate", "apply", "--env", "gorm"); err != nil {
logMsg(fmt.Sprintf("Failed to run apply: %v", err))
return
}
logMsg("Migration complete")
}