updatingGolangDB(izin jadi ishowspeed)

This commit is contained in:
MRMARCABLE
2026-09-28 21:09:39 +07:00
commit 3e2c85d729
6 changed files with 200 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
package database
import (
"context"
"fmt"
"log"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"5803025050/internal/config"
)
// ConnectDB establishes a connection pool to the PostgreSQL database
// using the configuration values from Config.
func ConnectDB(cfg *config.Config) (*pgxpool.Pool, error) {
dsn := cfg.DatabaseURL()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
poolConfig, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("unable to parse database config: %w", err)
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("unable to create connection pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("unable to ping database: %w", err)
}
log.Println("database connection established")
return pool, nil
}
// CloseDB gracefully closes the database connection pool.
func CloseDB(pool *pgxpool.Pool) {
if pool != nil {
pool.Close()
log.Println("database connection closed")
}
}