updatingGolangDB(izin jadi ishowspeed)
This commit is contained in:
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user