Files
Bookra/apps/backend/internal/db/pool.go
T
Tomas Dvorak 035ac8ddb5 first commit
2026-04-10 12:01:36 +02:00

57 lines
943 B
Go

package db
import (
"context"
"time"
"bookra/apps/backend/internal/config"
"github.com/jackc/pgx/v5/pgxpool"
)
type Pools struct {
App *pgxpool.Pool
Direct *pgxpool.Pool
}
func NewPools(cfg config.Config) (*Pools, error) {
pools := &Pools{}
if cfg.DatabaseURL != "" {
pool, err := connect(cfg.DatabaseURL)
if err != nil {
return nil, err
}
pools.App = pool
}
if cfg.DatabaseDirectURL != "" {
pool, err := connect(cfg.DatabaseDirectURL)
if err != nil {
return nil, err
}
pools.Direct = pool
}
return pools, nil
}
func (p *Pools) Close() {
if p.App != nil {
p.App.Close()
}
if p.Direct != nil {
p.Direct.Close()
}
}
func (p *Pools) DatabaseConfigured() bool {
return p.App != nil || p.Direct != nil
}
func connect(databaseURL string) (*pgxpool.Pool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return pgxpool.New(ctx, databaseURL)
}