Skip to content

Commit

Permalink
feat: add support for nested transactions (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
felixmosh authored Oct 13, 2021
1 parent 17d0dbf commit 368c4f3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/Tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ export class Tracker {
public _handle(rawQuery: RawQuery): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(async () => {
if (typeof rawQuery.method === 'undefined' && transactionCommands.includes(rawQuery.sql)) {
if (
typeof rawQuery.method === 'undefined' &&
transactionCommands.some((trxCommand) => rawQuery.sql.startsWith(trxCommand))
) {
return resolve(undefined);
}

Expand Down
8 changes: 7 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
export const queryMethods = ['select', 'insert', 'update', 'delete', 'any'] as const;

export const transactionCommands = ['BEGIN;', 'COMMIT;', 'ROLLBACK'];
export const transactionCommands = [
'BEGIN;',
'COMMIT;',
'ROLLBACK',
'SAVEPOINT',
'RELEASE SAVEPOINT',
];
18 changes: 18 additions & 0 deletions tests/insert.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,22 @@ describe('mock Insert statement', () => {
expect(tracker.history.insert).toHaveLength(1);
expect(tracker.history.delete).toHaveLength(1);
});

it('should support nested transactions', async () => {
tracker.on.insert('table_name').responseOnce(1);
tracker.on.delete('table_name').responseOnce(1);

await db.transaction(async (trx) => {
await db('table_name').insert({ name: faker.name.firstName() }).transacting(trx);
await trx.transaction(async (innerTrx) => {
await db('table_name')
.delete()
.where({ name: faker.name.firstName() })
.transacting(innerTrx);
});
});

expect(tracker.history.insert).toHaveLength(1);
expect(tracker.history.delete).toHaveLength(1);
});
});

0 comments on commit 368c4f3

Please sign in to comment.