db.go 787 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package postgres
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/jackc/pgx/v5"
  6. "github.com/jackc/pgx/v5/pgxpool"
  7. )
  8. type Store struct {
  9. pool *pgxpool.Pool
  10. }
  11. type Tx = pgx.Tx
  12. func Open(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
  13. pool, err := pgxpool.New(ctx, databaseURL)
  14. if err != nil {
  15. return nil, fmt.Errorf("open postgres pool: %w", err)
  16. }
  17. if err := pool.Ping(ctx); err != nil {
  18. pool.Close()
  19. return nil, fmt.Errorf("ping postgres: %w", err)
  20. }
  21. return pool, nil
  22. }
  23. func NewStore(pool *pgxpool.Pool) *Store {
  24. return &Store{pool: pool}
  25. }
  26. func (s *Store) Pool() *pgxpool.Pool {
  27. return s.pool
  28. }
  29. func (s *Store) Close() {
  30. if s.pool != nil {
  31. s.pool.Close()
  32. }
  33. }
  34. func (s *Store) Begin(ctx context.Context) (pgx.Tx, error) {
  35. return s.pool.Begin(ctx)
  36. }