package db import ( "context" "database/sql" "errors" "fmt" _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver ) // openPostgres connects with pgx. The DSN is a connection URL such as // postgres://user:pass@host:5432/dbname?sslmode=require. func openPostgres(ctx context.Context, dsn string) (*DB, error) { if dsn == "" { return nil, errors.New("db: postgres needs a connection URL") } sqldb, err := sql.Open("pgx", dsn) if err != nil { return nil, err } sqldb.SetMaxOpenConns(20) sqldb.SetMaxIdleConns(10) if err := sqldb.PingContext(ctx); err != nil { sqldb.Close() // The driver's error can quote the DSN, which holds the password. return nil, fmt.Errorf("db: cannot connect to postgres: %s", redactDSN(err.Error(), dsn)) } return &DB{SQL: sqldb, Dialect: Postgres}, nil } // redactDSN removes the connection string from an error message. func redactDSN(msg, dsn string) string { out := msg for i := 0; i+len(dsn) <= len(out); { if out[i:i+len(dsn)] == dsn { out = out[:i] + "[dsn]" + out[i+len(dsn):] continue } i++ } return out } // LockUser serializes transactions that check and then change a user's // rows, such as "count active jobs, then insert one". SQLite does this by // itself, because every transaction holds the write lock. Postgres runs // transactions side by side, so two fast requests could both pass the // check. The advisory lock is held until the transaction ends. func (s *Store) LockUser(ctx context.Context, userID int64) error { if s.db.Dialect != Postgres || !s.inTx { return nil } _, err := s.q.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, userID) return err } // LockJob takes a row lock on a job until the transaction ends, so that // its status cannot change between reading it and acting on it. Without // it Postgres lets, for example, a worker claim a job in the moment a // requester cancels it. SQLite needs nothing: its transactions are serial. func (s *Store) LockJob(ctx context.Context, jobID string) error { if s.db.Dialect != Postgres || !s.inTx { return nil } var id string err := s.q.QueryRowContext(ctx, `SELECT id FROM jobs WHERE id = $1 FOR UPDATE`, jobID).Scan(&id) if errors.Is(err, sql.ErrNoRows) { return ErrNotFound } return err }