Skip to content

Commit 8868429

Browse files
committed
refactor: database initialization and migration logic
1 parent d510e99 commit 8868429

2 files changed

Lines changed: 13 additions & 22 deletions

File tree

api/cmd/main.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ package main
33
import (
44
"context"
55
"fmt"
6+
"os"
7+
"strings"
8+
69
"github.com/Yaon-C2H8N2/bahclePlayer/internal/controllers"
710
"github.com/Yaon-C2H8N2/bahclePlayer/internal/models"
811
"github.com/Yaon-C2H8N2/bahclePlayer/internal/services"
912
"github.com/Yaon-C2H8N2/bahclePlayer/pkg/utils"
10-
"os"
11-
"strings"
1213
)
1314
import "github.com/gin-gonic/gin"
1415

@@ -20,7 +21,6 @@ func main() {
2021
}
2122
}
2223

23-
utils.Migrate()
2424
utils.InitDatabase()
2525
utils.InitValkey()
2626

api/pkg/utils/Database.go

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@ package utils
22

33
import (
44
"context"
5-
"database/sql"
65
"fmt"
6+
"log"
7+
"os"
8+
"time"
9+
710
"github.com/golang-migrate/migrate/v4"
811
"github.com/golang-migrate/migrate/v4/database/postgres"
912
_ "github.com/golang-migrate/migrate/v4/source/file"
1013
"github.com/jackc/pgx/v5"
1114
"github.com/jackc/pgx/v5/pgxpool"
12-
"log"
13-
"os"
14-
"time"
15+
"github.com/jackc/pgx/v5/stdlib"
1516
)
1617

1718
var Database *pgxpool.Pool
1819

1920
func InitDatabase() {
2021
connectionString := fmt.Sprintf(
21-
"postgres://%s:%s@%s:%s/%s",
22+
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
2223
os.Getenv("POSTGRES_USER"),
2324
os.Getenv("POSTGRES_PASSWORD"),
2425
os.Getenv("POSTGRES_URL"),
@@ -32,6 +33,7 @@ func InitDatabase() {
3233
}
3334

3435
Database = pool
36+
migrateDatabase(pool)
3537
}
3638

3739
func GetConnection() *pgxpool.Conn {
@@ -56,21 +58,10 @@ func DoRequest(conn *pgxpool.Conn, query string, args ...any) pgx.Rows {
5658
return rows
5759
}
5860

59-
func Migrate() {
60-
connectionString := fmt.Sprintf(
61-
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
62-
os.Getenv("POSTGRES_USER"),
63-
os.Getenv("POSTGRES_PASSWORD"),
64-
os.Getenv("POSTGRES_URL"),
65-
os.Getenv("POSTGRES_PORT"),
66-
os.Getenv("POSTGRES_DB"),
67-
)
61+
func migrateDatabase(pool *pgxpool.Pool) {
62+
db := stdlib.OpenDBFromPool(pool)
63+
fmt.Printf("Migrating database %s\n", pool.Config().ConnConfig.ConnString())
6864

69-
fmt.Printf("Migrating database %s\n", connectionString)
70-
db, err := sql.Open("postgres", connectionString)
71-
if err != nil {
72-
log.Fatal(err)
73-
}
7465
defer func() {
7566
if err := db.Close(); err != nil {
7667
log.Fatal(err)

0 commit comments

Comments
 (0)