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 | 131x 798x 798x 798x 798x 798x 798x 792x 792x 1x 1x 20070x 20070x 4x 20066x 20066x 38x 20070x 20070x 20066x 4x 20104x 20104x 104x 344x 33x 33x 779x 779x 798x 798x 1605x 798x 19x 792x 6x 7x 792x 18746x 18746x 9x 29x 92x 792x 1289x 38351x 38x 66x 312x 92x 12x 92x | import type { ConnectionConfig } from '../connection/connection-config.ts';
import { ConnectHooks } from '../connection/connect-hooks.ts';
import { ConnectionManager } from '../connection/connection-manager.ts';
import type { ExecuteOptions, QueryResult } from '../connection/connection-types.ts';
import { NotificationListener, type NotificationHandler } from '../connection/notifications.ts';
import type {
ConnectionConfig as ConnectionSettings,
SequelizeOptions,
} from '../connection/options.ts';
import { QueryLogger } from '../connection/query-logger.ts';
import { RetryRunner } from '../connection/retry.ts';
import { PgErrorMapper } from '../errors/map-pg-error.ts';
import { HookRegistry } from '../hooks/hooks.ts';
import type { ModelAttributes } from '../model/model-definition.ts';
import type { AnyModel, ModelStatic } from '../model/options.ts';
import type { ModelRuntime, QueryOptionsBase } from '../model/runtime.ts';
import { RawQuery, ROUTED_QUERY } from '../query/raw-query.ts';
import type { QueryInterface } from '../query-interface/query-interface.ts';
import type { CompiledQuery } from '../sql/compile.ts';
import type { Transaction, TransactionOptions } from '../transaction/transaction.ts';
import { transactionScope } from '../transaction/transaction-runner.ts';
import { TransactionStarter } from '../transaction/transaction-starter.ts';
const rawQuery = new RawQuery();
/** What the internals need from the owning `Sequelize` instance. */
export type InternalsOwner = Readonly<{
models: Record<string, ModelStatic<AnyModel>>;
config: ConnectionSettings;
define: (name: string, attributes: ModelAttributes, options?: Record<string, unknown>) => object;
getQueryInterface: () => QueryInterface;
query: (sql: string, options: object) => Promise<unknown>;
}>;
/**
* State and services behind a `Sequelize` instance: hooks, connections, query execution,
* transactions, notifications and the runtime handed to models.
*
* @internal
*/
export class SequelizeInternals {
/** Hooks registered on the instance. */
hooks: HookRegistry;
/** Pools of the instance. */
readonly connections: ConnectionManager;
/** Schema API, created on first use. */
queryInterface: QueryInterface | undefined;
/** Services provided to models. */
readonly runtime: ModelRuntime;
readonly #owner: InternalsOwner;
readonly #retries: RetryRunner;
readonly #transactions: TransactionStarter;
#serverVersion: Promise<number> | undefined;
#notifier: NotificationListener | undefined;
/**
* @param owner - The `Sequelize` instance.
* @param connectionConfig - Normalized connection configuration.
*/
constructor(owner: InternalsOwner, connectionConfig: ConnectionConfig) {
this.#owner = owner;
this.hooks = HookRegistry.fromOption(connectionConfig.options.hooks);
this.connections = this.#createConnections(connectionConfig);
this.#retries = new RetryRunner(connectionConfig.options.retry);
this.#transactions = new TransactionStarter(this.connections, this.#retries);
this.runtime = this.#createRuntime(connectionConfig.options);
}
/**
* Makes `sequelize.options.hooks = {...}` replace the global hooks, as in v6 (tests and apps reset them that way).
*
* @param options - The `options` object of the instance.
*/
watchOptionHooks(options: SequelizeOptions): void {
let current = options.hooks;
Object.defineProperty(options, 'hooks', {
configurable: true,
enumerable: true,
get: () => current,
set: (value: SequelizeOptions['hooks']) => {
current = value;
this.hooks = HookRegistry.fromOption(value);
},
});
}
/**
* Runs a compiled query on the pool or transaction the options select.
*
* @param query - Query text and values.
* @param options - Transaction, logging and routing options.
* @param kind - `'read'` queries may run on a replica.
* @returns Query result.
*/
execute(
query: CompiledQuery,
options: QueryOptionsBase,
kind: 'read' | 'write' = 'write',
): Promise<QueryResult> {
const finished = SequelizeInternals.#finishedTransaction(query, options);
if (finished !== undefined) {
return Promise.reject(finished);
}
const settings = this.executeOptions(options, kind);
// A statement inside a transaction is never retried: PostgreSQL has aborted the transaction.
return settings.client === undefined && this.#retries.active(options.retry)
? this.#retries.run(() => this.connections.execute(query, settings), options.retry)
: this.connections.execute(query, settings);
}
// A query on a transaction that was committed or rolled back is rejected with the v6 message and `sql`.
static #finishedTransaction(query: CompiledQuery, options: QueryOptionsBase): Error | undefined {
const transaction = options.transaction;
if (transaction?.finished === undefined) {
return undefined;
}
return Object.assign(
new Error(
`${transaction.finished} has been called on this transaction(${transaction.id}), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)`,
),
{ sql: query.text },
);
}
/**
* Resolves the transaction, replica route and logging of one query.
*
* @param options - Query options.
* @param kind - `'read'` queries may run on a replica.
* @returns Connection manager execute options.
*/
executeOptions(options: QueryOptionsBase, kind: 'read' | 'write' = 'write'): ExecuteOptions {
const transaction =
options.transaction === undefined
? transactionScope.active()
: (options.transaction ?? undefined);
return {
...(transaction === undefined ? {} : transaction.executeOptions()),
...(transaction === undefined && kind === 'read' && options.useMaster !== true
? { route: 'read' as const }
: {}),
...(options.logging === undefined ? {} : { logging: options.logging }),
...(options.benchmark === undefined ? {} : { benchmark: options.benchmark }),
...(options.statementTimeout === undefined
? {}
: { statementTimeout: options.statementTimeout }),
};
}
/**
* Starts an unmanaged transaction.
*
* @param options - Transaction options.
* @returns Started transaction.
*/
begin(options: TransactionOptions = {}): Promise<Transaction> {
return this.#transactions.begin(options);
}
/**
* Runs `run` in a managed transaction.
*
* @param options - Transaction options.
* @param run - Callback receiving the transaction.
* @returns Result of `run`.
*/
managed<T>(
options: TransactionOptions,
run: (transaction: Transaction) => Promise<T>,
): Promise<T> {
return this.#transactions.managed(options, run);
}
/**
* Subscribes to a `NOTIFY` channel.
*
* @param channel - Channel name.
* @param handler - Notification handler.
* @returns Function that unsubscribes the handler.
*/
listen(channel: string, handler: NotificationHandler): Promise<() => Promise<void>> {
this.#notifier ??= new NotificationListener(() => this.connections.dedicated());
return this.#notifier.listen(channel, handler);
}
/**
* Closes the notification connection and all pools.
*
* @returns Resolves when closed.
*/
async close(): Promise<void> {
await this.#notifier?.close();
await this.connections.close();
}
#createConnections(connectionConfig: ConnectionConfig): ConnectionManager {
const { options } = connectionConfig;
const pools = connectionConfig.replicationPoolConfigs();
const hooks = new ConnectHooks(() => this.hooks, this.#owner);
return new ConnectionManager(
hooks.apply(pools.write),
pools.read.map((config) => hooks.apply(config)),
QueryLogger.fromOptions(options),
new PgErrorMapper(),
options.statementCache,
);
}
#createRuntime(options: SequelizeOptions): ModelRuntime {
return {
...this.#queryRuntime(),
...this.#modelRuntime(),
beginTransaction: (transactionOptions) => this.begin(transactionOptions),
transaction: (run, parent) =>
this.managed(parent === undefined || parent === null ? {} : { transaction: parent }, run),
defaults: options.define ?? {},
inAsAnyThreshold: options.inAsAnyThreshold,
minifyAliases: options.minifyAliases,
};
}
#queryRuntime(): Pick<ModelRuntime, 'execute' | 'copyFrom' | 'copyTo' | 'serverVersion'> {
return {
// Through `sequelize.query` (like v6), so a wrapper or override of it sees the SQL of every model
// query; the routed marker makes `query` run the statement as it is and return the driver result.
execute: (query, options, kind = 'write') => {
const injected = rawQuery.inject(query, options.replacements);
return this.#owner.query(injected.text, {
...options,
bind: injected.values,
[ROUTED_QUERY]: kind,
}) as Promise<QueryResult>;
},
copyFrom: (text, lines, options) =>
this.connections.copyFrom(text, lines, this.executeOptions(options)),
copyTo: (text, options, kind) =>
this.connections.copyTo(text, this.executeOptions(options, kind)),
serverVersion: () => this.#serverVersionNumber(),
};
}
#modelRuntime(): Pick<
ModelRuntime,
'register' | 'hooks' | 'defineModel' | 'models' | 'queryInterface'
> {
return {
register: (name, model) => {
this.#owner.models[name] = model as ModelStatic<AnyModel>;
},
hooks: () => this.hooks,
defineModel: (name, attributes, options) =>
this.#owner.define(name, attributes as ModelAttributes, options),
models: () => this.#owner.models,
queryInterface: () => this.#owner.getQueryInterface(),
};
}
#serverVersionNumber(): Promise<number> {
this.#serverVersion ??= this.execute({ text: 'SHOW server_version_num', values: [] }, {}).then(
(result) => Number(result.rows[0]?.['server_version_num'] ?? 0),
);
return this.#serverVersion;
}
}
|