Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | 556x 556x 556x 556x 556x 462x 462x 462x 462x 462x 462x 16x 1331x 1331x 14x 1331x 1317x 462x 460x 204x 465x 460x 462x 462x 385x 352x 272x 272x 172x 172x 172x 172x 170x 168x 17x 49x 49x 49x 49x 48x 21x 50x 21x 17x 18x 352x 352x 164x 385x 86x 86x 272x 271x 271x 207x 17x 982x 461x 461x 461x 457x 457x | import { randomUUID } from 'node:crypto';
import type {
Client,
ConnectionManager,
ExecuteOptions,
} from '../connection/connection-manager.ts';
import type { LoggingFunction } from '../connection/options.ts';
import type { RetryOptions, RetryRunner } from '../connection/retry.ts';
import { transactionScope } from './transaction-runner.ts';
import type { DeferrableValue } from '../ddl/ddl-types.ts';
import { AdvisoryLocks, type AdvisoryLockKey } from './advisory-locks.ts';
import { TransactionStatements } from './transaction-statements.ts';
import {
ISOLATION_LEVELS,
LOCK,
TRANSACTION_TYPES,
type IsolationLevel,
} from './transaction-constants.ts';
export { ISOLATION_LEVELS, LOCK, TRANSACTION_TYPES } from './transaction-constants.ts';
export type { AdvisoryLockKey } from './advisory-locks.ts';
export type { IsolationLevel, LockStrength } from './transaction-constants.ts';
/**
* Options of `sequelize.transaction()`.
*
* All fields are optional.
*
* @example
* ```ts
* const options: TransactionOptions = {
* isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
* readOnly: true,
* deferrable: true,
* settings: { 'app.user_id': '42', statement_timeout: '5s' },
* };
* const t = await sequelize.transaction(options);
* await t.commit();
* ```
*/
export type TransactionOptions = Readonly<{
/** Isolation level of a new transaction. */
isolationLevel?: IsolationLevel;
/** Accepted for compatibility, ignored. */
type?: (typeof TRANSACTION_TYPES)[keyof typeof TRANSACTION_TYPES];
/**
* Start `READ ONLY`. PostgreSQL extension.
* @postgrelize
*/
readOnly?: boolean;
/**
* `true` / `false`: start `DEFERRABLE` / `NOT DEFERRABLE`. PostgreSQL honours it only for
* `SERIALIZABLE READ ONLY` transactions: a deferrable one waits for a safe snapshot and then runs
* without serialization failures; ignored for savepoints (PostgreSQL extension).
* `Deferrable.SET_DEFERRED` / `Deferrable.SET_IMMEDIATE` (Sequelize v6): run `SET CONSTRAINTS ... DEFERRED` /
* `IMMEDIATE` right after the transaction starts, for all constraints or the names given.
* @postgrelize
*/
deferrable?: boolean | DeferrableValue;
/** Parent transaction: the new transaction becomes a savepoint inside it. */
transaction?: Transaction | null;
/**
* Session settings applied with `SET LOCAL` semantics (`set_config(name, value, true)`), e.g.
* `{ 'app.user_id': '42', statement_timeout: '5s' }` for row-level security. PostgreSQL extension.
* @postgrelize
*/
settings?: Readonly<Record<string, string | number | boolean>>;
/** SQL logger for transaction statements. */
logging?: LoggingFunction | false;
/**
* Retries acquiring the connection and `BEGIN` (and the statements that follow it, up to the
* first user statement) when they fail, merged over the instance `retry` option (Sequelize v6).
* Ignored for savepoints and for statements inside the transaction. See {@link RetryOptions}.
*/
retry?: RetryOptions;
}>;
/**
* Handle of an open database transaction or savepoint (Sequelize v6 `Transaction`).
*
* Obtain one from `sequelize.transaction()` and pass it to queries with the `transaction` option.
* Unmanaged transactions must be finished with {@link Transaction.commit} or
* {@link Transaction.rollback}; the connection is released to the pool when that happens.
*
* @example
* ```ts
* const t = await sequelize.transaction();
* try {
* const created = await User.create({ name: 'Ann' }, { transaction: t });
* await Post.create({ title: 'Hi', userId: created.id }, { transaction: t });
* await t.commit();
* } catch (e) {
* await t.rollback();
* throw e;
* }
* ```
*/
export class Transaction {
/** Values for the `isolationLevel` option, e.g. `SERIALIZABLE` or `READ_COMMITTED`. */
static readonly ISOLATION_LEVELS = ISOLATION_LEVELS;
/** Row lock strengths. */
static readonly LOCK = LOCK;
/** Transaction types (ignored by PostgreSQL). */
static readonly TYPES = TRANSACTION_TYPES;
/** Unique id, used in SQL logs and as savepoint name. */
readonly id: string = randomUUID();
/** Options the transaction was started with. */
readonly options: TransactionOptions;
/** Parent transaction when this one is a savepoint. */
readonly parent: Transaction | undefined;
/** `'commit'` or `'rollback'` once the transaction is finished. */
finished: 'commit' | 'rollback' | undefined;
readonly #connections: ConnectionManager;
readonly #advisoryLocks: AdvisoryLocks;
readonly #statements: TransactionStatements;
readonly #retries: RetryRunner | undefined;
#client: Client | undefined;
#afterCommit: readonly ((transaction: Transaction) => unknown)[] = [];
/**
* Creates an unstarted transaction; use `sequelize.transaction()` instead of calling this directly.
*
* @param connections - Connection manager of the owning `Sequelize` instance.
* @param options - Transaction options.
* @param retries - Retry settings applied when starting the transaction.
*/
constructor(
connections: ConnectionManager,
options: TransactionOptions = {},
retries?: RetryRunner,
) {
this.#connections = connections;
this.#retries = retries;
this.#advisoryLocks = new AdvisoryLocks(connections, () => this.executeOptions());
this.options = options;
this.parent = options.transaction ?? undefined;
this.#statements = new TransactionStatements(this.id, this.parent !== undefined);
}
/** Row lock strengths (instance alias of {@link Transaction.LOCK}). */
get LOCK(): typeof LOCK {
return LOCK;
}
/** @internal */
get client(): Client {
const client = this.#client ?? this.parent?.client;
if (client === undefined) {
throw new Error('Transaction has not started');
}
return client;
}
/** @internal */
executeOptions(): ExecuteOptions {
return {
client: this.client,
transactionId: this.id,
...(this.options.logging === undefined ? {} : { logging: this.options.logging }),
};
}
/** @internal */
async begin(): Promise<this> {
await (this.parent === undefined && this.#retries !== undefined
? this.#retries.run(() => this.#start(), this.options.retry)
: this.#start());
return this;
}
async #start(): Promise<void> {
if (this.parent === undefined) {
this.#client = await this.#connections.getConnection({ type: 'write', uuid: this.id });
}
try {
await this.#run(this.#statements.begin(this.options));
await this.#applySettings();
await this.#setConstraints();
} catch (error) {
await this.#abortBegin();
throw error;
}
}
/**
* Commits the transaction (or releases the savepoint) and runs `afterCommit` hooks.
*
* @returns Resolves when committed and all `afterCommit` hooks have run.
* @throws Error when the transaction is already finished.
*
* @example
* ```ts
* const t = await sequelize.transaction();
* await User.create({ name: 'Ann' }, { transaction: t });
* await t.commit();
* ```
*/
async commit(): Promise<void> {
this.#assertActive('commit');
// marked at once: a query issued while the COMMIT is on its way is rejected (v6)
this.finished = 'commit';
try {
await this.#run(this.#statements.commit());
} finally {
await this.#release();
}
await this.#afterCommit.reduce<Promise<unknown>>(
(previous, hook) => previous.then(() => hook(this)),
Promise.resolve(),
);
}
/**
* Rolls the transaction back (or rolls back to the savepoint).
*
* @returns Resolves when rolled back.
* @throws Error when the transaction is already finished.
*
* @example
* ```ts
* const t = await sequelize.transaction();
* try {
* await User.create({ name: 'Ann' }, { transaction: t });
* await t.commit();
* } catch (e) {
* await t.rollback();
* }
* ```
*/
async rollback(): Promise<void> {
this.#assertActive('rollback');
this.finished = 'rollback';
try {
await this.#run(this.#statements.rollback());
} finally {
await this.#release();
}
}
/**
* Takes a transaction-level advisory lock (`pg_advisory_xact_lock`), waiting until it is free.
* The lock is released on commit or rollback. PostgreSQL extension.
*
* @postgrelize
* @param key - Integer key, or a string hashed with `hashtextextended`.
* @param options - `shared: true` for a shared lock.
* @returns Resolves when the lock is held.
*
* @example
* ```ts
* await sequelize.transaction(async (t) => {
* await t.advisoryLock('invoice-42');
* await Invoice.update({ status: 'sent' }, { where: { id: 42 }, transaction: t });
* });
* ```
*/
async advisoryLock(
key: AdvisoryLockKey,
options: Readonly<{ shared?: boolean }> = {},
): Promise<void> {
await this.#advisoryLocks.lock(key, options.shared === true);
}
/**
* Tries to take a transaction-level advisory lock without waiting. PostgreSQL extension.
*
* @postgrelize
* @param key - Integer key, or a string hashed with `hashtextextended`.
* @param options - `shared: true` for a shared lock.
* @returns True when the lock was acquired.
*
* @example
* ```ts
* await sequelize.transaction(async (t) => {
* if (await t.tryAdvisoryLock(42, { shared: true })) {
* await Task.findAll({ transaction: t });
* }
* });
* ```
*/
async tryAdvisoryLock(
key: AdvisoryLockKey,
options: Readonly<{ shared?: boolean }> = {},
): Promise<boolean> {
return this.#advisoryLocks.tryLock(key, options.shared === true);
}
/**
* Registers a callback run after a successful commit.
*
* @param hook - Callback receiving this transaction; hooks run in registration order after the
* transaction is committed and are awaited by `commit()`. They never run after a rollback.
*
* @example
* ```ts
* await sequelize.transaction(async (t) => {
* t.afterCommit(() => console.log('committed, safe to notify'));
* await User.create({ name: 'Ann' }, { transaction: t });
* });
* ```
*/
afterCommit(hook: (transaction: Transaction) => unknown): void {
if (typeof hook !== 'function') {
throw new Error('"fn" must be a function');
}
this.#afterCommit = [...this.#afterCommit, hook];
}
async #setConstraints(): Promise<void> {
const { deferrable } = this.options;
if (typeof deferrable !== 'boolean' && deferrable !== undefined) {
await this.#run(deferrable.sql);
}
}
async #applySettings(): Promise<void> {
await Object.entries(this.options.settings ?? {}).reduce<Promise<unknown>>(
(previous, [name, value]) =>
previous.then(() =>
this.#connections.execute(
{ text: 'SELECT set_config($1, $2, true)', values: [name, String(value)] },
this.executeOptions(),
),
),
Promise.resolve(),
);
}
async #abortBegin(): Promise<void> {
if (this.parent === undefined) {
// Never return a connection inside an open (possibly aborted) transaction to the pool.
await this.#run(this.#statements.rollback()).catch(() => undefined);
await this.#release();
}
}
#assertActive(action: string): void {
if (this.finished !== undefined) {
throw new Error(
`Transaction cannot be ${action === 'commit' ? 'committed' : 'rolled back'} because it has been finished with state: ${this.finished}`,
);
}
}
async #run(sql: string): Promise<void> {
await this.#connections.execute({ text: sql, values: [] }, this.executeOptions());
}
async #release(): Promise<void> {
transactionScope.release(this);
const client = this.#client;
if (this.parent === undefined && client !== undefined) {
this.#client = undefined;
await this.#connections.releaseConnection(client);
}
}
}
|