在 TypeORM 和 PostgreSQL 中管理查询取消:检索长时间运行的请求的 PID

问题描述 投票:0回答:1

我目前正在开发 TypeORM 和 PostgreSQL 设置中的一项功能,我需要处理长时间运行且耗时的请求的取消。为此,我认为我需要跟踪特定 PostgreSQL 连接的进程 ID (PID),以正确取消已请求停止的查询。有谁有经验或知道如何在 TypeORM 中检索查询的 PID?

我正在考虑使用自定义查询来调用 pg_backend_pid(),但我想知道是否有更有效的方法或标准实践来执行此操作,尤其是在生产环境中。 任何有关管理此类查询取消的见解将不胜感激!

node.js postgresql typeorm pid
1个回答
0
投票

TypeORM github 中有这个未解决的问题,因此很可能没有以任何方式实现:https://github.com/typeorm/typeorm/issues/8552

我认为使用

pg_backend_pid()
pg_cancel_backend()
是您最好的选择,您只需确保在同一连接上运行查询和
pg_backend_pid()
即可。

我会如何去做:

// Connection to run queries
// DB is your TypeORM DataSource
const qR = DB.createQueryRunner();

// Assuming desired timeout for a query is 30s
const timeoutId = setTimeout(() => qR.query('SELECT pg_cancel_backend(pg_backend_pid())'), 30_000);

// Run your query
const queryResult = await qR.query('.....');

// If the query completes within 30s the timeout gets cleared so it won't stop any queries in the future
// If the query didn't complete in time the timeout cancels it
clearTimeout(timeoutId);

// Release connection back into the pool
qR.release();

© www.soinside.com 2019 - 2024. All rights reserved.