PostgreSQL SET runtime variables with typeorm,如何确保会话是隔离的?
PostgreSQL SET runtime variables with typeorm, how to ensure the session is isolated?
我想 set 运行 为每个执行的查询设置时间变量而不使用事务。
例如:
SET app.current_user_id = ${userId};
如何确保会话被隔离并防止数据库出现争用情况?
为确保会话被隔离,您需要使用池中的特定连接。在 postgres 中 SESSION 和 CONNECTION 是等价的。
typeORM的相关方法是createQueryRunner
。文档中没有关于它的信息,但它记录在 api.
Creates a query runner used for perform queries on a single database
connection. Using query runners you can control your queries to
execute using single database connection and manually control your
database transaction.
用法示例:
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);
}
});
};
这也是我对 How to add a request timeout in Typeorm/Typescript?
的回答
我想 set 运行 为每个执行的查询设置时间变量而不使用事务。
例如:
SET app.current_user_id = ${userId};
如何确保会话被隔离并防止数据库出现争用情况?
为确保会话被隔离,您需要使用池中的特定连接。在 postgres 中 SESSION 和 CONNECTION 是等价的。
typeORM的相关方法是createQueryRunner
。文档中没有关于它的信息,但它记录在 api.
Creates a query runner used for perform queries on a single database connection. Using query runners you can control your queries to execute using single database connection and manually control your database transaction.
用法示例:
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);
}
});
};
这也是我对 How to add a request timeout in Typeorm/Typescript?
的回答