feat(pgdb): add DATABASE_URI environment variable support
Add support for PostgreSQL connection URIs via DATABASE_URI env var. When set, it takes precedence over config files and PoolOptions are ignored (pool settings can be specified in URI query string).
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package pgdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -149,3 +152,63 @@ func TestCreatePoolConfigDefaults(t *testing.T) {
|
||||
t.Errorf("Expected default Port=5432, got %d", poolCfg.ConnConfig.Port)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenPoolWithDatabaseURI(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test")
|
||||
}
|
||||
|
||||
// This test requires a running PostgreSQL instance
|
||||
uri := os.Getenv("TEST_DATABASE_URI")
|
||||
if uri == "" {
|
||||
t.Skip("TEST_DATABASE_URI not set")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
t.Setenv("DATABASE_URI", uri)
|
||||
|
||||
pool, err := OpenPool(ctx, DefaultPoolOptions())
|
||||
if err != nil {
|
||||
t.Fatalf("OpenPool failed: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Verify connection works
|
||||
var result int
|
||||
err = pool.QueryRow(ctx, "SELECT 1").Scan(&result)
|
||||
if err != nil {
|
||||
t.Fatalf("query failed: %v", err)
|
||||
}
|
||||
if result != 1 {
|
||||
t.Errorf("expected 1, got %d", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabaseURIPrecedence(t *testing.T) {
|
||||
// Test that DATABASE_URI takes precedence over config files
|
||||
// We use localhost with a port that's unlikely to have postgres running
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Set DATABASE_URI to a parseable URI pointing to a non-listening port
|
||||
t.Setenv("DATABASE_URI", "postgres://testuser:testpass@127.0.0.1:59999/testdb?connect_timeout=1")
|
||||
|
||||
// Set config files to a nonexistent path - if this were used, we'd get
|
||||
// "config file not found" error instead of connection refused
|
||||
opts := DefaultPoolOptions()
|
||||
opts.ConfigFiles = []string{"/nonexistent/path/database.yaml"}
|
||||
|
||||
_, err := OpenPool(ctx, opts)
|
||||
|
||||
// Should fail with connection error (not config file error)
|
||||
// This proves DATABASE_URI was used instead of config files
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
||||
// The error should be about connection failure, not about missing config file
|
||||
errStr := err.Error()
|
||||
if strings.Contains(errStr, "config file") || strings.Contains(errStr, "no such file") {
|
||||
t.Errorf("expected connection error, got config file error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user