51 lines
905 B
Go
51 lines
905 B
Go
|
package db
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
"github.com/jackc/pgx/v4/pgxpool"
|
||
|
"go.uber.org/zap"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
type Client struct {
|
||
|
pool *pgxpool.Pool
|
||
|
}
|
||
|
|
||
|
func NewClient(l *zap.Logger) *Client {
|
||
|
l.Info("Setting up database connection")
|
||
|
|
||
|
dbPool := setupPool()
|
||
|
testConnection(dbPool)
|
||
|
|
||
|
l.Info("Database successfully connected")
|
||
|
|
||
|
return &Client{pool: dbPool}
|
||
|
}
|
||
|
|
||
|
func setupPool() *pgxpool.Pool {
|
||
|
dbUrl := os.Getenv("DATABASE_URL")
|
||
|
if dbUrl == "" {
|
||
|
panic(errors.New("DATABASE_URL is not set"))
|
||
|
}
|
||
|
dbPool, err := pgxpool.Connect(context.Background(), dbUrl)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
|
return dbPool
|
||
|
}
|
||
|
|
||
|
func testConnection(dbPool *pgxpool.Pool) {
|
||
|
var greeting string
|
||
|
err := dbPool.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (c *Client) GetConn(ctx context.Context) *pgxpool.Conn {
|
||
|
conn, _ := c.pool.Acquire(ctx)
|
||
|
return conn
|
||
|
}
|