Also replace question options on update so placement grading stays consistent with admin edits, and tune the Postgres pool defaults. Co-authored-by: Cursor <cursoragent@cursor.com>
92 lines
1.9 KiB
Go
92 lines
1.9 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"strconv"
|
|
"time"
|
|
|
|
dbgen "Yimaru-Backend/gen/db"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type Store struct {
|
|
queries *dbgen.Queries
|
|
conn *pgxpool.Pool
|
|
}
|
|
|
|
func NewStore(conn *pgxpool.Pool) *Store {
|
|
|
|
queries := dbgen.New(conn)
|
|
return &Store{
|
|
queries: queries,
|
|
conn: conn,
|
|
}
|
|
}
|
|
|
|
func OpenDB(url string) (*pgxpool.Pool, func(), error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
cfg, err := pgxpool.ParseConfig(url)
|
|
if err != nil {
|
|
return nil, func() {}, err
|
|
}
|
|
|
|
// Sensible production defaults; override via env without changing DB_URL query params.
|
|
cfg.MaxConns = envInt32("DB_MAX_CONNS", 25)
|
|
cfg.MinConns = envInt32("DB_MIN_CONNS", 5)
|
|
cfg.MaxConnLifetime = time.Duration(envInt64("DB_MAX_CONN_LIFETIME_MINUTES", 30)) * time.Minute
|
|
cfg.MaxConnIdleTime = time.Duration(envInt64("DB_MAX_CONN_IDLE_MINUTES", 5)) * time.Minute
|
|
cfg.HealthCheckPeriod = time.Duration(envInt64("DB_HEALTH_CHECK_SECONDS", 30)) * time.Second
|
|
|
|
conn, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, func() {}, err
|
|
}
|
|
|
|
if err := conn.Ping(ctx); err != nil {
|
|
conn.Close()
|
|
return nil, func() {}, err
|
|
}
|
|
|
|
return conn, func() {
|
|
conn.Close()
|
|
}, nil
|
|
}
|
|
|
|
func envInt32(key string, fallback int32) int32 {
|
|
raw := os.Getenv(key)
|
|
if raw == "" {
|
|
return fallback
|
|
}
|
|
n, err := strconv.Atoi(raw)
|
|
if err != nil || n <= 0 {
|
|
return fallback
|
|
}
|
|
return int32(n)
|
|
}
|
|
|
|
func envInt64(key string, fallback int64) int64 {
|
|
raw := os.Getenv(key)
|
|
if raw == "" {
|
|
return fallback
|
|
}
|
|
n, err := strconv.ParseInt(raw, 10, 64)
|
|
if err != nil || n <= 0 {
|
|
return fallback
|
|
}
|
|
return n
|
|
}
|
|
|
|
func (s *Store) BeginTx(ctx context.Context) (*dbgen.Queries, pgx.Tx, error) {
|
|
tx, err := s.conn.Begin(ctx)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
q := s.queries.WithTx(tx)
|
|
return q, tx, nil
|
|
}
|