serverctl/pkg/db/db.go

51 lines
905 B
Go
Raw Normal View History

2022-02-13 21:45:27 +01:00
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
}