b1f8ac453b
feat!: base template * first bit of templating * codeowners * linuxbased * restart * baseline project * add grpc api and basic integration test * startqueue * queueMsg * splitscripts * migrations * queueintegrationtest * gateway
46 lines
971 B
Go
46 lines
971 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"gotemplate/internal/env"
|
|
"log"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func createConnectionString() string {
|
|
driver := "postgres"
|
|
dbUser := env.GetRequired("DB_USER")
|
|
dbPass := env.GetRequired("DB_PASS")
|
|
dbHost := env.GetRequired("DB_HOST")
|
|
dbPort := env.GetRequired("DB_PORT")
|
|
dbName := env.GetRequired("DB_NAME")
|
|
connStr := fmt.Sprintf("%s://%s:%s@%s:%s/%s?sslmode=disable", driver, dbUser, dbPass, dbHost, dbPort, dbName)
|
|
|
|
return connStr
|
|
}
|
|
|
|
func GetDBPool(ctx context.Context) *pgxpool.Pool {
|
|
connStr := createConnectionString()
|
|
|
|
pool, err := pgxpool.New(ctx, connStr)
|
|
if err != nil {
|
|
log.Fatalf("Unable to create database pool: %v\n", err)
|
|
}
|
|
|
|
return pool
|
|
}
|
|
|
|
func GetDBConn(ctx context.Context) *pgx.Conn {
|
|
connStr := createConnectionString()
|
|
|
|
conn, err := pgx.Connect(ctx, connStr)
|
|
if err != nil {
|
|
log.Fatalf("Unable to connect to database: %v\n", err)
|
|
}
|
|
|
|
return conn
|
|
}
|