Fix database replacement in PG DSN

This commit is contained in:
Knut Ahlers 2024-06-30 15:14:29 +02:00
parent cf143aaa58
commit aed9ee6684
Signed by: luzifer
SSH key fingerprint: SHA256:/xtE5lCgiRDQr8SLxHMS92ZBlACmATUmF1crK16Ks4E
4 changed files with 10 additions and 9 deletions

View file

@ -48,8 +48,8 @@ INFO[0000] sqlapi started addr="127.0.0.1:7895" ver
- For parameters see [github.com/go-sql-driver/mysql](https://pkg.go.dev/github.com/go-sql-driver/mysql#readme-dsn-data-source-name)
- **Postgres / CockroachDB**
- `postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca`
- `user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca`
- For parameters see [github.com/jackc/pgx/v5](https://pkg.go.dev/github.com/jackc/pgx/v5@v5.6.0/pgconn#ParseConfig)
- The `key=value anotherkey=anothervalue` format is **not** supported
### Request format

View file

@ -3,9 +3,9 @@ package main
import (
"database/sql"
"fmt"
"net/url"
"github.com/go-sql-driver/mysql"
"github.com/jackc/pgx/v5"
_ "github.com/jackc/pgx/v5/stdlib"
)
@ -25,13 +25,14 @@ func connect(database string) (db *sql.DB, err error) {
return db, nil
case "postgres", "pg", "crdb":
connInfo, err := pgx.ParseConfig(cfg.DSN)
u, err := url.Parse(cfg.DSN)
if err != nil {
return nil, fmt.Errorf("parsing DSN: %w", err)
return nil, fmt.Errorf("parsing DSN URL: %w", err)
}
connInfo.Database = database
if db, err = sql.Open("pgx", connInfo.ConnString()); err != nil {
u.Path = fmt.Sprintf("/%s", database)
if db, err = sql.Open("pgx", u.String()); err != nil {
return nil, fmt.Errorf("opening db connection: %w", err)
}

2
go.mod
View file

@ -19,7 +19,7 @@ require (
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.14.0 // indirect

4
go.sum
View file

@ -35,8 +35,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=