mirror of
https://github.com/Dvorinka/Bookra.git
synced 2026-06-04 04:22:59 +00:00
57 lines
943 B
Go
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)
|
|
}
|