Search code examples
kubernetesgoogle-cloud-sqlgoroutinesqlxcloud-sql-proxy

Goroutine opening a new connection to database after each request (sqlx) and ticker


Let's consider the following goroutine:

func main(){
    ...
    go dbGoRoutine()
    ...
}

And the func:

func dbGoRoutine() {
    db, err := sqlx.Connect("postgres", GetPSQLInfo())
    if err != nil {
        panic(err)
    }
    defer db.Close()

    ticker := time.NewTicker(10 * time.Second)
    for _ = range ticker.C {
        _, err := db.Queryx("SELECT * FROM table")
        if err != nil {
            // handle
        }
    }
}

Each time the function iterates on the ticker it opens a cloudSQL connection

[service... cloudsql-proxy] 2019/11/08 17:05:05 New connection for "location:exemple-db"

I can't figure out why it opens a new connection each time, since the sqlx.Connect is not in the for loop.


Solution

  • This issue is due to how Query function in sql package, it returns Row which are:

    Rows is the result of a query. Its cursor starts before the first row of the result set.

    Those cursor are stored using cache.

    try using Exec().