Files
Crussell/backend/db/db_dev.go
T
popertots 0ac69a92c7
Backend Tests / test (push) Failing after 49s
fix(db): use POSTGRES_HOST env var in dev Connect()
The dev-tagged Connect() in db_dev.go hardcoded localhost:5432 in the
DSN instead of reading the POSTGRES_HOST env var. Since CI tests run
with -tags "test,dev", db_dev.go is compiled and the POSTGRES_HOST=postgres
env var was silently ignored, causing db package tests to try connecting
to 127.0.0.1:5432 where no PostgreSQL is listening (service container
is only reachable via Docker DNS hostname postgres).

Also remove the -a flag from the workflow now that caching is no longer
suspected of causing issues.
2026-06-25 01:08:28 +01:00

70 lines
1.2 KiB
Go

//go:build dev
// +build dev
package db
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
var Conn *PoolProxy
func Connect() error {
// Connect to Postgres inside Docker network
dsn := fmt.Sprintf(
"postgres://%s:%s@%s:5432/%s?sslmode=disable&require_auth=scram-sha-256",
getEnv("POSTGRES_USER"),
getEnv("POSTGRES_PASSWORD"),
getEnv("POSTGRES_HOST"),
getEnv("POSTGRES_DB"),
)
poolCfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return err
}
poolCfg.ConnConfig.RuntimeParams["timezone"] = "UTC"
pool, err := pgxpool.NewWithConfig(context.Background(), poolCfg)
if err != nil {
return err
}
Conn = NewPoolProxy(pool)
err = testDB()
if err != nil {
return err
}
return nil
}
func testDB() error {
ctx := context.Background()
conn, err := Conn.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
row := conn.QueryRow(ctx, "SELECT 1")
var result int
err = row.Scan(&result)
if err != nil {
return err
}
return nil
}
func getEnv(key string) string {
if val := os.Getenv(key); val != "" {
return val
}
// Return empty string instead of fatal error - allows tests to run without prod env vars
return ""
}