Added function to create a new database if it doesn't exist

This commit is contained in:
2025-04-13 18:39:30 +02:00
parent 73d85adc42
commit d15d1422da

View File

@@ -78,6 +78,22 @@ func ResetGameIdSeq() {
}
}
func createDb(host string, port string, user string, password string, dbname string) {
conninfo := fmt.Sprintf("host=%s port=%s user=%s password=%s sslmode=disable", host, port, user, password)
db, err := sql.Open("postgres", conninfo)
defer db.Close()
if err != nil {
log.Fatal(err)
}
_, err = db.Exec("create database " + dbname)
if err != nil {
//handle the error
log.Fatal(err)
}
log.Println("Finished creating database")
}
func Migrate_db(host string, port string, user string, password string, dbname string) {
migrationInfo := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable",
user, password, host, port, dbname)
@@ -88,6 +104,19 @@ func Migrate_db(host string, port string, user string, password string, dbname s
if err != nil {
log.Println(err)
}
_, err = db.Query("select * from game")
if err != nil {
log.Println(err)
createDb(host, port, user, password, dbname)
db, err = sql.Open("postgres", migrationInfo)
if err != nil {
log.Fatal(err)
}
}
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
log.Println(err)
@@ -114,11 +143,11 @@ func Migrate_db(host string, port string, user string, password string, dbname s
fmt.Println("Migration version before: ", version)
err = m.Force(1)
//err = m.Force(1)
//err = m.Up() // or m.Steps(2) if you want to explicitly set the number of migrations to run
if err != nil {
log.Println("Force err: ", err)
}
//if err != nil {
// log.Println("Force err: ", err)
//}
err = m.Migrate(2)
//err = m.Up() // or m.Steps(2) if you want to explicitly set the number of migrations to run