// Package postgres opens the connection pool and applies the schema. // // Pool size and server-side timeouts are constants rather than settings: they // bound how long one request can hold a connection, and the request deadline // of the API is chosen against them. package postgres import ( "context" "errors" "fmt" "strconv" "time" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/stdlib" "github.com/pressly/goose/v3" "github.com/pressly/goose/v3/lock" "messenger/migrations" ) const ( maxConns = 10 connectTimeout = 3 * time.Second statementTimeout = 5 * time.Second idleInTxTimeout = 10 * time.Second ) const codeUniqueViolation = "23505" func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) { cfg, err := pgxpool.ParseConfig(dsn) if err != nil { return nil, fmt.Errorf("parse database url: %w", err) } cfg.MaxConns = maxConns cfg.ConnConfig.ConnectTimeout = connectTimeout cfg.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(statementTimeout.Milliseconds(), 10) cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = strconv.FormatInt(idleInTxTimeout.Milliseconds(), 10) pool, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { return nil, fmt.Errorf("create pool: %w", err) } if err := pool.Ping(ctx); err != nil { pool.Close() return nil, fmt.Errorf("ping database: %w", err) } return pool, nil } // Migrate applies pending migrations. A session advisory lock serialises // concurrent starts, so several API replicas may call it at once; applied // versions are recorded, which makes a repeated run a no-op. func Migrate(ctx context.Context, pool *pgxpool.Pool) error { db := stdlib.OpenDBFromPool(pool) defer db.Close() locker, err := lock.NewPostgresSessionLocker() if err != nil { return fmt.Errorf("migration lock: %w", err) } provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker)) if err != nil { return fmt.Errorf("load migrations: %w", err) } if _, err := provider.Up(ctx); err != nil { return fmt.Errorf("apply migrations: %w", err) } return nil } // IsUniqueViolation reports whether err is a unique violation of the named // constraint. func IsUniqueViolation(err error, constraint string) bool { pgErr, ok := errors.AsType[*pgconn.PgError](err) return ok && pgErr.Code == codeUniqueViolation && pgErr.ConstraintName == constraint }