@vibeorm/adapter-mysql 2.0.0-alpha.6 → 2.0.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acquire.d.ts +73 -0
- package/dist/acquire.d.ts.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +93 -16
- package/dist/index.js.map +5 -4
- package/package.json +2 -2
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded pool acquisition — the adapter's own acquire timeout.
|
|
3
|
+
*
|
|
4
|
+
* mysql2 has NO acquire timeout of its own (verified against mysql2 3.23.3:
|
|
5
|
+
* neither `acquireTimeout` nor `acquire_timeout` exists anywhere in its
|
|
6
|
+
* sources). Its pool backpressure knobs are `waitForConnections`
|
|
7
|
+
* (`node_modules/mysql2/lib/pool_config.js:11-14`, default `true`) and
|
|
8
|
+
* `queueLimit` (`:24-26`, default `0` = unlimited), which bounds queue DEPTH,
|
|
9
|
+
* not TIME; `connectTimeout` is the TCP deadline for establishing a NEW
|
|
10
|
+
* connection, not for waiting on a busy pool. So an exhausted pool queues the
|
|
11
|
+
* caller forever unless something above the driver bounds the wait — which is
|
|
12
|
+
* what this module does.
|
|
13
|
+
*
|
|
14
|
+
* The trap this module exists to get right: when the deadline wins the race,
|
|
15
|
+
* the driver's `getConnection()` promise is STILL PENDING and will later hand
|
|
16
|
+
* back a real connection nobody holds. Dropping it would turn "waits too long"
|
|
17
|
+
* into "the pool is dead forever", so the losing promise is always released.
|
|
18
|
+
*/
|
|
19
|
+
import { VibeError } from "@vibeorm/schema";
|
|
20
|
+
/** Timer handle, as the ambient `setTimeout` returns it. */
|
|
21
|
+
export type TimerHandle = ReturnType<typeof setTimeout>;
|
|
22
|
+
/**
|
|
23
|
+
* Timer seam — a test injects a counting pair to prove the deadline timer is
|
|
24
|
+
* cleared exactly once, rather than asserting on wall-clock luck.
|
|
25
|
+
*/
|
|
26
|
+
export type AcquireTimers = {
|
|
27
|
+
readonly set: (fn: () => void, ms: number) => TimerHandle;
|
|
28
|
+
readonly clear: (handle: TimerHandle) => void;
|
|
29
|
+
};
|
|
30
|
+
/** The ambient timers, used whenever no seam is injected. */
|
|
31
|
+
export declare const DEFAULT_ACQUIRE_TIMERS: AcquireTimers;
|
|
32
|
+
/** The one connection capability the late-release path needs. */
|
|
33
|
+
export type ReleasableConnection = {
|
|
34
|
+
release(): void;
|
|
35
|
+
};
|
|
36
|
+
/** The one pool capability bounded acquisition needs. */
|
|
37
|
+
export type AcquireSource<TConnection extends ReleasableConnection> = {
|
|
38
|
+
getConnection(): Promise<TConnection>;
|
|
39
|
+
};
|
|
40
|
+
/** mysql2's own pool default when `connectionLimit` is unset (`lib/pool_config.js:15-17`). */
|
|
41
|
+
export declare const MYSQL_DEFAULT_CONNECTION_LIMIT: number;
|
|
42
|
+
/**
|
|
43
|
+
* The refusal a bounded acquisition raises. `VIBE_ADAPTER` for parity with
|
|
44
|
+
* `@vibeorm/adapter-pg`, whose `connectionTimeout` surfaces the same way, and
|
|
45
|
+
* `meta.reason: "acquire-timeout"` so a caller can tell an exhausted pool from
|
|
46
|
+
* any other adapter failure without reading message text.
|
|
47
|
+
*/
|
|
48
|
+
export declare function acquireTimeoutError(params: {
|
|
49
|
+
timeoutMs: number;
|
|
50
|
+
poolSize?: number;
|
|
51
|
+
}): VibeError;
|
|
52
|
+
/**
|
|
53
|
+
* Check a connection out of `pool`, refusing with {@link acquireTimeoutError}
|
|
54
|
+
* when it takes longer than `timeoutMs`.
|
|
55
|
+
*
|
|
56
|
+
* Two invariants make this safe:
|
|
57
|
+
*
|
|
58
|
+
* 1. **The lost acquire is released.** When the deadline wins, the pending
|
|
59
|
+
* `getConnection()` is not abandoned: a handler released it as soon as it
|
|
60
|
+
* lands, so a `connectionLimit: 1` pool keeps working after a timeout
|
|
61
|
+
* instead of being permanently starved of its only connection.
|
|
62
|
+
* 2. **The deadline timer never outlives the call.** It is cleared in a
|
|
63
|
+
* `finally`, so a successful acquire leaves nothing pending that could keep
|
|
64
|
+
* the event loop (or a test runner) alive.
|
|
65
|
+
*/
|
|
66
|
+
export declare function acquireWithTimeout<TConnection extends ReleasableConnection>(params: {
|
|
67
|
+
pool: AcquireSource<TConnection>;
|
|
68
|
+
timeoutMs: number;
|
|
69
|
+
/** Effective pool size, named in the refusal; omit when the pool is the caller's. */
|
|
70
|
+
poolSize?: number;
|
|
71
|
+
timers?: AcquireTimers;
|
|
72
|
+
}): Promise<TConnection>;
|
|
73
|
+
//# sourceMappingURL=acquire.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"acquire.d.ts","sourceRoot":"","sources":["../src/acquire.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,4DAA4D;AAC5D,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,EAAE,EAAE,EAAE,MAAM,KAAK,WAAW,CAAC;IAC1D,QAAQ,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,CAAC;CAC/C,CAAC;AAEF,6DAA6D;AAC7D,eAAO,MAAM,sBAAsB,EAAE,aAGnC,CAAC;AAEH,iEAAiE;AACjE,MAAM,MAAM,oBAAoB,GAAG;IACjC,OAAO,IAAI,IAAI,CAAC;CACjB,CAAC;AAEF,yDAAyD;AACzD,MAAM,MAAM,aAAa,CAAC,WAAW,SAAS,oBAAoB,IAAI;IACpE,aAAa,IAAI,OAAO,CAAC,WAAW,CAAC,CAAC;CACvC,CAAC;AAIF,8FAA8F;AAC9F,eAAO,MAAM,8BAA8B,EAAE,MAAW,CAAC;AAEzD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAkB/F;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAsB,kBAAkB,CAAC,WAAW,SAAS,oBAAoB,EAAE,MAAM,EAAE;IACzF,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,CAAC;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,qFAAqF;IACrF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,aAAa,CAAC;CACxB,GAAG,OAAO,CAAC,WAAW,CAAC,CAiCvB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -110,6 +110,26 @@ export type MysqlAdapterOptions = {
|
|
|
110
110
|
readonly timezone?: string;
|
|
111
111
|
/** Connection charset/collation (mysql2 default `utf8mb4_general_ci`). */
|
|
112
112
|
readonly charset?: string;
|
|
113
|
+
/**
|
|
114
|
+
* Milliseconds to wait for a pool connection before refusing with a
|
|
115
|
+
* `VibeError` (`VIBE_ADAPTER`, `meta.reason: "acquire-timeout"`).
|
|
116
|
+
*
|
|
117
|
+
* **Unset (the default) keeps mysql2's own behaviour**: the pool is created
|
|
118
|
+
* with `waitForConnections: true` and no time bound, so a caller whose
|
|
119
|
+
* connections are all busy QUEUES until one frees. Setting this bounds EVERY
|
|
120
|
+
* pool checkout the adapter makes — the caller gets a coded refusal instead
|
|
121
|
+
* of an unbounded wait.
|
|
122
|
+
*
|
|
123
|
+
* Adapter-owned: mysql2 has no acquire timeout at all (its pool knobs are
|
|
124
|
+
* `waitForConnections` and `queueLimit`, which bounds queue DEPTH, not time),
|
|
125
|
+
* so this value is never passed to `mysql2.createPool`.
|
|
126
|
+
*
|
|
127
|
+
* **Not mysql2's `connectTimeout`**, which is the deadline for establishing a
|
|
128
|
+
* NEW connection rather than for waiting on a busy pool. The equivalent
|
|
129
|
+
* option on `@vibeorm/adapter-pg` is `connectionTimeout`; the name differs
|
|
130
|
+
* here precisely because mysql2 already uses that word for something else.
|
|
131
|
+
*/
|
|
132
|
+
readonly acquireTimeout?: number;
|
|
113
133
|
/**
|
|
114
134
|
* Allow multiple statements per `executeUnsafe` call (default false). Leave
|
|
115
135
|
* it off: the ORM never batches, @vibeorm/migrate applies DDL per statement,
|
|
@@ -150,6 +170,8 @@ export type MysqlAdapterOptions = {
|
|
|
150
170
|
* is a string. The adapter forwards values verbatim — no second conversion.
|
|
151
171
|
*/
|
|
152
172
|
export declare function mysqlAdapter(options?: MysqlAdapterOptions): DatabaseAdapter;
|
|
173
|
+
export { DEFAULT_ACQUIRE_TIMERS, MYSQL_DEFAULT_CONNECTION_LIMIT, acquireTimeoutError, acquireWithTimeout, } from "./acquire.ts";
|
|
174
|
+
export type { AcquireSource, AcquireTimers, ReleasableConnection, TimerHandle } from "./acquire.ts";
|
|
153
175
|
export { MYSQL_ERRNO_ERROR_CODES, MYSQL_ERRNO_REASONS, mapMysqlDriverError, mysqlErrorErrno, runMapped, } from "./errors.ts";
|
|
154
176
|
export { isResultSetHeader, normalizeDriverResult } from "./results.ts";
|
|
155
177
|
export { createSavepointCounter, nextSavepointName } from "./savepoints.ts";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAiD,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAiD,MAAM,kBAAkB,CAAC;AAkBvG,gEAAgE;AAChE,MAAM,MAAM,mBAAmB,GAAG;IAChC,8EAA8E;IAC9E,OAAO,CAAC,IA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,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IACtC;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,aAAa,CAAC;CAClE,CAAC;AA8BF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,eAAe,CA+S3E;AAID,OAAO,EACL,sBAAsB,EACtB,8BAA8B,EAC9B,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACpG,OAAO,EACL,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,EACf,SAAS,GACV,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC5E,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,6BAA6B,EAC7B,yBAAyB,EACzB,8BAA8B,EAC9B,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -3,8 +3,56 @@
|
|
|
3
3
|
import { internalError } from "@vibeorm/schema";
|
|
4
4
|
import { createPool as mysql2CreatePool } from "mysql2/promise";
|
|
5
5
|
|
|
6
|
-
// packages/adapter-mysql/src/
|
|
6
|
+
// packages/adapter-mysql/src/acquire.ts
|
|
7
7
|
import { VibeError } from "@vibeorm/schema";
|
|
8
|
+
var DEFAULT_ACQUIRE_TIMERS = Object.freeze({
|
|
9
|
+
set: (fn, ms) => setTimeout(fn, ms),
|
|
10
|
+
clear: (handle) => clearTimeout(handle)
|
|
11
|
+
});
|
|
12
|
+
var MYSQL_DEFAULT_CONNECTION_LIMIT = 10;
|
|
13
|
+
function acquireTimeoutError(params) {
|
|
14
|
+
const { timeoutMs, poolSize } = params;
|
|
15
|
+
const size = poolSize === undefined ? "pool size unknown \u2014 the pool was supplied by the caller" : `connectionLimit ${poolSize}`;
|
|
16
|
+
return new VibeError({
|
|
17
|
+
code: "VIBE_ADAPTER",
|
|
18
|
+
message: `timed out after ${timeoutMs} ms waiting for a mysql pool connection \u2014 every pooled connection ` + `is busy (${size}). Raise \`connectionLimit\`, shorten the work holding a connection, or raise ` + "the adapter's `acquireTimeout` option.",
|
|
19
|
+
meta: {
|
|
20
|
+
reason: "acquire-timeout",
|
|
21
|
+
timeoutMs,
|
|
22
|
+
...poolSize === undefined ? {} : { connectionLimit: poolSize }
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
async function acquireWithTimeout(params) {
|
|
27
|
+
const { pool, timeoutMs, poolSize } = params;
|
|
28
|
+
const timers = params.timers ?? DEFAULT_ACQUIRE_TIMERS;
|
|
29
|
+
const pending = pool.getConnection();
|
|
30
|
+
let timedOut = false;
|
|
31
|
+
let handle;
|
|
32
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
33
|
+
handle = timers.set(() => {
|
|
34
|
+
timedOut = true;
|
|
35
|
+
reject(acquireTimeoutError({ timeoutMs, poolSize }));
|
|
36
|
+
}, timeoutMs);
|
|
37
|
+
});
|
|
38
|
+
pending.then((connection) => {
|
|
39
|
+
if (timedOut)
|
|
40
|
+
connection.release();
|
|
41
|
+
}, () => {
|
|
42
|
+
return;
|
|
43
|
+
}).catch(() => {
|
|
44
|
+
return;
|
|
45
|
+
});
|
|
46
|
+
try {
|
|
47
|
+
return await Promise.race([pending, deadline]);
|
|
48
|
+
} finally {
|
|
49
|
+
if (handle !== undefined)
|
|
50
|
+
timers.clear(handle);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// packages/adapter-mysql/src/errors.ts
|
|
55
|
+
import { VibeError as VibeError2 } from "@vibeorm/schema";
|
|
8
56
|
var MYSQL_ERRNO_ERROR_CODES = Object.freeze({
|
|
9
57
|
1062: "VIBE_UNIQUE_VIOLATION",
|
|
10
58
|
1586: "VIBE_UNIQUE_VIOLATION",
|
|
@@ -44,7 +92,7 @@ function mysqlErrorErrno(params) {
|
|
|
44
92
|
}
|
|
45
93
|
function mapMysqlDriverError(params) {
|
|
46
94
|
const { error } = params;
|
|
47
|
-
if (error instanceof
|
|
95
|
+
if (error instanceof VibeError2)
|
|
48
96
|
return error;
|
|
49
97
|
const source = error !== null && typeof error === "object" ? error : {};
|
|
50
98
|
const errno = mysqlErrorErrno({ error });
|
|
@@ -65,7 +113,7 @@ function mapMysqlDriverError(params) {
|
|
|
65
113
|
if (reason !== undefined)
|
|
66
114
|
meta.reason = reason;
|
|
67
115
|
const message = readStringField({ source, key: "message" }) ?? (sqlMessage !== undefined ? sqlMessage.trim() : undefined) ?? (typeof error === "string" ? error : "unknown mysql driver error");
|
|
68
|
-
return new
|
|
116
|
+
return new VibeError2({ code, message, meta, cause: error });
|
|
69
117
|
}
|
|
70
118
|
async function runMapped(fn) {
|
|
71
119
|
try {
|
|
@@ -113,7 +161,7 @@ function nextSavepointName(params) {
|
|
|
113
161
|
}
|
|
114
162
|
|
|
115
163
|
// packages/adapter-mysql/src/transaction-sql.ts
|
|
116
|
-
import { VibeError as
|
|
164
|
+
import { VibeError as VibeError3 } from "@vibeorm/schema";
|
|
117
165
|
var ISOLATION_LEVEL_SQL = Object.freeze({
|
|
118
166
|
ReadCommitted: "READ COMMITTED",
|
|
119
167
|
RepeatableRead: "REPEATABLE READ",
|
|
@@ -125,7 +173,7 @@ function setIsolationLevelStatement(params) {
|
|
|
125
173
|
function maxExecutionTimeStatement(params) {
|
|
126
174
|
const { timeout } = params;
|
|
127
175
|
if (!Number.isInteger(timeout) || timeout < 0) {
|
|
128
|
-
throw new
|
|
176
|
+
throw new VibeError3({
|
|
129
177
|
code: "VIBE_VALIDATION",
|
|
130
178
|
message: `transaction timeout must be a non-negative integer of milliseconds, received ${String(timeout)}`,
|
|
131
179
|
meta: { timeout }
|
|
@@ -159,7 +207,7 @@ function refuseNestedTransactionOptions(params) {
|
|
|
159
207
|
meta.isolationLevel = options.isolationLevel;
|
|
160
208
|
if (options.timeout !== undefined)
|
|
161
209
|
meta.timeout = options.timeout;
|
|
162
|
-
throw new
|
|
210
|
+
throw new VibeError3({
|
|
163
211
|
code: "VIBE_VALIDATION",
|
|
164
212
|
message: `nested transactions run as savepoints and cannot honor ${passed.join(" or ")} \u2014 a savepoint cannot change the isolation level of the transaction it joins, and a nested timeout is not enforceable; pass options on the top-level $transaction`,
|
|
165
213
|
meta
|
|
@@ -183,6 +231,8 @@ function mysqlAdapter(options) {
|
|
|
183
231
|
let pool = null;
|
|
184
232
|
let ownsPool = false;
|
|
185
233
|
let rawSession = null;
|
|
234
|
+
const acquireTimeoutMs = options?.acquireTimeout;
|
|
235
|
+
const poolSize = options?.pool === undefined ? options?.connectionLimit ?? MYSQL_DEFAULT_CONNECTION_LIMIT : undefined;
|
|
186
236
|
function getPool() {
|
|
187
237
|
if (pool !== null)
|
|
188
238
|
return pool;
|
|
@@ -213,6 +263,13 @@ function mysqlAdapter(options) {
|
|
|
213
263
|
ownsPool = true;
|
|
214
264
|
return pool;
|
|
215
265
|
}
|
|
266
|
+
async function acquireConnection() {
|
|
267
|
+
const active = getPool();
|
|
268
|
+
if (acquireTimeoutMs === undefined) {
|
|
269
|
+
return runMapped(() => active.getConnection());
|
|
270
|
+
}
|
|
271
|
+
return runMapped(() => acquireWithTimeout({ pool: active, timeoutMs: acquireTimeoutMs, poolSize }));
|
|
272
|
+
}
|
|
216
273
|
async function runExecute(params) {
|
|
217
274
|
const [result] = await runMapped(() => params.queryable.execute(params.text, params.values));
|
|
218
275
|
return normalizeDriverResult({ result }).rows;
|
|
@@ -260,7 +317,15 @@ function mysqlAdapter(options) {
|
|
|
260
317
|
provider: PROVIDER,
|
|
261
318
|
wire: WIRE,
|
|
262
319
|
async execute(params) {
|
|
263
|
-
|
|
320
|
+
if (acquireTimeoutMs === undefined) {
|
|
321
|
+
return runExecute({ queryable: getPool(), ...params });
|
|
322
|
+
}
|
|
323
|
+
const conn = await acquireConnection();
|
|
324
|
+
try {
|
|
325
|
+
return await runExecute({ queryable: conn, ...params });
|
|
326
|
+
} finally {
|
|
327
|
+
conn.release();
|
|
328
|
+
}
|
|
264
329
|
},
|
|
265
330
|
async executeUnsafe(params) {
|
|
266
331
|
const control = classifyRawTransactionControl({ text: params.text });
|
|
@@ -277,21 +342,29 @@ function mysqlAdapter(options) {
|
|
|
277
342
|
return runExecuteUnsafe({ queryable: rawSession, ...params });
|
|
278
343
|
}
|
|
279
344
|
if (control === "open") {
|
|
280
|
-
const
|
|
345
|
+
const conn2 = await acquireConnection();
|
|
281
346
|
try {
|
|
282
|
-
const result = await runExecuteUnsafe({ queryable:
|
|
283
|
-
rawSession =
|
|
347
|
+
const result = await runExecuteUnsafe({ queryable: conn2, ...params });
|
|
348
|
+
rawSession = conn2;
|
|
284
349
|
return result;
|
|
285
350
|
} catch (error) {
|
|
286
|
-
|
|
351
|
+
conn2.release();
|
|
287
352
|
throw error;
|
|
288
353
|
}
|
|
289
354
|
}
|
|
290
|
-
|
|
355
|
+
if (acquireTimeoutMs === undefined) {
|
|
356
|
+
return runExecuteUnsafe({ queryable: getPool(), ...params });
|
|
357
|
+
}
|
|
358
|
+
const conn = await acquireConnection();
|
|
359
|
+
try {
|
|
360
|
+
return await runExecuteUnsafe({ queryable: conn, ...params });
|
|
361
|
+
} finally {
|
|
362
|
+
conn.release();
|
|
363
|
+
}
|
|
291
364
|
},
|
|
292
365
|
async transaction(fn, transactionOptions) {
|
|
293
366
|
const timeoutText = transactionOptions?.timeout === undefined ? undefined : maxExecutionTimeStatement({ timeout: transactionOptions.timeout });
|
|
294
|
-
const conn = await
|
|
367
|
+
const conn = await acquireConnection();
|
|
295
368
|
try {
|
|
296
369
|
if (timeoutText !== undefined) {
|
|
297
370
|
await runMapped(() => conn.query(timeoutText));
|
|
@@ -329,7 +402,7 @@ function mysqlAdapter(options) {
|
|
|
329
402
|
}
|
|
330
403
|
},
|
|
331
404
|
async connect() {
|
|
332
|
-
const conn = await
|
|
405
|
+
const conn = await acquireConnection();
|
|
333
406
|
try {
|
|
334
407
|
await runMapped(() => conn.ping());
|
|
335
408
|
} finally {
|
|
@@ -369,10 +442,14 @@ export {
|
|
|
369
442
|
isResultSetHeader,
|
|
370
443
|
createSavepointCounter,
|
|
371
444
|
classifyRawTransactionControl,
|
|
445
|
+
acquireWithTimeout,
|
|
446
|
+
acquireTimeoutError,
|
|
372
447
|
RESET_MAX_EXECUTION_TIME_SQL,
|
|
373
448
|
MYSQL_ERRNO_REASONS,
|
|
374
449
|
MYSQL_ERRNO_ERROR_CODES,
|
|
375
|
-
|
|
450
|
+
MYSQL_DEFAULT_CONNECTION_LIMIT,
|
|
451
|
+
ISOLATION_LEVEL_SQL,
|
|
452
|
+
DEFAULT_ACQUIRE_TIMERS
|
|
376
453
|
};
|
|
377
454
|
|
|
378
|
-
//# debugId=
|
|
455
|
+
//# debugId=CAF3242F05183E7764756E2164756E21
|
package/dist/index.js.map
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../src/errors.ts", "../src/results.ts", "../src/savepoints.ts", "../src/transaction-sql.ts"],
|
|
3
|
+
"sources": ["../src/index.ts", "../src/acquire.ts", "../src/errors.ts", "../src/results.ts", "../src/savepoints.ts", "../src/transaction-sql.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * @vibeorm/adapter-mysql — mysql2 adapter for VibeORM v2.\n *\n * Runs on Bun and Node over `mysql2/promise`. Owns pooling, transactions\n * (nested → savepoints on the same pinned connection) and driver-error\n * mapping. Only `VibeError` ever escapes.\n *\n * SAME-CONNECTION GUARANTEE (board #7): `transaction()` checks ONE connection\n * out of the pool and every operation on the callback's adapter — `execute`,\n * `executeUnsafe`, nested `transaction` — runs on that same connection until\n * commit/rollback. That pinning is what makes `LAST_INSERT_ID()` sound: the\n * runtime wraps DB-assigned-key creates in `adapter.transaction` and issues\n * `SELECT LAST_INSERT_ID() AS id` via `executeUnsafe`, and LAST_INSERT_ID() is\n * per-connection state in MySQL — on any other connection it would answer for\n * someone else's INSERT.\n *\n * Driver configuration is pinned to the runtime's MYSQL_CODECS contract\n * (packages/runtime/src/codecs.ts) — see {@link MysqlPoolConfig}.\n */\n\nimport type { DatabaseAdapter, QueryResult, TransactionOptions, WireFidelity } from \"@vibeorm/runtime\";\nimport type { Dialect, Provider } from \"@vibeorm/schema\";\nimport { internalError } from \"@vibeorm/schema\";\nimport { createPool as mysql2CreatePool } from \"mysql2/promise\";\nimport { mapMysqlDriverError, runMapped } from \"./errors.ts\";\nimport { normalizeDriverResult } from \"./results.ts\";\nimport { createSavepointCounter, nextSavepointName, type SavepointCounter } from \"./savepoints.ts\";\nimport {\n RESET_MAX_EXECUTION_TIME_SQL,\n classifyRawTransactionControl,\n maxExecutionTimeStatement,\n refuseNestedTransactionOptions,\n setIsolationLevelStatement,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal mysql2 surface ───────────────────────────────────────\n\n/** The parts of a mysql2 `PoolConnection` this adapter uses. */\nexport type MysqlConnectionLike = {\n /** Binary protocol — prepared statements, cached per connection by mysql2. */\n execute(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n /** Text protocol — raw path and transaction-control statements. */\n query(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n beginTransaction(): Promise<void>;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n ping(): Promise<void>;\n release(): void;\n destroy(): void;\n};\n\n/** The parts of a mysql2 promise `Pool` this adapter uses. */\nexport type MysqlPoolLike = {\n execute(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n query(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n getConnection(): Promise<MysqlConnectionLike>;\n end(): Promise<void>;\n};\n\n/** Anything that can run a statement: the pool itself or a pinned connection. */\ntype Queryable = Pick<MysqlConnectionLike, \"execute\" | \"query\">;\n\n// ─── Pool config ──────────────────────────────────────────────────\n\n/**\n * The exact configuration this adapter hands to `mysql2.createPool`. The\n * literal-typed fields are pinned to the runtime's MYSQL_CODECS contract and\n * are not user-overridable:\n *\n * - `decimalNumbers: false` — DECIMAL comes back as a string; the Decimal\n * codec keeps it a string (no float rounding) and trims the fixed-scale\n * padding MySQL reports (`DECIMAL(65, 30)` → `\"42.420…00\"` → `\"42.42\"`).\n * - `supportBigNumbers: true` + `bigNumberStrings: true` — BIGINT (and\n * DECIMAL) always come back as strings, never a precision-lossy JS number;\n * the BigInt codec decodes strings exactly.\n * - `dateStrings: false` — DATETIME comes back as a JS `Date`; the DateTime\n * codec passes `Date` through in both directions.\n * - `jsonStrings: false` — JSON columns come back already parsed, which is\n * what the Json codec's decode expects from mysql2.\n * - `namedPlaceholders: false` — the mysql dialect renders positional `?`.\n * - `multipleStatements` defaults to false: the ORM never batches, and\n * @vibeorm/migrate's mysql runner applies DDL per-statement anyway (DDL\n * auto-commits, so per-statement progress tracking needs it).\n */\nexport type MysqlPoolConfig = {\n readonly uri?: string;\n readonly host?: string;\n readonly port?: number;\n readonly user?: string;\n readonly password?: string;\n readonly database?: string;\n readonly connectionLimit?: number;\n readonly charset?: string;\n readonly timezone: string;\n readonly decimalNumbers: false;\n readonly supportBigNumbers: true;\n readonly bigNumberStrings: true;\n readonly dateStrings: false;\n readonly jsonStrings: false;\n readonly namedPlaceholders: false;\n readonly multipleStatements: boolean;\n};\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/**\n * Options for {@link mysqlAdapter}. Point it at a connection URL **or** at\n * discrete `host`/`port`/`user`/`password`/`database` fields (mysql2 accepts\n * both; when both are given the discrete fields win — mysql2 merges the parsed\n * URL underneath explicit config), or hand it a pool you already own.\n */\nexport type MysqlAdapterOptions = {\n /** MySQL connection URL (`mysql://user:pw@host:3306/db`). Defaults to `process.env.MYSQL_URL`. */\n readonly url?: string;\n readonly host?: string;\n readonly port?: number;\n readonly user?: string;\n readonly password?: string;\n readonly database?: string;\n /**\n * An existing mysql2 promise pool to use instead of creating one. The\n * adapter never ends a pool it did not create, so `disconnect()` is a no-op\n * in this mode. The pool MUST be configured to the codec contract\n * ({@link MysqlPoolConfig}) — the adapter cannot verify it.\n */\n readonly pool?: MysqlPoolLike;\n /** Maximum pooled connections (mysql2 default 10). Ignored when `pool` is given. */\n readonly connectionLimit?: number;\n /**\n * mysql2 `timezone`, default `\"Z\"`: the codec table stores DateTime as UTC\n * in `DATETIME(3)` columns, and DATETIME has no zone of its own — with\n * `\"Z\"` mysql2 serializes outgoing `Date`s as UTC and parses incoming\n * DATETIME text as UTC, so the instant round-trips regardless of the server\n * or process time zone. mysql2's own default (`\"local\"`) would silently\n * shift values by the process offset.\n */\n readonly timezone?: string;\n /** Connection charset/collation (mysql2 default `utf8mb4_general_ci`). */\n readonly charset?: string;\n /**\n * Allow multiple statements per `executeUnsafe` call (default false). Leave\n * it off: the ORM never batches, @vibeorm/migrate applies DDL per statement,\n * and enabling it widens the SQL-injection blast radius of raw queries.\n */\n readonly multipleStatements?: boolean;\n /**\n * Pool factory — a test seam. Defaults to `mysql2/promise`'s `createPool`;\n * tests inject a recording fake here to assert the exact config the adapter\n * builds. Ignored when `pool` is given.\n */\n readonly createPool?: (config: MysqlPoolConfig) => MysqlPoolLike;\n};\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"mysql\";\nconst PROVIDER: Provider = \"mysql\";\n\n/**\n * mysql2 wire (board #30, live-verified on both execute paths, 8.4):\n * datetime(3) → `Date` (under the adapter's pinned `timezone: \"Z\"`), JSON →\n * parsed values, int/double → numbers. (BIGINT arrives as a string and\n * TINYINT(1) as 0/1 — BigInt/Boolean decoding stays.)\n */\nconst WIRE: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\" } as const);\n\nfunction defaultCreatePool(config: MysqlPoolConfig): MysqlPoolLike {\n // Single cast seam: mysql2's Pool satisfies MysqlPoolLike structurally, but\n // its generic overloads don't reduce to our plain signatures.\n return mysql2CreatePool(config as Parameters<typeof mysql2CreatePool>[0]) as unknown as MysqlPoolLike;\n}\n\n/** Scalar-array params must never reach this adapter — the dialect expands IN. */\nfunction throwOnArrayParam(values: unknown[]): never {\n throw internalError({\n message:\n \"formatArrayParam called on the mysql adapter — the mysql dialect expands scalar-list parameters into IN (?, ?, …) placeholders, so the runtime should have expanded this array before binding\",\n meta: { length: values.length },\n });\n}\n\n/**\n * Create a VibeORM adapter backed by mysql2.\n *\n * @example\n * ```ts\n * const adapter = mysqlAdapter({ url: process.env.MYSQL_URL, connectionLimit: 20 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: \"SELECT * FROM `User` WHERE `id` = ?\", values: [1] });\n * ```\n *\n * @example Discrete fields, or reusing a pool you already own\n * ```ts\n * const adapter = mysqlAdapter({ host: \"127.0.0.1\", port: 3306, user: \"app\", password: \"pw\", database: \"app\" });\n * const shared = mysqlAdapter({ pool: existingPool });\n * ```\n *\n * ORM path (`execute`) uses mysql2's binary protocol (`pool.execute`), which\n * prepares statements and caches them per connection keyed by statement text\n * (mysql2's `maxPreparedStatements` LRU, default 16000). Raw path\n * (`executeUnsafe`) uses the text protocol (`pool.query`) — no statement\n * cache, and DDL (which the binary protocol cannot prepare) works.\n *\n * Parameters arrive PRE-ENCODED by the runtime codec table: Json is already a\n * string, DateTime is a `Date` (mysql2 serializes it per `timezone`), BigInt\n * is a string. The adapter forwards values verbatim — no second conversion.\n */\nexport function mysqlAdapter(options?: MysqlAdapterOptions): DatabaseAdapter {\n let pool: MysqlPoolLike | null = null;\n let ownsPool = false;\n\n /**\n * The pinned connection of an OPEN raw transaction — session affinity for\n * the raw path. A raw `BEGIN` … `COMMIT` sequence over `executeUnsafe` is\n * sound only when every statement in between rides the SAME pooled\n * connection, so a pure `BEGIN` checks one out, raw statements ride it, and\n * the matching `COMMIT`/`ROLLBACK` releases it (same semantics as the pg and\n * bun adapters). The ORM path (`execute`) and `transaction()` stay on the\n * pool. Concurrent raw transactions on one adapter are unsupported.\n */\n let rawSession: MysqlConnectionLike | null = null;\n\n function getPool(): MysqlPoolLike {\n if (pool !== null) return pool;\n\n if (options?.pool !== undefined) {\n pool = options.pool;\n ownsPool = false;\n return pool;\n }\n\n const config: MysqlPoolConfig = {\n uri: options?.url ?? process.env.MYSQL_URL,\n host: options?.host,\n port: options?.port,\n user: options?.user,\n password: options?.password,\n database: options?.database,\n connectionLimit: options?.connectionLimit,\n charset: options?.charset,\n timezone: options?.timezone ?? \"Z\",\n decimalNumbers: false,\n supportBigNumbers: true,\n bigNumberStrings: true,\n dateStrings: false,\n jsonStrings: false,\n namedPlaceholders: false,\n multipleStatements: options?.multipleStatements ?? false,\n };\n pool = (options?.createPool ?? defaultCreatePool)(config);\n ownsPool = true;\n return pool;\n }\n\n async function runExecute(params: {\n queryable: Queryable;\n text: string;\n values: unknown[];\n }): Promise<Record<string, unknown>[]> {\n const [result] = await runMapped(() => params.queryable.execute(params.text, params.values));\n return normalizeDriverResult({ result }).rows;\n }\n\n async function runExecuteUnsafe(params: {\n queryable: Queryable;\n text: string;\n values?: unknown[];\n }): Promise<QueryResult> {\n const [result] = await runMapped(() => params.queryable.query(params.text, params.values));\n return normalizeDriverResult({ result });\n }\n\n /**\n * Adapter bound to the ONE pinned connection of an open transaction — the\n * same-connection guarantee. Nested `transaction()` calls open savepoints on\n * that connection, naming them from the counter shared across the whole\n * top-level transaction so siblings never collide.\n */\n function createConnectionAdapter(params: {\n conn: MysqlConnectionLike;\n savepointCounter: SavepointCounter;\n }): DatabaseAdapter {\n const { conn, savepointCounter } = params;\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n\n async execute(execParams) {\n return runExecute({ queryable: conn, ...execParams });\n },\n\n async executeUnsafe(execParams) {\n return runExecuteUnsafe({ queryable: conn, ...execParams });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n const savepoint = nextSavepointName({ counter: savepointCounter });\n await runMapped(() => conn.query(`SAVEPOINT ${savepoint}`));\n try {\n const result = await fn(createConnectionAdapter({ conn, savepointCounter }));\n await runMapped(() => conn.query(`RELEASE SAVEPOINT ${savepoint}`));\n return result;\n } catch (error) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await conn.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);\n } catch {\n /* rollback is best-effort */\n }\n throw error;\n }\n },\n\n async connect(): Promise<void> {\n // Already connected — this adapter is bound to a pinned connection.\n },\n\n async disconnect(): Promise<void> {\n // The pool owns the connection lifecycle; releasing happens at the\n // top-level transaction boundary.\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return throwOnArrayParam(values);\n },\n };\n }\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n\n async execute(params) {\n return runExecute({ queryable: getPool(), ...params });\n },\n\n async executeUnsafe(params) {\n const control = classifyRawTransactionControl({ text: params.text });\n if (rawSession !== null) {\n if (control === \"close\") {\n const session = rawSession;\n rawSession = null;\n try {\n return await runExecuteUnsafe({ queryable: session, ...params });\n } finally {\n session.release();\n }\n }\n return runExecuteUnsafe({ queryable: rawSession, ...params });\n }\n if (control === \"open\") {\n const conn = await runMapped(() => getPool().getConnection());\n try {\n const result = await runExecuteUnsafe({ queryable: conn, ...params });\n rawSession = conn;\n return result;\n } catch (error) {\n conn.release();\n throw error;\n }\n }\n return runExecuteUnsafe({ queryable: getPool(), ...params });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n // Validate the timeout before taking a connection, so a bad option fails\n // fast instead of wasting a checkout.\n const timeoutText =\n transactionOptions?.timeout === undefined\n ? undefined\n : maxExecutionTimeStatement({ timeout: transactionOptions.timeout });\n\n const conn = await runMapped(() => getPool().getConnection());\n try {\n // Session-scoped SELECT bound — see transaction-sql.ts for the loud\n // \"SELECT statements only\" caveat. Reset in finally below.\n if (timeoutText !== undefined) {\n await runMapped(() => conn.query(timeoutText));\n }\n // Applies to the NEXT transaction in the session → must precede begin.\n const isolationLevel = transactionOptions?.isolationLevel;\n if (isolationLevel !== undefined) {\n const isolationText = setIsolationLevelStatement({ isolationLevel });\n await runMapped(() => conn.query(isolationText));\n }\n await runMapped(() => conn.beginTransaction());\n try {\n const result = await fn(createConnectionAdapter({ conn, savepointCounter: createSavepointCounter() }));\n await runMapped(() => conn.commit());\n return result;\n } catch (error) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await conn.rollback();\n } catch {\n /* rollback is best-effort */\n }\n throw error;\n }\n } finally {\n let poisoned = false;\n if (timeoutText !== undefined) {\n try {\n await conn.query(RESET_MAX_EXECUTION_TIME_SQL);\n } catch {\n poisoned = true;\n }\n }\n // A connection whose session default could not be restored must never\n // return to the pool with a lowered MAX_EXECUTION_TIME.\n if (poisoned) {\n conn.destroy();\n } else {\n conn.release();\n }\n }\n },\n\n async connect(): Promise<void> {\n const conn = await runMapped(() => getPool().getConnection());\n try {\n await runMapped(() => conn.ping());\n } finally {\n conn.release();\n }\n },\n\n async disconnect(): Promise<void> {\n if (rawSession !== null) {\n // An abandoned raw transaction must not leak an in-transaction\n // connection; roll it back best-effort before the pool ends.\n const session = rawSession;\n rawSession = null;\n try {\n await session.query(\"ROLLBACK\");\n } catch {\n /* the pool is closing; the session is going away regardless */\n }\n session.release();\n }\n if (pool !== null && ownsPool) {\n const closing = pool;\n pool = null;\n await runMapped(() => closing.end());\n }\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return throwOnArrayParam(values);\n },\n };\n}\n\n// ─── Re-exports (driver-error table, helpers) ─────────────────────\n\nexport {\n MYSQL_ERRNO_ERROR_CODES,\n MYSQL_ERRNO_REASONS,\n mapMysqlDriverError,\n mysqlErrorErrno,\n runMapped,\n} from \"./errors.ts\";\nexport { isResultSetHeader, normalizeDriverResult } from \"./results.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"./savepoints.ts\";\nexport type { SavepointCounter } from \"./savepoints.ts\";\nexport {\n ISOLATION_LEVEL_SQL,\n RESET_MAX_EXECUTION_TIME_SQL,\n classifyRawTransactionControl,\n maxExecutionTimeStatement,\n refuseNestedTransactionOptions,\n setIsolationLevelStatement,\n} from \"./transaction-sql.ts\";\nexport type { RawTransactionControl } from \"./transaction-sql.ts\";\n",
|
|
5
|
+
"/**\n * @vibeorm/adapter-mysql — mysql2 adapter for VibeORM v2.\n *\n * Runs on Bun and Node over `mysql2/promise`. Owns pooling, transactions\n * (nested → savepoints on the same pinned connection) and driver-error\n * mapping. Only `VibeError` ever escapes.\n *\n * SAME-CONNECTION GUARANTEE (board #7): `transaction()` checks ONE connection\n * out of the pool and every operation on the callback's adapter — `execute`,\n * `executeUnsafe`, nested `transaction` — runs on that same connection until\n * commit/rollback. That pinning is what makes `LAST_INSERT_ID()` sound: the\n * runtime wraps DB-assigned-key creates in `adapter.transaction` and issues\n * `SELECT LAST_INSERT_ID() AS id` via `executeUnsafe`, and LAST_INSERT_ID() is\n * per-connection state in MySQL — on any other connection it would answer for\n * someone else's INSERT.\n *\n * Driver configuration is pinned to the runtime's MYSQL_CODECS contract\n * (packages/runtime/src/codecs.ts) — see {@link MysqlPoolConfig}.\n */\n\nimport type { DatabaseAdapter, QueryResult, TransactionOptions, WireFidelity } from \"@vibeorm/runtime\";\nimport type { Dialect, Provider } from \"@vibeorm/schema\";\nimport { internalError } from \"@vibeorm/schema\";\nimport { createPool as mysql2CreatePool } from \"mysql2/promise\";\nimport { MYSQL_DEFAULT_CONNECTION_LIMIT, acquireWithTimeout } from \"./acquire.ts\";\nimport { mapMysqlDriverError, runMapped } from \"./errors.ts\";\nimport { normalizeDriverResult } from \"./results.ts\";\nimport { createSavepointCounter, nextSavepointName, type SavepointCounter } from \"./savepoints.ts\";\nimport {\n RESET_MAX_EXECUTION_TIME_SQL,\n classifyRawTransactionControl,\n maxExecutionTimeStatement,\n refuseNestedTransactionOptions,\n setIsolationLevelStatement,\n} from \"./transaction-sql.ts\";\n\n// ─── Minimal mysql2 surface ───────────────────────────────────────\n\n/** The parts of a mysql2 `PoolConnection` this adapter uses. */\nexport type MysqlConnectionLike = {\n /** Binary protocol — prepared statements, cached per connection by mysql2. */\n execute(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n /** Text protocol — raw path and transaction-control statements. */\n query(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n beginTransaction(): Promise<void>;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n ping(): Promise<void>;\n release(): void;\n destroy(): void;\n};\n\n/** The parts of a mysql2 promise `Pool` this adapter uses. */\nexport type MysqlPoolLike = {\n execute(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n query(text: string, values?: unknown[]): Promise<[unknown, unknown]>;\n getConnection(): Promise<MysqlConnectionLike>;\n end(): Promise<void>;\n};\n\n/** Anything that can run a statement: the pool itself or a pinned connection. */\ntype Queryable = Pick<MysqlConnectionLike, \"execute\" | \"query\">;\n\n// ─── Pool config ──────────────────────────────────────────────────\n\n/**\n * The exact configuration this adapter hands to `mysql2.createPool`. The\n * literal-typed fields are pinned to the runtime's MYSQL_CODECS contract and\n * are not user-overridable:\n *\n * - `decimalNumbers: false` — DECIMAL comes back as a string; the Decimal\n * codec keeps it a string (no float rounding) and trims the fixed-scale\n * padding MySQL reports (`DECIMAL(65, 30)` → `\"42.420…00\"` → `\"42.42\"`).\n * - `supportBigNumbers: true` + `bigNumberStrings: true` — BIGINT (and\n * DECIMAL) always come back as strings, never a precision-lossy JS number;\n * the BigInt codec decodes strings exactly.\n * - `dateStrings: false` — DATETIME comes back as a JS `Date`; the DateTime\n * codec passes `Date` through in both directions.\n * - `jsonStrings: false` — JSON columns come back already parsed, which is\n * what the Json codec's decode expects from mysql2.\n * - `namedPlaceholders: false` — the mysql dialect renders positional `?`.\n * - `multipleStatements` defaults to false: the ORM never batches, and\n * @vibeorm/migrate's mysql runner applies DDL per-statement anyway (DDL\n * auto-commits, so per-statement progress tracking needs it).\n */\nexport type MysqlPoolConfig = {\n readonly uri?: string;\n readonly host?: string;\n readonly port?: number;\n readonly user?: string;\n readonly password?: string;\n readonly database?: string;\n readonly connectionLimit?: number;\n readonly charset?: string;\n readonly timezone: string;\n readonly decimalNumbers: false;\n readonly supportBigNumbers: true;\n readonly bigNumberStrings: true;\n readonly dateStrings: false;\n readonly jsonStrings: false;\n readonly namedPlaceholders: false;\n readonly multipleStatements: boolean;\n};\n\n// ─── Options ──────────────────────────────────────────────────────\n\n/**\n * Options for {@link mysqlAdapter}. Point it at a connection URL **or** at\n * discrete `host`/`port`/`user`/`password`/`database` fields (mysql2 accepts\n * both; when both are given the discrete fields win — mysql2 merges the parsed\n * URL underneath explicit config), or hand it a pool you already own.\n */\nexport type MysqlAdapterOptions = {\n /** MySQL connection URL (`mysql://user:pw@host:3306/db`). Defaults to `process.env.MYSQL_URL`. */\n readonly url?: string;\n readonly host?: string;\n readonly port?: number;\n readonly user?: string;\n readonly password?: string;\n readonly database?: string;\n /**\n * An existing mysql2 promise pool to use instead of creating one. The\n * adapter never ends a pool it did not create, so `disconnect()` is a no-op\n * in this mode. The pool MUST be configured to the codec contract\n * ({@link MysqlPoolConfig}) — the adapter cannot verify it.\n */\n readonly pool?: MysqlPoolLike;\n /** Maximum pooled connections (mysql2 default 10). Ignored when `pool` is given. */\n readonly connectionLimit?: number;\n /**\n * mysql2 `timezone`, default `\"Z\"`: the codec table stores DateTime as UTC\n * in `DATETIME(3)` columns, and DATETIME has no zone of its own — with\n * `\"Z\"` mysql2 serializes outgoing `Date`s as UTC and parses incoming\n * DATETIME text as UTC, so the instant round-trips regardless of the server\n * or process time zone. mysql2's own default (`\"local\"`) would silently\n * shift values by the process offset.\n */\n readonly timezone?: string;\n /** Connection charset/collation (mysql2 default `utf8mb4_general_ci`). */\n readonly charset?: string;\n /**\n * Milliseconds to wait for a pool connection before refusing with a\n * `VibeError` (`VIBE_ADAPTER`, `meta.reason: \"acquire-timeout\"`).\n *\n * **Unset (the default) keeps mysql2's own behaviour**: the pool is created\n * with `waitForConnections: true` and no time bound, so a caller whose\n * connections are all busy QUEUES until one frees. Setting this bounds EVERY\n * pool checkout the adapter makes — the caller gets a coded refusal instead\n * of an unbounded wait.\n *\n * Adapter-owned: mysql2 has no acquire timeout at all (its pool knobs are\n * `waitForConnections` and `queueLimit`, which bounds queue DEPTH, not time),\n * so this value is never passed to `mysql2.createPool`.\n *\n * **Not mysql2's `connectTimeout`**, which is the deadline for establishing a\n * NEW connection rather than for waiting on a busy pool. The equivalent\n * option on `@vibeorm/adapter-pg` is `connectionTimeout`; the name differs\n * here precisely because mysql2 already uses that word for something else.\n */\n readonly acquireTimeout?: number;\n /**\n * Allow multiple statements per `executeUnsafe` call (default false). Leave\n * it off: the ORM never batches, @vibeorm/migrate applies DDL per statement,\n * and enabling it widens the SQL-injection blast radius of raw queries.\n */\n readonly multipleStatements?: boolean;\n /**\n * Pool factory — a test seam. Defaults to `mysql2/promise`'s `createPool`;\n * tests inject a recording fake here to assert the exact config the adapter\n * builds. Ignored when `pool` is given.\n */\n readonly createPool?: (config: MysqlPoolConfig) => MysqlPoolLike;\n};\n\n// ─── Adapter ──────────────────────────────────────────────────────\n\nconst DIALECT: Dialect = \"mysql\";\nconst PROVIDER: Provider = \"mysql\";\n\n/**\n * mysql2 wire (board #30, live-verified on both execute paths, 8.4):\n * datetime(3) → `Date` (under the adapter's pinned `timezone: \"Z\"`), JSON →\n * parsed values, int/double → numbers. (BIGINT arrives as a string and\n * TINYINT(1) as 0/1 — BigInt/Boolean decoding stays.)\n */\nconst WIRE: WireFidelity = Object.freeze({ dateTime: \"native\", json: \"parsed\", numbers: \"native\" } as const);\n\nfunction defaultCreatePool(config: MysqlPoolConfig): MysqlPoolLike {\n // Single cast seam: mysql2's Pool satisfies MysqlPoolLike structurally, but\n // its generic overloads don't reduce to our plain signatures.\n return mysql2CreatePool(config as Parameters<typeof mysql2CreatePool>[0]) as unknown as MysqlPoolLike;\n}\n\n/** Scalar-array params must never reach this adapter — the dialect expands IN. */\nfunction throwOnArrayParam(values: unknown[]): never {\n throw internalError({\n message:\n \"formatArrayParam called on the mysql adapter — the mysql dialect expands scalar-list parameters into IN (?, ?, …) placeholders, so the runtime should have expanded this array before binding\",\n meta: { length: values.length },\n });\n}\n\n/**\n * Create a VibeORM adapter backed by mysql2.\n *\n * @example\n * ```ts\n * const adapter = mysqlAdapter({ url: process.env.MYSQL_URL, connectionLimit: 20 });\n * await adapter.connect();\n * const rows = await adapter.execute({ text: \"SELECT * FROM `User` WHERE `id` = ?\", values: [1] });\n * ```\n *\n * @example Discrete fields, or reusing a pool you already own\n * ```ts\n * const adapter = mysqlAdapter({ host: \"127.0.0.1\", port: 3306, user: \"app\", password: \"pw\", database: \"app\" });\n * const shared = mysqlAdapter({ pool: existingPool });\n * ```\n *\n * ORM path (`execute`) uses mysql2's binary protocol (`pool.execute`), which\n * prepares statements and caches them per connection keyed by statement text\n * (mysql2's `maxPreparedStatements` LRU, default 16000). Raw path\n * (`executeUnsafe`) uses the text protocol (`pool.query`) — no statement\n * cache, and DDL (which the binary protocol cannot prepare) works.\n *\n * Parameters arrive PRE-ENCODED by the runtime codec table: Json is already a\n * string, DateTime is a `Date` (mysql2 serializes it per `timezone`), BigInt\n * is a string. The adapter forwards values verbatim — no second conversion.\n */\nexport function mysqlAdapter(options?: MysqlAdapterOptions): DatabaseAdapter {\n let pool: MysqlPoolLike | null = null;\n let ownsPool = false;\n\n /**\n * The pinned connection of an OPEN raw transaction — session affinity for\n * the raw path. A raw `BEGIN` … `COMMIT` sequence over `executeUnsafe` is\n * sound only when every statement in between rides the SAME pooled\n * connection, so a pure `BEGIN` checks one out, raw statements ride it, and\n * the matching `COMMIT`/`ROLLBACK` releases it (same semantics as the pg and\n * bun adapters). The ORM path (`execute`) and `transaction()` stay on the\n * pool. Concurrent raw transactions on one adapter are unsupported.\n */\n let rawSession: MysqlConnectionLike | null = null;\n\n const acquireTimeoutMs = options?.acquireTimeout;\n\n /**\n * Effective pool size for the refusal message. Unknown — and reported as\n * such — when the caller supplied the pool, since `connectionLimit` is\n * ignored in that mode.\n */\n const poolSize: number | undefined =\n options?.pool === undefined ? (options?.connectionLimit ?? MYSQL_DEFAULT_CONNECTION_LIMIT) : undefined;\n\n function getPool(): MysqlPoolLike {\n if (pool !== null) return pool;\n\n if (options?.pool !== undefined) {\n pool = options.pool;\n ownsPool = false;\n return pool;\n }\n\n const config: MysqlPoolConfig = {\n uri: options?.url ?? process.env.MYSQL_URL,\n host: options?.host,\n port: options?.port,\n user: options?.user,\n password: options?.password,\n database: options?.database,\n connectionLimit: options?.connectionLimit,\n charset: options?.charset,\n timezone: options?.timezone ?? \"Z\",\n decimalNumbers: false,\n supportBigNumbers: true,\n bigNumberStrings: true,\n dateStrings: false,\n jsonStrings: false,\n namedPlaceholders: false,\n multipleStatements: options?.multipleStatements ?? false,\n };\n pool = (options?.createPool ?? defaultCreatePool)(config);\n ownsPool = true;\n return pool;\n }\n\n /**\n * The ONE place a connection is checked out. Without `acquireTimeout` this is\n * mysql2's own unbounded checkout, byte for byte; with it, the wait is\n * bounded and a caller that cannot be served refuses instead of queueing.\n * `runMapped` maps driver failures — the timeout error is already a\n * `VibeError` and passes through untouched (errors.ts:121).\n */\n async function acquireConnection(): Promise<MysqlConnectionLike> {\n const active = getPool();\n if (acquireTimeoutMs === undefined) {\n return runMapped(() => active.getConnection());\n }\n return runMapped(() => acquireWithTimeout({ pool: active, timeoutMs: acquireTimeoutMs, poolSize }));\n }\n\n async function runExecute(params: {\n queryable: Queryable;\n text: string;\n values: unknown[];\n }): Promise<Record<string, unknown>[]> {\n const [result] = await runMapped(() => params.queryable.execute(params.text, params.values));\n return normalizeDriverResult({ result }).rows;\n }\n\n async function runExecuteUnsafe(params: {\n queryable: Queryable;\n text: string;\n values?: unknown[];\n }): Promise<QueryResult> {\n const [result] = await runMapped(() => params.queryable.query(params.text, params.values));\n return normalizeDriverResult({ result });\n }\n\n /**\n * Adapter bound to the ONE pinned connection of an open transaction — the\n * same-connection guarantee. Nested `transaction()` calls open savepoints on\n * that connection, naming them from the counter shared across the whole\n * top-level transaction so siblings never collide.\n */\n function createConnectionAdapter(params: {\n conn: MysqlConnectionLike;\n savepointCounter: SavepointCounter;\n }): DatabaseAdapter {\n const { conn, savepointCounter } = params;\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n\n async execute(execParams) {\n return runExecute({ queryable: conn, ...execParams });\n },\n\n async executeUnsafe(execParams) {\n return runExecuteUnsafe({ queryable: conn, ...execParams });\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n nestedOptions?: TransactionOptions,\n ): Promise<T> {\n refuseNestedTransactionOptions({ options: nestedOptions, provider: PROVIDER });\n const savepoint = nextSavepointName({ counter: savepointCounter });\n await runMapped(() => conn.query(`SAVEPOINT ${savepoint}`));\n try {\n const result = await fn(createConnectionAdapter({ conn, savepointCounter }));\n await runMapped(() => conn.query(`RELEASE SAVEPOINT ${savepoint}`));\n return result;\n } catch (error) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await conn.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);\n } catch {\n /* rollback is best-effort */\n }\n throw error;\n }\n },\n\n async connect(): Promise<void> {\n // Already connected — this adapter is bound to a pinned connection.\n },\n\n async disconnect(): Promise<void> {\n // The pool owns the connection lifecycle; releasing happens at the\n // top-level transaction boundary.\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return throwOnArrayParam(values);\n },\n };\n }\n\n return {\n dialect: DIALECT,\n provider: PROVIDER,\n wire: WIRE,\n\n async execute(params) {\n // Default path: mysql2's `pool.execute` does its own implicit checkout.\n // With `acquireTimeout` set that checkout has to be visible to be\n // bounded, so the statement is routed over an explicit connection\n // instead (mysql2 caches prepared statements per connection either way).\n if (acquireTimeoutMs === undefined) {\n return runExecute({ queryable: getPool(), ...params });\n }\n const conn = await acquireConnection();\n try {\n return await runExecute({ queryable: conn, ...params });\n } finally {\n conn.release();\n }\n },\n\n async executeUnsafe(params) {\n const control = classifyRawTransactionControl({ text: params.text });\n if (rawSession !== null) {\n if (control === \"close\") {\n const session = rawSession;\n rawSession = null;\n try {\n return await runExecuteUnsafe({ queryable: session, ...params });\n } finally {\n session.release();\n }\n }\n return runExecuteUnsafe({ queryable: rawSession, ...params });\n }\n if (control === \"open\") {\n const conn = await acquireConnection();\n try {\n const result = await runExecuteUnsafe({ queryable: conn, ...params });\n rawSession = conn;\n return result;\n } catch (error) {\n conn.release();\n throw error;\n }\n }\n // Default path: mysql2's `pool.query` checks a connection out\n // implicitly. Same reroute as `execute()` above, for the same reason —\n // a checkout has to be visible to be bounded, so with `acquireTimeout`\n // set the raw statement runs on an explicit connection too.\n if (acquireTimeoutMs === undefined) {\n return runExecuteUnsafe({ queryable: getPool(), ...params });\n }\n const conn = await acquireConnection();\n try {\n return await runExecuteUnsafe({ queryable: conn, ...params });\n } finally {\n conn.release();\n }\n },\n\n async transaction<T>(\n fn: (txAdapter: DatabaseAdapter) => Promise<T>,\n transactionOptions?: TransactionOptions,\n ): Promise<T> {\n // Validate the timeout before taking a connection, so a bad option fails\n // fast instead of wasting a checkout.\n const timeoutText =\n transactionOptions?.timeout === undefined\n ? undefined\n : maxExecutionTimeStatement({ timeout: transactionOptions.timeout });\n\n const conn = await acquireConnection();\n try {\n // Session-scoped SELECT bound — see transaction-sql.ts for the loud\n // \"SELECT statements only\" caveat. Reset in finally below.\n if (timeoutText !== undefined) {\n await runMapped(() => conn.query(timeoutText));\n }\n // Applies to the NEXT transaction in the session → must precede begin.\n const isolationLevel = transactionOptions?.isolationLevel;\n if (isolationLevel !== undefined) {\n const isolationText = setIsolationLevelStatement({ isolationLevel });\n await runMapped(() => conn.query(isolationText));\n }\n await runMapped(() => conn.beginTransaction());\n try {\n const result = await fn(createConnectionAdapter({ conn, savepointCounter: createSavepointCounter() }));\n await runMapped(() => conn.commit());\n return result;\n } catch (error) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await conn.rollback();\n } catch {\n /* rollback is best-effort */\n }\n throw error;\n }\n } finally {\n let poisoned = false;\n if (timeoutText !== undefined) {\n try {\n await conn.query(RESET_MAX_EXECUTION_TIME_SQL);\n } catch {\n poisoned = true;\n }\n }\n // A connection whose session default could not be restored must never\n // return to the pool with a lowered MAX_EXECUTION_TIME.\n if (poisoned) {\n conn.destroy();\n } else {\n conn.release();\n }\n }\n },\n\n async connect(): Promise<void> {\n const conn = await acquireConnection();\n try {\n await runMapped(() => conn.ping());\n } finally {\n conn.release();\n }\n },\n\n async disconnect(): Promise<void> {\n if (rawSession !== null) {\n // An abandoned raw transaction must not leak an in-transaction\n // connection; roll it back best-effort before the pool ends.\n const session = rawSession;\n rawSession = null;\n try {\n await session.query(\"ROLLBACK\");\n } catch {\n /* the pool is closing; the session is going away regardless */\n }\n session.release();\n }\n if (pool !== null && ownsPool) {\n const closing = pool;\n pool = null;\n await runMapped(() => closing.end());\n }\n },\n\n formatArrayParam(values: unknown[]): unknown {\n return throwOnArrayParam(values);\n },\n };\n}\n\n// ─── Re-exports (driver-error table, helpers) ─────────────────────\n\nexport {\n DEFAULT_ACQUIRE_TIMERS,\n MYSQL_DEFAULT_CONNECTION_LIMIT,\n acquireTimeoutError,\n acquireWithTimeout,\n} from \"./acquire.ts\";\nexport type { AcquireSource, AcquireTimers, ReleasableConnection, TimerHandle } from \"./acquire.ts\";\nexport {\n MYSQL_ERRNO_ERROR_CODES,\n MYSQL_ERRNO_REASONS,\n mapMysqlDriverError,\n mysqlErrorErrno,\n runMapped,\n} from \"./errors.ts\";\nexport { isResultSetHeader, normalizeDriverResult } from \"./results.ts\";\nexport { createSavepointCounter, nextSavepointName } from \"./savepoints.ts\";\nexport type { SavepointCounter } from \"./savepoints.ts\";\nexport {\n ISOLATION_LEVEL_SQL,\n RESET_MAX_EXECUTION_TIME_SQL,\n classifyRawTransactionControl,\n maxExecutionTimeStatement,\n refuseNestedTransactionOptions,\n setIsolationLevelStatement,\n} from \"./transaction-sql.ts\";\nexport type { RawTransactionControl } from \"./transaction-sql.ts\";\n",
|
|
6
|
+
"/**\n * Bounded pool acquisition — the adapter's own acquire timeout.\n *\n * mysql2 has NO acquire timeout of its own (verified against mysql2 3.23.3:\n * neither `acquireTimeout` nor `acquire_timeout` exists anywhere in its\n * sources). Its pool backpressure knobs are `waitForConnections`\n * (`node_modules/mysql2/lib/pool_config.js:11-14`, default `true`) and\n * `queueLimit` (`:24-26`, default `0` = unlimited), which bounds queue DEPTH,\n * not TIME; `connectTimeout` is the TCP deadline for establishing a NEW\n * connection, not for waiting on a busy pool. So an exhausted pool queues the\n * caller forever unless something above the driver bounds the wait — which is\n * what this module does.\n *\n * The trap this module exists to get right: when the deadline wins the race,\n * the driver's `getConnection()` promise is STILL PENDING and will later hand\n * back a real connection nobody holds. Dropping it would turn \"waits too long\"\n * into \"the pool is dead forever\", so the losing promise is always released.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\n\n// ─── Seams ────────────────────────────────────────────────────────\n\n/** Timer handle, as the ambient `setTimeout` returns it. */\nexport type TimerHandle = ReturnType<typeof setTimeout>;\n\n/**\n * Timer seam — a test injects a counting pair to prove the deadline timer is\n * cleared exactly once, rather than asserting on wall-clock luck.\n */\nexport type AcquireTimers = {\n readonly set: (fn: () => void, ms: number) => TimerHandle;\n readonly clear: (handle: TimerHandle) => void;\n};\n\n/** The ambient timers, used whenever no seam is injected. */\nexport const DEFAULT_ACQUIRE_TIMERS: AcquireTimers = Object.freeze({\n set: (fn: () => void, ms: number): TimerHandle => setTimeout(fn, ms),\n clear: (handle: TimerHandle): void => clearTimeout(handle),\n});\n\n/** The one connection capability the late-release path needs. */\nexport type ReleasableConnection = {\n release(): void;\n};\n\n/** The one pool capability bounded acquisition needs. */\nexport type AcquireSource<TConnection extends ReleasableConnection> = {\n getConnection(): Promise<TConnection>;\n};\n\n// ─── Error ────────────────────────────────────────────────────────\n\n/** mysql2's own pool default when `connectionLimit` is unset (`lib/pool_config.js:15-17`). */\nexport const MYSQL_DEFAULT_CONNECTION_LIMIT: number = 10;\n\n/**\n * The refusal a bounded acquisition raises. `VIBE_ADAPTER` for parity with\n * `@vibeorm/adapter-pg`, whose `connectionTimeout` surfaces the same way, and\n * `meta.reason: \"acquire-timeout\"` so a caller can tell an exhausted pool from\n * any other adapter failure without reading message text.\n */\nexport function acquireTimeoutError(params: { timeoutMs: number; poolSize?: number }): VibeError {\n const { timeoutMs, poolSize } = params;\n const size =\n poolSize === undefined\n ? \"pool size unknown — the pool was supplied by the caller\"\n : `connectionLimit ${poolSize}`;\n return new VibeError({\n code: \"VIBE_ADAPTER\",\n message:\n `timed out after ${timeoutMs} ms waiting for a mysql pool connection — every pooled connection ` +\n `is busy (${size}). Raise \\`connectionLimit\\`, shorten the work holding a connection, or raise ` +\n \"the adapter's `acquireTimeout` option.\",\n meta: {\n reason: \"acquire-timeout\",\n timeoutMs,\n ...(poolSize === undefined ? {} : { connectionLimit: poolSize }),\n },\n });\n}\n\n// ─── Bounded acquisition ──────────────────────────────────────────\n\n/**\n * Check a connection out of `pool`, refusing with {@link acquireTimeoutError}\n * when it takes longer than `timeoutMs`.\n *\n * Two invariants make this safe:\n *\n * 1. **The lost acquire is released.** When the deadline wins, the pending\n * `getConnection()` is not abandoned: a handler released it as soon as it\n * lands, so a `connectionLimit: 1` pool keeps working after a timeout\n * instead of being permanently starved of its only connection.\n * 2. **The deadline timer never outlives the call.** It is cleared in a\n * `finally`, so a successful acquire leaves nothing pending that could keep\n * the event loop (or a test runner) alive.\n */\nexport async function acquireWithTimeout<TConnection extends ReleasableConnection>(params: {\n pool: AcquireSource<TConnection>;\n timeoutMs: number;\n /** Effective pool size, named in the refusal; omit when the pool is the caller's. */\n poolSize?: number;\n timers?: AcquireTimers;\n}): Promise<TConnection> {\n const { pool, timeoutMs, poolSize } = params;\n const timers = params.timers ?? DEFAULT_ACQUIRE_TIMERS;\n\n const pending = pool.getConnection();\n let timedOut = false;\n let handle: TimerHandle | undefined;\n\n const deadline = new Promise<never>((_resolve, reject) => {\n handle = timers.set(() => {\n timedOut = true;\n reject(acquireTimeoutError({ timeoutMs, poolSize }));\n }, timeoutMs);\n });\n\n // Trap: the loser of the race still settles. A connection that arrives after\n // the refusal belongs to nobody, so it goes straight back to the pool; a\n // rejection is already the race's business and is swallowed here so it can\n // never surface as an unhandled rejection.\n void pending\n .then(\n (connection) => {\n if (timedOut) connection.release();\n },\n () => undefined,\n )\n .catch(() => undefined);\n\n try {\n return await Promise.race([pending, deadline]);\n } finally {\n if (handle !== undefined) timers.clear(handle);\n }\n}\n",
|
|
6
7
|
"/**\n * Driver-error mapping for mysql2.\n *\n * Constitution rule 5: a raw driver error never escapes an adapter. Every\n * failure becomes a `VibeError` with a stable code, the driver error attached\n * as `cause`, and the MySQL errno / symbolic code / SQLSTATE / server message\n * in `meta`.\n *\n * mysql2 errors carry `errno` (the numeric MySQL server error, e.g. 1062),\n * `code` (the symbolic name, `ER_DUP_ENTRY`, or a client-side string like\n * `ECONNREFUSED` / `PROTOCOL_CONNECTION_LOST`), `sqlState` and `sqlMessage`.\n * The table is keyed by `errno` because it is the stable server-side identity;\n * client-side failures have no errno and fall through to `VIBE_ADAPTER`.\n */\n\nimport { VibeError, type VibeErrorCode } from \"@vibeorm/schema\";\n\n// ─── Errno table ──────────────────────────────────────────────────\n\n/**\n * MySQL server errno → stable VibeError code. Frozen and mirrored by tests;\n * anything absent from this table maps to `VIBE_ADAPTER` — including access\n * failures (1044 `ER_DBACCESS_DENIED_ERROR`, 1045 `ER_ACCESS_DENIED_ERROR`)\n * and every client-side connection error (`ECONNREFUSED`,\n * `PROTOCOL_CONNECTION_LOST`, `ETIMEDOUT`), which carry no errno at all.\n */\nexport const MYSQL_ERRNO_ERROR_CODES: Readonly<Record<number, VibeErrorCode>> = Object.freeze({\n /** ER_DUP_ENTRY */\n 1062: \"VIBE_UNIQUE_VIOLATION\",\n /** ER_DUP_ENTRY_WITH_KEY_NAME */\n 1586: \"VIBE_UNIQUE_VIOLATION\",\n /** ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO */\n 1761: \"VIBE_UNIQUE_VIOLATION\",\n /** ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO */\n 1762: \"VIBE_UNIQUE_VIOLATION\",\n /** ER_NO_REFERENCED_ROW */\n 1216: \"VIBE_FK_VIOLATION\",\n /** ER_ROW_IS_REFERENCED */\n 1217: \"VIBE_FK_VIOLATION\",\n /** ER_ROW_IS_REFERENCED_2 */\n 1451: \"VIBE_FK_VIOLATION\",\n /** ER_NO_REFERENCED_ROW_2 */\n 1452: \"VIBE_FK_VIOLATION\",\n /** ER_BAD_NULL_ERROR — NOT NULL column set to NULL */\n 1048: \"VIBE_VALIDATION\",\n /** ER_WARN_DATA_OUT_OF_RANGE — value out of column range */\n 1264: \"VIBE_VALIDATION\",\n /** ER_NO_DEFAULT_FOR_FIELD — column without default omitted */\n 1364: \"VIBE_VALIDATION\",\n /** ER_DATA_TOO_LONG */\n 1406: \"VIBE_VALIDATION\",\n /**\n * WARN_DATA_TRUNCATED — despite the WARN_ name, strict mode raises it as a\n * hard error: an out-of-range ENUM value or a truncated numeric string\n * (live-verified on 8.4: `role = \"SUPERUSER\"` and `n = \"12abc\"` → 1265).\n * The same bad input is a CHECK violation on sqlite and SQLSTATE 22P02 on\n * postgres — all VIBE_VALIDATION (board #9).\n */\n 1265: \"VIBE_VALIDATION\",\n /**\n * ER_TRUNCATED_WRONG_VALUE_FOR_FIELD — a wrong-TYPED value for the column\n * (live-verified on 8.4: `\"abc\"` into INT, `\"12.x9\"` into DECIMAL → 1366).\n */\n 1366: \"VIBE_VALIDATION\",\n /**\n * ER_TRUNCATED_WRONG_VALUE — an unparseable literal, e.g. a bad datetime\n * (live-verified on 8.4: `\"not-a-date\"` into DATETIME(3) → 1292,\n * SQLSTATE 22007).\n */\n 1292: \"VIBE_VALIDATION\",\n /** ER_CHECK_CONSTRAINT_VIOLATED */\n 3819: \"VIBE_VALIDATION\",\n /** ER_LOCK_DEADLOCK */\n 1213: \"VIBE_TRANSACTION\",\n /** ER_LOCK_WAIT_TIMEOUT */\n 1205: \"VIBE_TRANSACTION\",\n /** ER_QUERY_TIMEOUT — max_execution_time exceeded, statement interrupted */\n 3024: \"VIBE_TRANSACTION\",\n});\n\n/** Errnos that additionally explain themselves through `meta.reason`. */\nexport const MYSQL_ERRNO_REASONS: Readonly<Record<number, string>> = Object.freeze({\n /** ER_LOCK_DEADLOCK */\n 1213: \"deadlock\",\n /** ER_LOCK_WAIT_TIMEOUT */\n 1205: \"timeout\",\n /** ER_QUERY_TIMEOUT */\n 3024: \"timeout\",\n});\n\n// ─── Reading driver errors ────────────────────────────────────────\n\nfunction readStringField(params: { source: Record<string, unknown>; key: string }): string | undefined {\n const value = params.source[params.key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Extract the numeric MySQL errno from a mysql2 error. Client-side failures\n * (`ECONNREFUSED`, `PROTOCOL_CONNECTION_LOST`, …) have no numeric errno and\n * yield `undefined`.\n */\nexport function mysqlErrorErrno(params: { error: unknown }): number | undefined {\n const { error } = params;\n if (error === null || typeof error !== \"object\") return undefined;\n const errno = (error as Record<string, unknown>).errno;\n return typeof errno === \"number\" && Number.isInteger(errno) ? errno : undefined;\n}\n\n// ─── Mapping ──────────────────────────────────────────────────────\n\n/**\n * Map any error thrown by mysql2 onto a `VibeError`.\n *\n * A `VibeError` passes through unchanged, so an error raised deeper inside the\n * ORM (or by a nested adapter call) is never re-wrapped, and a user callback's\n * error is rethrown identically.\n */\nexport function mapMysqlDriverError(params: { error: unknown }): VibeError {\n const { error } = params;\n if (error instanceof VibeError) return error;\n\n const source: Record<string, unknown> =\n error !== null && typeof error === \"object\" ? (error as Record<string, unknown>) : {};\n const errno = mysqlErrorErrno({ error });\n const code: VibeErrorCode =\n (errno === undefined ? undefined : MYSQL_ERRNO_ERROR_CODES[errno]) ?? \"VIBE_ADAPTER\";\n\n const meta: Record<string, unknown> = {};\n if (errno !== undefined) meta.errno = errno;\n const symbolicCode = readStringField({ source, key: \"code\" });\n if (symbolicCode !== undefined) meta.code = symbolicCode;\n const sqlState = readStringField({ source, key: \"sqlState\" });\n if (sqlState !== undefined) meta.sqlState = sqlState;\n const sqlMessage = readStringField({ source, key: \"sqlMessage\" });\n if (sqlMessage !== undefined) meta.sqlMessage = sqlMessage.trim();\n const reason = errno === undefined ? undefined : MYSQL_ERRNO_REASONS[errno];\n if (reason !== undefined) meta.reason = reason;\n\n const message =\n readStringField({ source, key: \"message\" }) ??\n (sqlMessage !== undefined ? sqlMessage.trim() : undefined) ??\n (typeof error === \"string\" ? error : \"unknown mysql driver error\");\n\n return new VibeError({ code, message, meta, cause: error });\n}\n\n/** Run a driver call, mapping anything it throws onto a `VibeError`. */\nexport async function runMapped<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw mapMysqlDriverError({ error });\n }\n}\n",
|
|
7
8
|
"/**\n * Result normalization for mysql2.\n *\n * mysql2 resolves `execute()` / `query()` with a `[result, fields]` tuple where\n * `result` is one of:\n * - `RowDataPacket[]` — a SELECT's rows (plain objects; `rowsAsArray` is off);\n * - `ResultSetHeader` — an INSERT / UPDATE / DELETE / DDL OK-packet carrying\n * `affectedRows` and `insertId`;\n * - an array of the above — only when `multipleStatements` is enabled, one\n * entry per statement.\n *\n * The adapter's contract: `execute` returns rows (a header normalizes to `[]`);\n * `executeUnsafe` returns `{ rows, affectedRows }` (a SELECT has\n * `affectedRows: 0`, a mutation has `rows: []`). With `multipleStatements`\n * enabled the LAST statement's result wins, mirroring adapter-pglite's `exec`.\n */\n\nimport type { QueryResult } from \"@vibeorm/runtime\";\n\n// ─── Header detection ─────────────────────────────────────────────\n\n/**\n * True when a driver result value is shaped like mysql2's `ResultSetHeader`\n * (an OK-packet). Checks `affectedRows` + `serverStatus` together so a row\n * object that merely aliases a column as `affectedRows` is not misread.\n */\nexport function isResultSetHeader(params: { value: unknown }): boolean {\n const { value } = params;\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const source = value as Record<string, unknown>;\n return typeof source.affectedRows === \"number\" && typeof source.serverStatus === \"number\";\n}\n\n// ─── Normalization ────────────────────────────────────────────────\n\n/** One result set (never a multi-statement array) → the adapter contract. */\nfunction normalizeSingle(value: unknown): QueryResult {\n if (Array.isArray(value)) {\n return { rows: value as Record<string, unknown>[], affectedRows: 0 };\n }\n if (isResultSetHeader({ value })) {\n return { rows: [], affectedRows: (value as { affectedRows: number }).affectedRows };\n }\n return { rows: [], affectedRows: 0 };\n}\n\n/**\n * Normalize the first element of mysql2's `[result, fields]` tuple. A\n * multi-statement result (array whose last entry is itself a result set or an\n * OK-packet) collapses to its LAST statement's result.\n */\nexport function normalizeDriverResult(params: { result: unknown }): QueryResult {\n const { result } = params;\n if (Array.isArray(result)) {\n const last: unknown = result.at(-1);\n if (last !== undefined && (Array.isArray(last) || isResultSetHeader({ value: last }))) {\n return normalizeSingle(last);\n }\n // A plain result set: row objects (or an empty SELECT).\n return { rows: result as Record<string, unknown>[], affectedRows: 0 };\n }\n return normalizeSingle(result);\n}\n",
|
|
8
9
|
"/**\n * Savepoint naming for nested transactions.\n *\n * v1 lesson (LEARNINGS.md): the counter is shared **by reference** across every\n * adapter created for one top-level transaction, so sibling and deeply nested\n * savepoints can never collide on a name.\n */\n\n/** Mutable counter shared by reference across one top-level transaction. */\nexport type SavepointCounter = { n: number };\n\n/** Fresh counter — one per top-level transaction. */\nexport function createSavepointCounter(): SavepointCounter {\n return { n: 0 };\n}\n\n/**\n * Allocate the next savepoint name (`vibeorm_sp_0`, `vibeorm_sp_1`, …) and\n * advance the shared counter. The name is an identifier by construction, so it\n * is safe to interpolate into `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` SQL.\n */\nexport function nextSavepointName(params: { counter: SavepointCounter }): string {\n return `vibeorm_sp_${params.counter.n++}`;\n}\n",
|
|
9
10
|
"/**\n * Transaction-control SQL text (mysql dialect).\n *\n * Kept apart from the adapter so the mapping from `TransactionOptions` to SQL\n * is unit-testable without a server, and so the timeout value is validated\n * before it is ever interpolated into a statement.\n *\n * MySQL specifics:\n * - `SET TRANSACTION ISOLATION LEVEL <level>` applies to the NEXT transaction\n * started in the session, so the adapter issues it BEFORE\n * `conn.beginTransaction()` — never inside the open transaction.\n * - MySQL has no general per-transaction statement timeout.\n * `MAX_EXECUTION_TIME` is the closest tool and it bounds **SELECT statements\n * only** — see {@link maxExecutionTimeStatement}.\n */\n\nimport type { IsolationLevel, TransactionOptions } from \"@vibeorm/runtime\";\nimport { VibeError } from \"@vibeorm/schema\";\n\n/** VibeORM isolation level → MySQL isolation level keyword. */\nexport const ISOLATION_LEVEL_SQL: Readonly<Record<IsolationLevel, string>> = Object.freeze({\n ReadCommitted: \"READ COMMITTED\",\n RepeatableRead: \"REPEATABLE READ\",\n Serializable: \"SERIALIZABLE\",\n});\n\n/**\n * `SET TRANSACTION ISOLATION LEVEL <level>` — scoped to the next transaction\n * in the session, which is why the adapter sends it before\n * `conn.beginTransaction()` on the pinned connection.\n *\n * Observability trap (verified live on MySQL 8.4): the one-shot value IS\n * applied to the next transaction — `performance_schema.\n * events_transactions_current` reports the requested level — but\n * `@@transaction_isolation` NEVER reflects it; that variable keeps answering\n * the session value both before and inside the transaction. Tests must assert\n * the level's behavior (e.g. SERIALIZABLE turning plain SELECTs into locking\n * reads), not the variable — see tests/live.test.ts.\n */\nexport function setIsolationLevelStatement(params: { isolationLevel: IsolationLevel }): string {\n return `SET TRANSACTION ISOLATION LEVEL ${ISOLATION_LEVEL_SQL[params.isolationLevel]}`;\n}\n\n/**\n * `SET SESSION MAX_EXECUTION_TIME = <ms>` — the closest MySQL gets to a\n * transaction timeout, and the semantics differ LOUDLY from postgres:\n *\n * **`MAX_EXECUTION_TIME` bounds SELECT statements only.** INSERT / UPDATE /\n * DELETE / DDL inside the transaction run unbounded; MySQL simply has no\n * per-statement timeout for mutations. An over-long SELECT is interrupted with\n * errno 3024 (`ER_QUERY_TIMEOUT`), mapped to `VIBE_TRANSACTION` with\n * `meta.reason = \"timeout\"`. The setting is session-scoped (not\n * transaction-scoped), so the adapter resets it to DEFAULT in `finally` before\n * the connection returns to the pool.\n *\n * One more caveat (verified live on MySQL 8.4): `SELECT SLEEP(n)` cannot\n * observe the bound — an interrupted `SLEEP()` swallows the kill and returns\n * `1` with NO error, so the statement comes back \"successfully\" at ~timeout.\n * Only a SELECT doing real work is cancelled with errno 3024.\n *\n * @throws VibeError `VIBE_VALIDATION` when the timeout is not a non-negative\n * integer — the value is interpolated into SQL, so it is never trusted blindly.\n */\nexport function maxExecutionTimeStatement(params: { timeout: number }): string {\n const { timeout } = params;\n if (!Number.isInteger(timeout) || timeout < 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `transaction timeout must be a non-negative integer of milliseconds, received ${String(timeout)}`,\n meta: { timeout },\n });\n }\n return `SET SESSION MAX_EXECUTION_TIME = ${timeout}`;\n}\n\n/**\n * Restores the session default after a transaction that set a timeout. Issued\n * in `finally`; if it fails the adapter destroys the connection instead of\n * releasing it, so a poisoned session never returns to the pool.\n */\nexport const RESET_MAX_EXECUTION_TIME_SQL: string = \"SET SESSION MAX_EXECUTION_TIME = DEFAULT\";\n\n// ─── Raw transaction control (session affinity) ─────────────────\n\n/** How a raw statement steers the adapter's session-affine raw transaction. */\nexport type RawTransactionControl = \"open\" | \"close\" | null;\n\nconst RAW_OPEN_PATTERN: RegExp = /^\\s*(?:begin|start\\s+transaction)\\b[^;]*;?\\s*$/i;\nconst RAW_CLOSE_PATTERN: RegExp = /^\\s*(?:commit|rollback)(?:\\s+work)?\\s*;?\\s*$/i;\n\n/**\n * Classify a raw statement as transaction control. A raw `BEGIN` … `COMMIT`\n * sequence over `executeUnsafe` is sound only when every statement in between\n * rides the SAME pooled connection, so the adapter pins one connection for\n * the whole raw transaction (\"open\" checks out, \"close\" releases). MySQL DDL\n * auto-commits, so @vibeorm/migrate never wraps here — this exists for raw\n * user sequences and keeps the three pool adapters' semantics identical.\n *\n * Deliberately strict: only PURE single-statement control text matches.\n * Compound scripts, `ROLLBACK TO SAVEPOINT` and `COMMIT AND CHAIN` (which\n * keeps a transaction open) never engage the pinning.\n */\nexport function classifyRawTransactionControl(params: { text: string }): RawTransactionControl {\n if (RAW_OPEN_PATTERN.test(params.text)) return \"open\";\n if (RAW_CLOSE_PATTERN.test(params.text)) return \"close\";\n return null;\n}\n\n// ─── Nested transaction options (the cross-adapter contract) ──────\n\n/**\n * Refuse options on a NESTED `transaction()` call — the same contract on every\n * adapter (see the `DatabaseAdapter.transaction` JSDoc in @vibeorm/runtime):\n * a nested transaction is a SAVEPOINT, and a savepoint can neither change the\n * isolation level of the transaction it joins nor enforce its own timeout.\n * Silently dropping the option (the pre-#3 behaviour) hid exactly that.\n *\n * @throws VibeError `VIBE_VALIDATION` when `isolationLevel` or `timeout` is\n * present (an `undefined` or empty options object is accepted).\n */\nexport function refuseNestedTransactionOptions(params: {\n options?: TransactionOptions;\n provider: string;\n}): void {\n const { options, provider } = params;\n if (options === undefined) return;\n\n const passed: string[] = [];\n if (options.isolationLevel !== undefined) passed.push(\"isolationLevel\");\n if (options.timeout !== undefined) passed.push(\"timeout\");\n if (passed.length === 0) return;\n\n const meta: Record<string, unknown> = { provider, nested: true };\n if (options.isolationLevel !== undefined) meta.isolationLevel = options.isolationLevel;\n if (options.timeout !== undefined) meta.timeout = options.timeout;\n\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `nested transactions run as savepoints and cannot honor ${passed.join(\" or \")} — a savepoint cannot change the isolation level of the transaction it joins, and a nested timeout is not enforceable; pass options on the top-level $transaction`,\n meta,\n });\n}\n"
|
|
10
11
|
],
|
|
11
|
-
"mappings": ";;AAsBA;AACA,uBAAS;;;
|
|
12
|
-
"debugId": "
|
|
12
|
+
"mappings": ";;AAsBA;AACA,uBAAS;;;ACJT;AAiBO,IAAM,yBAAwC,OAAO,OAAO;AAAA,EACjE,KAAK,CAAC,IAAgB,OAA4B,WAAW,IAAI,EAAE;AAAA,EACnE,OAAO,CAAC,WAA8B,aAAa,MAAM;AAC3D,CAAC;AAeM,IAAM,iCAAyC;AAQ/C,SAAS,mBAAmB,CAAC,QAA6D;AAAA,EAC/F,QAAQ,WAAW,aAAa;AAAA,EAChC,MAAM,OACJ,aAAa,YACT,iEACA,mBAAmB;AAAA,EACzB,OAAO,IAAI,UAAU;AAAA,IACnB,MAAM;AAAA,IACN,SACE,mBAAmB,qFACnB,YAAY,uFACZ;AAAA,IACF,MAAM;AAAA,MACJ,QAAQ;AAAA,MACR;AAAA,SACI,aAAa,YAAY,CAAC,IAAI,EAAE,iBAAiB,SAAS;AAAA,IAChE;AAAA,EACF,CAAC;AAAA;AAmBH,eAAsB,kBAA4D,CAAC,QAM1D;AAAA,EACvB,QAAQ,MAAM,WAAW,aAAa;AAAA,EACtC,MAAM,SAAS,OAAO,UAAU;AAAA,EAEhC,MAAM,UAAU,KAAK,cAAc;AAAA,EACnC,IAAI,WAAW;AAAA,EACf,IAAI;AAAA,EAEJ,MAAM,WAAW,IAAI,QAAe,CAAC,UAAU,WAAW;AAAA,IACxD,SAAS,OAAO,IAAI,MAAM;AAAA,MACxB,WAAW;AAAA,MACX,OAAO,oBAAoB,EAAE,WAAW,SAAS,CAAC,CAAC;AAAA,OAClD,SAAS;AAAA,GACb;AAAA,EAMI,QACF,KACC,CAAC,eAAe;AAAA,IACd,IAAI;AAAA,MAAU,WAAW,QAAQ;AAAA,KAEnC,MAAG;AAAA,IAAG;AA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YAC7C,MAAM;AAAA,YACN,WAAW;AAAA;AAAA,QAEf;AAAA,QAGA,IAAI,UAAU;AAAA,UACZ,KAAK,QAAQ;AAAA,QACf,EAAO;AAAA,UACL,KAAK,QAAQ;AAAA;AAAA;AAAA;AAAA,SAKb,QAAO,GAAkB;AAAA,MAC7B,MAAM,OAAO,MAAM,kBAAkB;AAAA,MACrC,IAAI;AAAA,QACF,MAAM,UAAU,MAAM,KAAK,KAAK,CAAC;AAAA,gBACjC;AAAA,QACA,KAAK,QAAQ;AAAA;AAAA;AAAA,SAIX,WAAU,GAAkB;AAAA,MAChC,IAAI,eAAe,MAAM;AAAA,QAGvB,MAAM,UAAU;AAAA,QAChB,aAAa;AAAA,QACb,IAAI;AAAA,UACF,MAAM,QAAQ,MAAM,UAAU;AAAA,UAC9B,MAAM;AAAA,QAGR,QAAQ,QAAQ;AAAA,MAClB;AAAA,MACA,IAAI,SAAS,QAAQ,UAAU;AAAA,QAC7B,MAAM,UAAU;AAAA,QAChB,OAAO;AAAA,QACP,MAAM,UAAU,MAAM,QAAQ,IAAI,CAAC;AAAA,MACrC;AAAA;AAAA,IAGF,gBAAgB,CAAC,QAA4B;AAAA,MAC3C,OAAO,kBAAkB,MAAM;AAAA;AAAA,EAEnC;AAAA;",
|
|
13
|
+
"debugId": "CAF3242F05183E7764756E2164756E21",
|
|
13
14
|
"names": []
|
|
14
15
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibeorm/adapter-mysql",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.7",
|
|
4
4
|
"description": "mysql2 adapter for VibeORM v2",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"orm",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"bun": ">=1.2.0"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@vibeorm/runtime": "2.0.0-alpha.
|
|
45
|
+
"@vibeorm/runtime": "2.0.0-alpha.7",
|
|
46
46
|
"@vibeorm/schema": "2.0.0-alpha.5",
|
|
47
47
|
"mysql2": "^3.15.0"
|
|
48
48
|
},
|