github.com/gudimz/urlShortener@v0.0.0-20230129195305-c8ee33059a67/internal/db/postgres/postgres.go (about)

     1  package postgres
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"github.com/gudimz/urlShortener/internal/config"
     7  	"github.com/jackc/pgx/v5"
     8  	"github.com/jackc/pgx/v5/pgconn"
     9  	"github.com/jackc/pgx/v5/pgxpool"
    10  )
    11  
    12  type Client interface {
    13  	Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
    14  	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
    15  	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
    16  	Begin(ctx context.Context) (pgx.Tx, error)
    17  }
    18  
    19  func NewClient(ctx context.Context, pc config.PostgresConfig) (*pgxpool.Pool, error) {
    20  	dsn := fmt.Sprintf("postgres://%s:%s@%s:%s/%s",
    21  		pc.Username,
    22  		pc.Password,
    23  		pc.Host,
    24  		pc.Port,
    25  		pc.DbName)
    26  	pool, err := pgxpool.New(ctx, dsn)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	return pool, nil
    31  }