Node PostgreSQL timeout a query by the client

2019-07-08 12:03发布

问题:

I'm using Node package pg for postgres (here):

npm i pg

var pg = require('pg');

I'm querying a large cluster which is not owned by me, and under certain conditions may fail. Failure may be bad response which is easy to handle or endless query. Please note I can not introduce changes [config or otherwise] on the DB side.

Is there any way to set a timeout for query time? I'd like my client to give up after a set time, and return timeout error.

Couldn't find anything as such in the docs.

Thanks from ahead!

回答1:

Best practice is using an init query, to set query timeout for the session.

    SET statement_timeout TO 15000; # x milliseconds or 0 (turns off limitation)

This takes an argument of the timeout in ms, and is applied for the session. Afterwards, when a query takes longer than the value specified, you will receive an error from the server. Note this is on user's request:

    ERROR:  Query (150) cancelled on user's request

Also note this actually cancels the query on the server side, reducing load.