package database import ( "context" "log/slog" "time" "git.runcible.io/learning/pulley/internal/config" pgx "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) // https://medium.com/@neelkanthsingh.jr/understanding-database-connection-pools-and-the-pgx-library-in-go-3087f3c5a0c // pgxpool.New implicitly creates a dbConfig from the database uri params which can include connection params // newPgxConfig creates a pgxpool Config from the application service config // func newPgxConfig(cfg config.ServiceConfig) (pgxpool.Config, error) { // dbconfig, err := pgxpool.ParseConfig(cfg.DatabaseUri) // } // OpenPgPool creates a db pool and tests connectivity func OpenPgPool(ctx context.Context, cfg config.ServiceConfig) (*pgxpool.Pool, error) { pool, err := pgxpool.New(ctx, cfg.DatabaseUri) if err != nil { return nil, err } timoutCtx, close := context.WithTimeout(ctx, 5*time.Second) defer close() if err := pool.Ping(timoutCtx); err != nil { slog.Error("Error in attempting first postgres database connection") pool.Close() return nil, err } return pool, nil } type PgxIface interface { Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) } // TODO determine if this is even useful. Sqlc does produce type DBQuierier struct { db *pgxpool.Pool } func (q *DBQuierier) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { return q.db.Query(ctx, sql, args...) } func (q *DBQuierier) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { return q.db.QueryRow(ctx, sql, args...) } func (q *DBQuierier) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) { return q.db.BeginTx(ctx, txOptions) }