lib / pq

Pure Go Postgres driver for database/sql
https://pkg.go.dev/github.com/lib/pq
MIT License
8.98k stars 909 forks source link

database/sql: Open silently connects to default database when url is quoted #1009

Open vHanda opened 3 years ago

vHanda commented 3 years ago
$ go version
go version go1.15.3 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/vishesh/Library/Caches/go-build"
GOENV="/Users/vishesh/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/vishesh/go/pkg/mod"
GONOPROXY="*.emobg.tech,*.ubeeqo.com"
GONOSUMDB="*.emobg.tech,*.ubeeqo.com"
GOOS="darwin"
GOPATH="/Users/vishesh/go"
GOPRIVATE="*.emobg.tech,*.ubeeqo.com"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/Cellar/go/1.15.3/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.15.3/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/7s/rqcr3mc96lv7j4s__zcjrcfm0000gn/T/go-build312611641=/tmp/go-build -gno-record-gcc-switches -fno-common"

Tested on linux as well.

What did you do?

When using sql.Open if you accidentally pass it a string which has quotes, it doesn't fail and silently tries to connect to the localhost with the default settings instead.

It should fail and an error should be shown.

package main

import (
    "database/sql"
    "log"

    _ "github.com/lib/pq"
)

func main() {
    dbUrl := "\"postgres://username:password@postgres:5432/postgres?sslmode=disable\""
    db, err := sql.Open("postgres", dbUrl)
    if err != nil {
        log.Panic("sqlx connect failed", err)
        return
    }

    err = db.Ping()
    if err != nil {
        log.Panic("Ping failed: ", err)
    }
}

What did you expect to see?

A clear error instead of it silently deciding to connect to a different database.

What did you see instead?

2020/11/04 20:21:55 Ping failed: dial tcp [::1]:5432: connect: connection refused
panic: Ping failed: dial tcp [::1]:5432: connect: connection refused

goroutine 1 [running]:
log.Panic(0xc0000f7f58, 0x2, 0x2)
    /usr/local/Cellar/go/1.15.3/libexec/src/log/log.go:351 +0xae
main.main()
    /Users/vishesh/src/gitjournal/gotrue/main.go:20 +0x14a

It's connecting to the database in localhost instead of the host postgres as specified.


Originally reported in golang - https://github.com/golang/go/issues/42380 - however this doesn't occur with the mysql driver.