48 lines
931 B
Go
48 lines
931 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func Connect(ctx context.Context, dbURL string) (*pgxpool.Pool, error) {
|
|
pool, err := pgxpool.New(ctx, dbURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to connect to database: %w", err)
|
|
}
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("unable to ping database: %w", err)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|
|
|
|
func Close(pool *pgxpool.Pool) {
|
|
if pool != nil {
|
|
pool.Close()
|
|
}
|
|
}
|
|
|
|
type PostgresDbWrapper struct {
|
|
db *pgxpool.Pool
|
|
}
|
|
|
|
func NewPostgresDbWrapper(db *pgxpool.Pool) DbWrapper {
|
|
return &PostgresDbWrapper{db: db}
|
|
}
|
|
|
|
func (wrapper *PostgresDbWrapper) Exec(ctx context.Context, query string, args ...any) (DbWrapperResult, error) {
|
|
result, err := wrapper.db.Exec(ctx, query, args...)
|
|
if err != nil {
|
|
return DbWrapperResult{}, err
|
|
}
|
|
|
|
return DbWrapperResult{
|
|
AffectedRows: result.RowsAffected(),
|
|
}, nil
|
|
}
|