github.com/10ego/gthp@v0.0.0-20241025155251-e1514fa71fbb/internal/database/conn.go (about)

     1  package database
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/jackc/pgx/v5/pgxpool"
     9  	"go.uber.org/zap"
    10  )
    11  
    12  // DB represents a database connection pool
    13  type DB struct {
    14  	*pgxpool.Pool
    15  	log *zap.SugaredLogger
    16  }
    17  
    18  // Connect establishes a connection to the database and returns a DB instance
    19  func Connect(databaseURL string, log *zap.SugaredLogger) (*DB, error) {
    20  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    21  	defer cancel()
    22  
    23  	config, err := pgxpool.ParseConfig(databaseURL)
    24  	if err != nil {
    25  		return nil, fmt.Errorf("unable to parse database URL: %v", err)
    26  	}
    27  
    28  	// You can set additional pool configuration here if needed
    29  	// For example:
    30  	// config.MaxConns = 10
    31  	// config.MinConns = 2
    32  
    33  	pool, err := pgxpool.NewWithConfig(ctx, config)
    34  	if err != nil {
    35  		return nil, fmt.Errorf("unable to create connection pool: %v", err)
    36  	}
    37  
    38  	// Verify the connection
    39  	err = pool.Ping(ctx)
    40  	if err != nil {
    41  		return nil, fmt.Errorf("unable to ping database: %v", err)
    42  	}
    43  
    44  	return &DB{Pool: pool, log: log}, nil
    45  }
    46  
    47  // Close closes the database connection pool
    48  func (db *DB) Close() {
    49  	db.Pool.Close()
    50  }
    51  
    52  // Example query method
    53  func (db *DB) GetUserByID(ctx context.Context, id int) (string, error) {
    54  	var name string
    55  	err := db.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)
    56  	if err != nil {
    57  		db.log.Errorw("Error querying user", "error", err, "id", id)
    58  		return "", fmt.Errorf("error querying user: %v", err)
    59  	}
    60  	return name, nil
    61  }