Skip to content

Commit

Permalink
feat: wrap inline result update inside a transaction (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
invisal authored Jul 27, 2023
1 parent c1e7bf8 commit 14f1e12
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 21 deletions.
54 changes: 34 additions & 20 deletions src/libs/SqlRunnerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ interface SqlExecuteOption {
onStart?: () => void;
skipProtection?: boolean;
disableAnalyze?: boolean;
insideTransaction?: boolean;
}

export class SqlRunnerManager {
Expand All @@ -44,6 +45,12 @@ export class SqlRunnerManager {
const result: SqlStatementResult[] = [];
const parser = new Parser();

// We only wrap transaction if it is multiple statement and
// insideTransactin is specified. Single statement, by itself, is
// transactional already.
const shouldStartTransaction =
!!options?.insideTransaction && statements.length > 1;

const finalStatements: SqlStatementWithAnalyze[] = options?.disableAnalyze
? statements
: statements.map((statement) => {
Expand All @@ -65,33 +72,40 @@ export class SqlRunnerManager {
}
}

for (const statement of finalStatements) {
for (const cb of this.beforeEachCallbacks) {
if (!(await cb(statement, options?.skipProtection))) {
throw 'Cancel';
try {
if (shouldStartTransaction) await this.executor('START TRANSACTION;');
for (const statement of finalStatements) {
for (const cb of this.beforeEachCallbacks) {
if (!(await cb(statement, options?.skipProtection))) {
throw 'Cancel';
}
}
}

if (options?.onStart) options.onStart();
if (options?.onStart) options.onStart();

console.log(statement.sql);
console.log(statement.sql);

const returnedResult = await this.executor(
statement.sql,
statement.params
);
const returnedResult = await this.executor(
statement.sql,
statement.params
);

if (!returnedResult?.error) {
result.push({
statement,
result: returnedResult,
});
} else {
throw returnedResult.error;
if (!returnedResult?.error) {
result.push({
statement,
result: returnedResult,
});
} else {
throw returnedResult.error;
}
}
}

return result;
if (shouldStartTransaction) await this.executor('COMMIT;');
return result;
} catch (e) {
if (shouldStartTransaction) await this.executor('ROLLBACK;');
throw e;
}
}

registerBeforeAll(cb: BeforeAllEventCallback) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export default function QueryResultAction({
}));

runner
.execute(rawSql)
.execute(rawSql, { insideTransaction: true })
.then(() => {
const changes = collector.getChanges();

Expand Down

0 comments on commit 14f1e12

Please sign in to comment.