Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC postgres query with a timeout

Unfortunately setTimeout is not implemented for JDBC/postgres. Is there some way I can simulate or workaround this? Functionally I want to execute the query and the then break if it takes longer than N seconds

like image 855
deltanovember Avatar asked Jul 24 '09 00:07

deltanovember


3 Answers

The "statement_timeout" looks like what you want.

SET statement_timeout TO 1000; -- for a second
<your_query_here>;
RESET statement_timeout; -- reset
like image 168
Milen A. Radev Avatar answered Nov 17 '22 18:11

Milen A. Radev


One way might be to try running the query in a Timer class. Throw an exception if the Timer ends without a value returned.

Hibernate and JDO supply such a construct. Maybe they'd be good alternatives for you.

like image 33
duffymo Avatar answered Nov 17 '22 18:11

duffymo


Using the LOCAL keyword limits the scope of the statement_timeout to the current transaction. That way, if anything goes wrong (e.g. it times out) the timeout gets reset.

BEGIN TRANSACTION;
SET LOCAL statement_timeout TO 1000;    -- one-second timeout
SELECT COUNT(*) FROM really_huge_table; -- your slow query
ROLLBACK;                               -- reset
like image 1
David Leppik Avatar answered Nov 17 '22 19:11

David Leppik