问题描述
我想为每个执行的查询set运行时变量,而不使用事务。
例如:
SET app.current_user_id = ${userId};
如何确保会话将被隔离并防止数据库出现争用情况?
解决方法
为确保会话将被隔离,您需要使用池中的特定连接。在postgres中,SESSION和CONNECTION是等效的。
typeORM的相关方法是createQueryRunner
。在文档中没有关于此的任何信息,但已在api中进行了记录。
创建一个查询运行器,用于在单个数据库上执行查询 连接。使用查询运行程序,您可以控制查询以 使用单个数据库连接执行并手动控制您的 数据库事务。
用法示例:
const foo = <T>(callback: <T>(em: EntityManager) => Promise<T>): Promise<T> => {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
return new Promise(async (resolve,reject) => {
let res: T;
try {
await queryRunner.connect();
await queryRunner.manager.query(`SET app.current_user_id = ${userId};`)
res = await callback(queryRunner.manager);
} catch (err) {
reject(err);
} finally {
await queryRunner.manager.query(`RESET app.current_user_id`)
await queryRunner.release();
resolve(res);
}
});
};
的回答