I'm configuring PGBouncer as the database connection pool for my application. I'm also using it with the session pool mode.
Due to some application requirements I need to keep a temporary table during the usage of each connection. What I'm currently doing is using the connect_query setting to create my temporary table.
According to the documentation this query "is executed after a connection is established". As far as I have been able to check this means that the connect_query is executed each time a connection is borrowed from the pool.
What I would like to avoid is the following scenario:
- I borrow a connection from the pool, if the physical connection does not exists, it will be created. The connect_query will be executed.
- I return the connection to the pool.
- I request a connection to the pool again, let's suppose that the pool reuses the same connection used in step 1) and returns it. The connect_query is executed again.
UPDATE I'm able to see that the connect_query is being executed once per connection request when connecting to PGBouncer through JDBC and use the connection to execute a query. See the below java class as an example:
public class TestPgbouncerConnectQuery {
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
try {
System.out.println("Iteration: " + i);
Connection conn = getConnection();
executeQuery(conn);
conn.close();
} catch (SQLException e) {
}
}
}
private static Connection getConnection() {
Connection conn = null;
try {
Properties properties = new Properties();
properties.setProperty("user", "myuser");
properties.setProperty("password", "mypass");
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:6432/mydatabase", properties);
conn.setAutoCommit(false);
} catch (Exception e) {
}
return conn;
}
private static void executeQuery(Connection conn) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement("select 1");
ps.executeQuery();
} catch (Exception e) {
} finally {
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
}
}
}
}
}
After executing this code, if I query to pg_stat_statements:
select * from pg_stat_statements
I can see that the connect_query has been executed once per connection retrieved. But if I comment this line, to not execute the query on each iteration:
executeQuery(conn);
I can not reproduce this issue,i.e., in the pg_stat_statements the connect_query does not appear once per connection retrieved.