ariga / atlas

Manage your database schema as code
https://atlasgo.io
Apache License 2.0
5.72k stars 254 forks source link

Postgres DSN with multiple hosts fails #2158

Open netsensei opened 11 months ago

netsensei commented 11 months ago

Problem

I'm trying to connect to a Postgres cluster using the DSN in atlas.hcl. Note how this contains multiple host entries, which is possible according to the libpq documentation

url = postgres://user:pass@host1:5432,host2:5432,host3:5432/db?target_session_attrs=read-write

However, I get this error message when I run e.g. atlas migrate apply --env myenvironment.

Error: postgres: scanning system variables: dial tcp: lookup host1,host2,host3: no such host

Additionally, this will fail too:

url = postgres://user:pass@host1:5432/db?target_session_attrs=read-write

With this error:

Error: postgres: scanning system variables: pq: unrecognized configuration parameter "target_session_attrs"

Whereas target_session_attrs is important to determine the primary server in a cluster which allows / is suitable for read-write operations; rather then accidentally connecting to a replication node.

Additional information

The same string works without a hitch with github.com/jackc/pgx/v5 e.g. the listing below yields <nil> indicating that a successful connection could be made with a DSN containing multiple hosts. We also use pgx in conjunction with ent and that works perfectly fine.

package main

import (
    "database/sql"
    "log"

    _ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
    db, err := sql.Open("pgx", "postgres://user:pass@localhost,localhost:5432/db?target_session_attrs=read-write")
    if err != nil {
        log.Println(err)
    }

    err = db.Ping()
    log.Println(err)
}
netsensei commented 11 months ago

Taking a little bit of a closer look, it seems like atlas relies on lib/pq however that projects seems to be in maintenance mode.

Moreover, they have an open PR to add multihost support, however it's not getting merged and a key contributor even suggests moving to pgx instead.