Search code examples
gopq

golang database/sql using pq


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...


Solution

  • 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.