fog/internal/db/db.go
2024-12-30 10:02:01 +00:00

31 lines
596 B
Go

package db
import (
"context"
"database/sql"
"log"
"time"
)
func New(addr string, maxOpenConns, maxIdleConns int, maxIdleTime time.Duration) (*sql.DB, error) {
db, err := sql.Open("postgres", addr)
if err != nil {
return nil, err
}
defer db.Close()
log.Println("database connection pool established")
db.SetMaxOpenConns(maxOpenConns)
db.SetMaxIdleConns(maxIdleConns)
db.SetConnMaxIdleTime(maxIdleTime)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
return nil, err
}
return db, nil
}