Skip to content

Commit c88ce2b

Browse files
committed
refactor: add precommit hook support to transaction management
Signed-off-by: Vladislav Polyakov <[email protected]>
1 parent 452ba1f commit c88ce2b

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

packages/query/src/index.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,13 @@ export type SQL = <T extends any[] = unknown[], P extends any[] = unknown[]>(
1515
...values: P
1616
) => Query<T>
1717

18+
export type RegisterPrecommitHook = (fn: () => Promise<void> | void) => void;
19+
1820
export type TX = SQL & {
1921
nodeId: bigint
2022
sessionId: string
2123
transactionId: string
24+
registerPrecommitHook: RegisterPrecommitHook
2225
}
2326

2427
interface SessionContextCallback<T> {
@@ -166,9 +169,24 @@ export function query(driver: Driver): QueryClient {
166169
store.transactionId = beginTransactionResult.txMeta?.id
167170

168171
try {
169-
let tx = Object.assign(yqlQuery, { nodeId: store.nodeId, sessionId: store.sessionId, transactionId: store.transactionId }) as TX
172+
let tx = Object.assign(yqlQuery, {
173+
nodeId: store.nodeId,
174+
sessionId: store.sessionId,
175+
transactionId: store.transactionId,
176+
registerPrecommitHook: (fn: () => Promise<void> | void) => {
177+
if (!store.precommitHooks) store.precommitHooks = [];
178+
store.precommitHooks.push(fn);
179+
},
180+
}) as TX
170181
let result = await ctx.run(store, () => caller!(tx, signal))
171182

183+
// --- precommit hooks: call before commit ---
184+
if (store.precommitHooks && store.precommitHooks.length > 0) {
185+
for (const hook of store.precommitHooks) {
186+
await hook();
187+
}
188+
}
189+
172190
let commitResult = await client.commitTransaction({ sessionId: store.sessionId, txId: store.transactionId }, { signal })
173191
if (commitResult.status !== StatusIds_StatusCode.SUCCESS) {
174192
throw new CommitError("Transaction commit failed.", new YDBError(commitResult.status, commitResult.issues))

0 commit comments

Comments
 (0)