I am having a problem with the latest version of the PostgreSQL JDBC driver: I cannot collect warnings / notifications while the ready statement is still executing. The list of warnings becomes available only after the operator returns.
I used this function with some version of the previous driver (I think 9.1), but the implementation has PgPreparedStatementprobably changed since then.
What are my options for collecting alerts before returning results?
I created this simple test:
public class WarningTest {
@Test
public void readWarnings() throws Exception {
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test_db", "test_user", "test_password");
createTestFunction(con);
PreparedStatement statement = con.prepareStatement("SELECT test_function();");
SQLWarning[] warnings = new SQLWarning[1];
new Timer().schedule(new TimerTask() {
@Override public void run() {
try {
warnings[0] = statement.getWarnings();
} catch (SQLException e) {
Assert.fail("Exception thrown: " + e.getMessage());
}
}
}, 3500);
statement.executeQuery();
Thread.sleep(1000);
statement.close();
Assert.assertNotNull(warnings[0]);
Assert.assertFalse(warnings[0].getMessage().isEmpty());
}
private void createTestFunction(Connection con) throws SQLException {
final PreparedStatement statement = con.prepareStatement(
"CREATE OR REPLACE FUNCTION test_function() RETURNS VOID AS\n"
+ "$BODY$\n"
+ "BEGIN\n"
+ "\tFOR i IN 1..3 LOOP \n"
+ "\t\tRAISE NOTICE 'Tick %', i;\n"
+ "\t\tEXECUTE pg_sleep(1);\n"
+ "\tEND LOOP;\n"
+ "END\n"
+ "$BODY$\n"
+ "\tLANGUAGE plpgsql STABLE;");
statement.execute();
statement.close();
}
}
It creates a function that runs for 3 seconds and writes a check mark at the beginning of every second.
, . 3500 1500, , 2 .