Search code examples
postgresqlgopq

Go database/sql - Issue Commands on Reconnect


I have a small application written in Go that connects to a PostgreSQL database on another server, utilizing database/sql and lib/pq. When I start the application, it goes through and establishes that all the database tables and indexes exist. As part of this process, it issues a SET search_path TO preferredschema,public command. Then, for the remainder of the database access, I do not have to specify the schema.

From what I've determined from debugging it, when database/sql reconnects (no network is perfect), the application begins failing because the search path isn't set. Is there a way to specify commands that should be executed when it reconnects? I've searched for an event that might be able to be leveraged, but have come up empty so far.

Thanks!


Solution

  • From the fine manual:

    Connection String Parameters
    [...]
    In addition to the parameters listed above, any run-time parameter that can be set at backend start time can be set in the connection string. For more information, see http://www.postgresql.org/docs/current/static/runtime-config.html.

    Then if we go over to the PostgreSQL documentation, you'll see various ways of setting connection parameters such as config files, SET commands, command line switches, ...

    While the desired behavior isn't exactly spelled out, it is suggested that you can put anything you'd SET right into the connection string:

    connStr := "dbname=... user=... search_path=preferredschema,public"
    // -----------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    and since that's all there is for configuring the connection, it should be used for every connection (including reconnects).

    The Connection String Parameters section of the pq documentation also tells you how to quote and escape things if whatever preferredschema really is needs it or if you have to grab a value at runtime and add it to the connection string.