Skip to content

Commit

Permalink
fix: attach FOR NO KEY UPDATE lock to query if required
Browse files Browse the repository at this point in the history
FOR NO KEY UPDATE was introduced in typeorm 0.2.25 but the relevant query
part was never added due to missing check in FindOptionUtils

Closes: typeorm#7717
  • Loading branch information
das-mensch committed Aug 2, 2021
1 parent f7eb46d commit db4d970
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/find-options/FindOptionsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,14 @@ export class FindOptionsUtils {
if (options.lock) {
if (options.lock.mode === "optimistic") {
qb.setLock(options.lock.mode, options.lock.version);
} else if (options.lock.mode === "pessimistic_read" || options.lock.mode === "pessimistic_write" || options.lock.mode === "dirty_read" || options.lock.mode === "pessimistic_partial_write" || options.lock.mode === "pessimistic_write_or_fail") {
} else if (
options.lock.mode === "pessimistic_read" ||
options.lock.mode === "pessimistic_write" ||
options.lock.mode === "dirty_read" ||
options.lock.mode === "pessimistic_partial_write" ||
options.lock.mode === "pessimistic_write_or_fail" ||
options.lock.mode === "for_no_key_update"
) {
const tableNames = options.lock.tables ? options.lock.tables.map((table) => {
const tableAlias = qb.expressionMap.aliases.find((alias) => {
return alias.metadata.tableNameWithoutPrefix === table;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,27 @@ describe("repository > find options > locking", () => {

})));

it("should attach for no key update lock statement on query if locking enabled", () => Promise.all(connections.map(async connection => {
if (!(connection.driver instanceof PostgresDriver))
return;

const executedSql: string[] = [];

await connection.manager.transaction(entityManager => {
const originalQuery = entityManager.queryRunner!.query.bind(entityManager.queryRunner);
entityManager.queryRunner!.query = (...args: any[]) => {
executedSql.push(args[0]);
return originalQuery(...args);
};

return entityManager
.getRepository(PostWithVersion)
.findOne(1, { lock: { mode: "for_no_key_update" } });
});

expect(executedSql.join(" ").includes("FOR NO KEY UPDATE")).to.be.true;
})));

it("should attach pessimistic write lock statement on query if locking enabled", () => Promise.all(connections.map(async connection => {
if (connection.driver instanceof AbstractSqliteDriver || connection.driver instanceof CockroachDriver || connection.driver instanceof SapDriver)
return;
Expand Down

0 comments on commit db4d970

Please sign in to comment.