1

I'm having this issue

 db, err := sql.Open("postgres", "user=xxx dbname=xxx connect_timeout=5 sslmode=disable")
 if err != nil {
    log.Fatal(err)
 }

I have no postgres installed on my localhost so sql.Open should return some error but actually it is not until I try to prepare a query and finally I get a connection refused error

stmt, err := c.DB.Prepare("SELECT id FROM services WHERE name = $1")
if err != nil {
    log.Fatal(err)
}

is this an expected behaviour? or I'm missing something...

Gavello
  • 1,399
  • 2
  • 13
  • 25
  • 2
    Yes, see related question: [How do I handle opening/closing Db connection in a Go app?](http://stackoverflow.com/questions/40587008/how-do-i-handle-opening-closing-db-connection-in-a-go-app/40587071#40587071) – icza Nov 15 '16 at 10:30

1 Answers1

3

According to this, Yes it is an expected behavior. Open() does not directly open a connection to the database. Instead the first connection is opened when the database is actually used the first time.

Open may just validate its arguments without creating a connection 
to the database. 
To verify that the data source name is valid, call Ping.

Use Ping() to check if the connection is valid or not.

sadlil
  • 3,077
  • 5
  • 23
  • 36