50 lines
1.0 KiB
Go
50 lines
1.0 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
var connPool *pgxpool.Pool
|
|
|
|
func InitDB(connString string) error {
|
|
poolConfig, err := pgxpool.ParseConfig(connString)
|
|
if err != nil {
|
|
return fmt.Errorf("error while parsing connection string: %w", err)
|
|
}
|
|
|
|
poolConfig.MaxConns = 10
|
|
poolConfig.MinConns = 0
|
|
poolConfig.MaxConnLifetime = time.Hour
|
|
poolConfig.HealthCheckPeriod = 30 * time.Second
|
|
|
|
connPool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
|
if err != nil {
|
|
return fmt.Errorf("error while initializing DB connection pool: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func transaction(ctx context.Context, handler func(pgx.Tx) (statusCode int, err error)) (statusCode int, err error) {
|
|
tx, err := connPool.Begin(ctx)
|
|
if err != nil {
|
|
statusCode = http.StatusInternalServerError
|
|
return
|
|
}
|
|
statusCode, err = handler(tx)
|
|
if err != nil {
|
|
tx.Rollback(ctx)
|
|
return
|
|
}
|
|
err = tx.Commit(ctx)
|
|
if err != nil {
|
|
statusCode = http.StatusInternalServerError
|
|
}
|
|
return
|
|
}
|