initial commit
This commit is contained in:
38
db.go
Normal file
38
db.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package libshared
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var Pool *pgxpool.Pool
|
||||
|
||||
func GetDbPool() *pgxpool.Pool {
|
||||
// Construct the connection string
|
||||
// Note: Ensure your Docker Compose env vars match these keys!
|
||||
dburl := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable",
|
||||
os.Getenv("POSTGRES_USER"),
|
||||
os.Getenv("POSTGRES_PASSWORD"),
|
||||
os.Getenv("POSTGRES_HOSTNAME"),
|
||||
os.Getenv("POSTGRES_DB"),
|
||||
)
|
||||
|
||||
var err error
|
||||
// Use pgxpool.New instead of Connect for v5
|
||||
Pool, err = pgxpool.New(context.Background(), dburl)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create connection pool: %v", err)
|
||||
}
|
||||
|
||||
// Ping the database to verify the connection is actually live
|
||||
err = Pool.Ping(context.Background())
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to ping database: %v", err)
|
||||
}
|
||||
|
||||
return Pool
|
||||
}
|
||||
Reference in New Issue
Block a user