Search code examples
postgresqlgoresource-leak

If a Go sql.DB is closed, do any unclosed prepared queries get closed?


In a Go program using database/sql, will any unclosed prepared queries be closed when I Close the Postgres DB I'm using?

I've cut this down to a very simple example that does not need the Prepare but still shows the question (I believe I could just pass query string to QueryRow and get an implicit Prepare, but leave it explicit here so I can ask my question):

import (
    "database/sql"
)

// Store struct is the postgres
type Store struct {
    pq *sql.DB
}

type Info struct {
    ID      string `json:"id"`
    Name    string `json:"name"`
}

func (s *Store) GetInfo(id string) Info {
    defer s.pq.Close()
    stmt, err := s.pq.Prepare(`
            SELECT id, name 
            FROM info 
            WHERE id = $1 LIMIT 1
            `)
    if err != nil {
        return Info{}
    }
    var res Info
    _ = stmt.QueryRow(id).Scan(&res.ID, &res.Name)
    return res
}

Solution

  • Technically database/sql definitely expects you to close your own prepared statements and doesn't do it for you when the DB or DC is closed. Further I thought it was possible the server might cleanup the backend memory when your program exits but PostgreSQL will also not clean it up...

    https://github.com/lib/pq/issues/446

    If you get the implicit Prepare then database/sql will handle cleaning up for you but that'll be less efficient if you're running these queries over and over so I'd strongly encourage you to clean up after yourself with a:

    defer stmt.Close()
    

    or similar.