Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions internal/pgcompare/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pgcompare

import (
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -130,11 +131,11 @@ func buildDSN() string {
if port == "" {
port = "5432"
}
return fmt.Sprintf(
"postgres://%s:%s@localhost:%s/%s",
os.Getenv("POSTGRES_USER"),
os.Getenv("POSTGRES_PASSWORD"),
port,
os.Getenv("POSTGRES_DB"),
)
u := url.URL{
Scheme: "postgres",
User: url.UserPassword(os.Getenv("POSTGRES_USER"), os.Getenv("POSTGRES_PASSWORD")),
Host: "localhost:" + port,
Path: "/" + os.Getenv("POSTGRES_DB"),
}
return u.String()
}
24 changes: 16 additions & 8 deletions internal/pgcompare/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,27 +104,35 @@ func TestConfigValidate(t *testing.T) {

func TestBuildDSN(t *testing.T) {
tests := []struct {
name string
port string
want string
name, user, pass, db, port, want string
}{
{
name: "all vars present",
port: "9999",
user: "u", pass: "p", db: "d", port: "9999",
want: "postgres://u:p@localhost:9999/d",
},
{
name: "default port",
port: "",
user: "u", pass: "p", db: "d", port: "",
want: "postgres://u:p@localhost:5432/d",
},
{
name: "password with special chars is escaped",
user: "u", pass: "p@ss:w/ord#1", db: "d", port: "5432",
want: "postgres://u:p%40ss%3Aw%2Ford%231@localhost:5432/d",
},
{
name: "user with special chars is escaped",
user: "u@admin", pass: "p", db: "d", port: "5432",
want: "postgres://u%40admin:p@localhost:5432/d",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("POSTGRES_USER", "u")
t.Setenv("POSTGRES_PASSWORD", "p")
t.Setenv("POSTGRES_DB", "d")
t.Setenv("POSTGRES_USER", tt.user)
t.Setenv("POSTGRES_PASSWORD", tt.pass)
t.Setenv("POSTGRES_DB", tt.db)
t.Setenv("POSTGRES_PORT", tt.port)

assert.Equal(t, tt.want, buildDSN())
Expand Down