最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node PostgreSQL timeout a query by the client - Stack Overflow

programmeradmin2浏览0评论

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!

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!

Share Improve this question edited Aug 9, 2015 at 15:49 Selfish asked Aug 9, 2015 at 12:45 SelfishSelfish 6,1904 gold badges46 silver badges66 bronze badges 1
  • 1 Only via cancel command, it seems, according to the author: github.com/brianc/node-postgres/issues/518 – vitaly-t Commented Aug 10, 2015 at 16:46
Add a comment  | 

2 Answers 2

Reset to default 14

You can setup statement_timeout in the client:

const { Client } = require('pg')

const client = new Client({
  statement_timeout: 10000
})

or in the pool:

const { Pool } = require('pg')

const pool = new Pool({
  statement_timeout: 10000
})

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.

发布评论

评论列表(0)

  1. 暂无评论