postgresql/migration.go

52 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-08-24 08:45:16 +00:00
package postgresql
import (
"database/sql"
"fmt"
2022-12-19 04:22:38 +00:00
"os"
2022-10-10 05:09:54 +00:00
"github.com/golang-migrate/migrate/v4"
2022-08-24 08:45:16 +00:00
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
func runMigration(db *sql.DB, server string) {
// init migrate data
driver, _ := postgres.WithInstance(db, &postgres.Config{})
m, err := migrate.NewWithDatabaseInstance(
fmt.Sprintf("file:///%s", getMigrationDirectoryPath(server)),
"postgres",
driver,
)
// up
if err == nil {
if err = m.Up(); err != nil && err.Error() != "no change" {
2022-12-19 04:22:38 +00:00
fmt.Printf("[postgresql] run migration error: %s", err.Error())
return
2022-08-24 08:45:16 +00:00
}
fmt.Printf("⚡️[postgres]: done migration \n")
}
}
func getMigrationDirectoryPath(server string) string {
migrationDir := fmt.Sprintf("/external/postgresql/%s/migrations/sql", server)
dirname, err := os.Getwd()
if err != nil {
panic(err)
}
// Check path existed
path := dirname + migrationDir
if _, err = os.Stat(path); os.IsNotExist(err) {
// Create if not existed
err = os.Mkdir(path, 0755)
if err != nil {
panic(err)
}
}
return path
}