pgx icon indicating copy to clipboard operation
pgx copied to clipboard

Connection mode changes from TCP to UNIX socket in pgx/v5

Open dwiw96 opened this issue 2 years ago • 1 comments

Bug Description pgx/v5 tries to connect via Unix socket instead of TCP to postgres inside docker on my local computer. The error was the same as #661 and #596, but in my case it only occurred when using pgx/v5.

Given the following code:

dbpool, err := pgxpool.New(context.Background(), os.Getenv("postgresql://pg:secret@exchange_rate:5432/exchange?sslmode=disable"))
if err != nil {
	fmt.Fprintf(os.Stderr, "Unable to create connection pool: %v\n", err)
	os.Exit(1)
}
defer dbpool.Close()
var greeting string
err = dbpool.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
if err != nil {
	fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
	os.Exit(1)
}

fmt.Println(greeting)

The output:

QueryRow failed: failed to connect to `host=/tmp user=dwiw22 database=`: dial error (dial unix /tmp/.s.PGSQL.5432: connect: no such file or directory)

I also tried using ParseConfig

config, err := pgxpool.ParseConfig("postgresql://pg:secret@exchange_rate:5432/exchange?sslmode=disable") 
if err != nil {
	log.Fatal(err)
}

dbpool, err := pgxpool.New(context.Background(), config.ConnString())

The output :

QueryRow failed: failed to connect to `host=exchange_rate user=pg database=exchange`: hostname resolving error (lookup exchange_rate on 127.0.0.53:53: server misbehaving)

code to run postgres inside docker:

docker run --rm --name exchange_rate -p 5432:5432 -e POSTGRES_USER=pg -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=exchange postgres

Parseconfig

  • host: (postgres_exchange_rate)
  • database: exchange
  • pass: secret
  • port: 5432
  • user: pg

I tried use pgx/v4 and pgx/v4/pgxpool, both are working correctly. This error only occurs for pgx/v5. I also tried to use localhost:5432 and empty the POSTGRES_ADDRESS but the same error still occurred. I already following suggestion from #661 to differentiated the host from directory names. Is this expected behaviour? am I doing something wrong?

Version

  • Linux: Ubuntu 22.04.3 LTS
  • Go: go version go1.20.3 linux/amd64
  • Docker: Docker version 24.0.7, build afdd53b
  • PostgreSQL: PostgreSQL 15.2 (Debian 15.2-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
  • pgx: github.com/jackc/pgx/v5 v5.4.3

Additional Info docker container list output: docker container list

dwiw96 avatar Nov 03 '23 01:11 dwiw96

dbpool, err := pgxpool.New(context.Background(), os.Getenv("postgresql://pg:secret@exchange_rate:5432/exchange?sslmode=disable"))

I think you want to pass your conn string directly, not to get an environment variable with the name of your conn string.

That would explain the behavior you are seeing. The conn string pgx is receiving is actually empty, and pgx defaults to unix socket when possible.

jackc avatar Nov 04 '23 15:11 jackc