Skip to content

Commit

Permalink
Explicitly roll back transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
cham11ng committed Mar 24, 2021
1 parent fb0c762 commit 01bd804
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 24 deletions.
6 changes: 0 additions & 6 deletions src/service/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,5 @@ export async function executeOperation<T extends OperationContext>(
await context.params.onFailed(result);
}

if (result.error) {
logDb('Result:\n%O', result);

throw result.error;
}

return result;
}
33 changes: 15 additions & 18 deletions src/util/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { dbLogger, log } from './logger';
import { getConnectionId } from '../config';
import ConnectionConfig from '../domain/ConnectionConfig';
import ConnectionReference from '../domain/ConnectionReference';
import OperationResult from '../domain/operation/OperationResult';

/**
* Database connections given by the user or the CLI frontend.
Expand Down Expand Up @@ -63,39 +64,35 @@ export function createInstance(config: ConnectionConfig): Knex {
* If `dryRun` is true, transaction will not be committed.
*
* @param {ConnectionReference} db
* @param {(trx: Knex.Transaction) => Promise<T>} callback
* @param {(trx: Knex.Transaction) => Promise<OperationResult>} callback
* @param {boolean} dryRun?
* @returns {Promise<T>}
* @returns {Promise<OperationResult>}
*/
export async function withTransaction<T>(
export async function withTransaction(
db: ConnectionReference,
callback: (trx: Knex.Transaction) => Promise<T>,
callback: (trx: Knex.Transaction) => Promise<OperationResult>,
dryRun?: boolean
): Promise<T> {
): Promise<OperationResult> {
const dbLog = dbLogger(db.id);
const trx = await db.connection.transaction();

if (dryRun) {
dbLog('BEGIN: Dry Run transaction');
dbLog(`BEGIN:${dryRun ? ' Dry Run ' : ' '}transaction`);

const trx = await db.connection.transaction();
const res = await callback(trx);
const result = await callback(trx);

if (dryRun || result.error) {
trx.rollback();

dbLog('END: Dry Run transaction rolled back successfully');
dbLog('END: transaction rolled back');

return res;
return result;
}

return db.connection.transaction(async trx => {
dbLog('BEGIN: transaction');

const result = await callback(trx);
trx.commit();

dbLog('END: transaction');
dbLog(`END: transaction committed`);

return result;
});
return result;
}

/**
Expand Down

0 comments on commit 01bd804

Please sign in to comment.