@culpritsql/test 0.0.0-stage → 0.5.6

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/index.js ADDED
@@ -0,0 +1,1368 @@
1
+ // src/wasm.ts
2
+ import {
3
+ diffPlans,
4
+ exportPlan,
5
+ init,
6
+ ParserError,
7
+ parseDeadlock,
8
+ parsePlan
9
+ } from "@culpritsql/plans";
10
+ var initPromise = null;
11
+ var wasmReady = false;
12
+ async function loadDefaultWasm() {
13
+ if (typeof import.meta.resolve === "function") {
14
+ const entryUrl = import.meta.resolve("@culpritsql/plans");
15
+ const wasmUrl = new URL("./native/culprit_wasm_bg.wasm", entryUrl);
16
+ if (wasmUrl.protocol === "file:") {
17
+ const { readFile } = await import("node:fs/promises");
18
+ const module_or_path = await readFile(wasmUrl);
19
+ await init({ module_or_path });
20
+ return;
21
+ }
22
+ await init({ module_or_path: wasmUrl });
23
+ return;
24
+ }
25
+ await init();
26
+ }
27
+ function ensureWasmInit(input) {
28
+ if (input !== void 0) {
29
+ const customPromise = init(input).then(() => {
30
+ wasmReady = true;
31
+ });
32
+ initPromise = customPromise.catch((err) => {
33
+ initPromise = null;
34
+ throw err;
35
+ });
36
+ return initPromise;
37
+ }
38
+ if (initPromise !== null) {
39
+ return initPromise;
40
+ }
41
+ initPromise = loadDefaultWasm().then(() => {
42
+ wasmReady = true;
43
+ }).catch((err) => {
44
+ initPromise = null;
45
+ throw err;
46
+ });
47
+ return initPromise;
48
+ }
49
+ var initWasm = ensureWasmInit;
50
+ function isWasmReady() {
51
+ return wasmReady;
52
+ }
53
+
54
+ // src/assertions.ts
55
+ var PlanAssertionError = class extends Error {
56
+ plan;
57
+ constructor(message, plan) {
58
+ super(message);
59
+ this.name = "PlanAssertionError";
60
+ this.plan = plan;
61
+ }
62
+ };
63
+ function assertIsPlan(value) {
64
+ if (value === null || typeof value !== "object" || typeof value.engine !== "string" || typeof value.total_cost !== "number" || typeof value.root !== "object" || value.root === null) {
65
+ throw new TypeError(
66
+ "Expected a parsed `@culpritsql/plans` Plan object (from `explain()` or `explainText()`)."
67
+ );
68
+ }
69
+ }
70
+ function collectPlanNodes(plan) {
71
+ const nodes = [];
72
+ const stack = [plan.root];
73
+ while (stack.length > 0) {
74
+ const current = stack.pop();
75
+ nodes.push(current);
76
+ for (let i = current.children.length - 1; i >= 0; i -= 1) {
77
+ stack.push(current.children[i]);
78
+ }
79
+ }
80
+ return nodes;
81
+ }
82
+ function stripIdentifierQuotes(raw) {
83
+ return raw.split(".").map((part) => part.trim().replace(/^\[|\]$|^"|"$|^`|`$/g, "")).filter((part) => part.length > 0).join(".");
84
+ }
85
+ function leafIdentifier(clean) {
86
+ const idx = clean.lastIndexOf(".");
87
+ return idx === -1 ? clean : clean.slice(idx + 1);
88
+ }
89
+ function matchesTarget(actual, target, alias) {
90
+ if (target === void 0) {
91
+ return Boolean(actual && actual.trim().length > 0);
92
+ }
93
+ const candidates = [];
94
+ if (actual && actual.trim().length > 0) {
95
+ const clean = stripIdentifierQuotes(actual);
96
+ candidates.push(actual, clean, leafIdentifier(clean));
97
+ }
98
+ if (alias && alias.trim().length > 0) {
99
+ const cleanAlias = stripIdentifierQuotes(alias);
100
+ candidates.push(alias, cleanAlias, leafIdentifier(cleanAlias));
101
+ }
102
+ if (candidates.length === 0) {
103
+ return false;
104
+ }
105
+ if (target instanceof RegExp) {
106
+ return candidates.some((c) => target.test(c));
107
+ }
108
+ const cleanTarget = stripIdentifierQuotes(target);
109
+ const lowerTarget = cleanTarget.toLowerCase();
110
+ if (cleanTarget.includes(".")) {
111
+ return candidates.some((c) => stripIdentifierQuotes(c).toLowerCase() === lowerTarget);
112
+ }
113
+ return candidates.some((c) => leafIdentifier(stripIdentifierQuotes(c)).toLowerCase() === lowerTarget);
114
+ }
115
+ function formatTargetLabel(target) {
116
+ if (target === void 0) return "any";
117
+ if (target instanceof RegExp) return String(target);
118
+ return `"${target}"`;
119
+ }
120
+ function formatRowsSummary(node) {
121
+ const parts = [];
122
+ if (node.act_rows !== null) {
123
+ parts.push(`act_rows=${Math.round(node.act_rows)}`);
124
+ }
125
+ parts.push(`est_rows=${Math.round(node.est_rows)}`);
126
+ if (node.rows_read !== null) {
127
+ parts.push(`rows_read=${Math.round(node.rows_read)}`);
128
+ }
129
+ return parts.join(", ");
130
+ }
131
+ function formatNodeDiagnostic(node) {
132
+ const location = node.object ? ` on ${node.object}` : "";
133
+ const indexPart = node.index ? ` [index=${node.index}]` : "";
134
+ const stats = [formatRowsSummary(node)];
135
+ if (node.subtree_cost > 0) {
136
+ stats.push(`cost=${node.subtree_cost.toFixed(2)}`);
137
+ }
138
+ if (node.act_time_ms !== null) {
139
+ stats.push(`time=${node.act_time_ms.toFixed(2)}ms`);
140
+ }
141
+ if (node.runtime?.logical_reads !== null && node.runtime?.logical_reads !== void 0) {
142
+ stats.push(`logical_reads=${node.runtime.logical_reads}`);
143
+ }
144
+ if (node.runtime?.spill_pages !== null && node.runtime?.spill_pages !== void 0) {
145
+ stats.push(`spill_pages=${node.runtime.spill_pages}`);
146
+ }
147
+ if (node.predicate) {
148
+ stats.push(`filter=${node.predicate}`);
149
+ }
150
+ return `[node #${node.id}] ${node.op}${location}${indexPart} (${stats.join(", ")})`;
151
+ }
152
+ function formatIndexHintsDiagnostic(plan, focusNodes) {
153
+ const lines = [];
154
+ for (const hint of plan.index_hints) {
155
+ const keys = [...hint.equality, ...hint.inequality];
156
+ const include = hint.include.length > 0 ? ` include=(${hint.include.join(", ")})` : "";
157
+ lines.push(
158
+ ` Index hint on ${hint.table}: key=(${keys.join(", ")})${include} (impact ${hint.impact_pct.toFixed(1)}%)`
159
+ );
160
+ }
161
+ const nodesToInspect = focusNodes ?? collectPlanNodes(plan);
162
+ for (const node of nodesToInspect) {
163
+ if (node.facts.possible_index_names.length > 0) {
164
+ lines.push(
165
+ ` Possible indexes on ${node.object ?? `node #${node.id}`}: ${node.facts.possible_index_names.join(", ")}`
166
+ );
167
+ }
168
+ if (node.facts.automatic_index) {
169
+ lines.push(
170
+ ` Automatic temp index built on ${node.facts.automatic_index.table}(${node.facts.automatic_index.columns.join(", ")})`
171
+ );
172
+ }
173
+ }
174
+ return lines.length > 0 ? `
175
+ Index diagnostics:
176
+ ${lines.join("\n")}` : "";
177
+ }
178
+ function isIndexAccessNode(node) {
179
+ const op = node.op.toLowerCase();
180
+ if (op === "clustered index scan") {
181
+ return false;
182
+ }
183
+ if (node.facts.automatic_index) {
184
+ return false;
185
+ }
186
+ if (op === "index scan" || op === "index seek" || op === "clustered index seek" || op === "index only scan" || op === "bitmap index scan") {
187
+ return true;
188
+ }
189
+ const detailUpper = node.detail?.toUpperCase() ?? "";
190
+ if (/\bUSING\s+(?:COVERING\s+)?INDEX\b/.test(detailUpper) || /\bUSING\s+(?:INTEGER\s+)?PRIMARY\s+KEY\b/.test(detailUpper)) {
191
+ return true;
192
+ }
193
+ if (node.kind === "seek" && node.index !== null && node.index.trim().length > 0) {
194
+ return true;
195
+ }
196
+ return false;
197
+ }
198
+ function isFullTableScanNode(node) {
199
+ const op = node.op.toLowerCase();
200
+ if (op === "seq scan" || op === "table scan" || op === "clustered index scan" || op === "columnstore index scan" || op === "clustered columnstore index scan") {
201
+ return true;
202
+ }
203
+ if (node.props.access_type?.toUpperCase() === "ALL") {
204
+ return true;
205
+ }
206
+ if (op === "scan" && (node.index === null || node.index.trim().length === 0)) {
207
+ return true;
208
+ }
209
+ return false;
210
+ }
211
+ function describeNodeSpill(node) {
212
+ const reasons = [];
213
+ const spillPages = node.runtime?.spill_pages ?? null;
214
+ if (spillPages !== null && spillPages > 0) {
215
+ reasons.push(`spill_pages=${spillPages}`);
216
+ }
217
+ const extraFacts = node.facts;
218
+ if (extraFacts.spilled === true) {
219
+ reasons.push("facts.spilled=true");
220
+ }
221
+ if (node.facts.sort_on_disk === true) {
222
+ reasons.push("sort_on_disk=true");
223
+ }
224
+ if (node.facts.exchange_spill === true) {
225
+ reasons.push("exchange_spill=true");
226
+ }
227
+ if ((node.facts.hash_batches ?? 0) > 1) {
228
+ reasons.push(`hash_batches=${node.facts.hash_batches}`);
229
+ }
230
+ if ((node.facts.hash_aggregate_batches ?? 0) > 1) {
231
+ reasons.push(`hash_aggregate_batches=${node.facts.hash_aggregate_batches}`);
232
+ }
233
+ if (node.props["Sort Space Type"]?.toLowerCase() === "disk" && !reasons.includes("sort_on_disk=true")) {
234
+ reasons.push('Sort Space Type="Disk"');
235
+ }
236
+ if (node.props["Sort Method"]?.toLowerCase().includes("external")) {
237
+ reasons.push(`Sort Method="${node.props["Sort Method"]}"`);
238
+ }
239
+ if (node.warnings.includes("spill")) {
240
+ reasons.push('warning="spill"');
241
+ }
242
+ return reasons;
243
+ }
244
+ function evaluateToUseIndex(plan, indexName) {
245
+ const nodes = collectPlanNodes(plan);
246
+ const indexNodes = nodes.filter((node) => {
247
+ if (!isIndexAccessNode(node)) return false;
248
+ if (indexName === void 0) return true;
249
+ return matchesTarget(node.index, indexName);
250
+ });
251
+ const pass = indexNodes.length > 0;
252
+ const label = indexName === void 0 ? "an index" : `index ${formatTargetLabel(indexName)}`;
253
+ const allFormatted = nodes.map((n) => ` ${formatNodeDiagnostic(n)}`).join("\n");
254
+ const matchedFormatted = indexNodes.map((n) => ` ${formatNodeDiagnostic(n)}`).join("\n");
255
+ const hints = formatIndexHintsDiagnostic(plan);
256
+ return {
257
+ pass,
258
+ positiveMessage: `Expected execution plan (${plan.engine}) to use ${label}, but no matching index operator was found.
259
+ Plan operators:
260
+ ${allFormatted}${hints}`,
261
+ negatedMessage: `Expected execution plan (${plan.engine}) not to use ${label}, but found ${indexNodes.length} matching operator(s):
262
+ ${matchedFormatted}`
263
+ };
264
+ }
265
+ function evaluateToScanTable(plan, tableName) {
266
+ const nodes = collectPlanNodes(plan);
267
+ const scanNodes = nodes.filter((node) => {
268
+ if (!isFullTableScanNode(node)) return false;
269
+ if (tableName === void 0) return true;
270
+ return matchesTarget(node.object, tableName, node.facts.table_alias);
271
+ });
272
+ const pass = scanNodes.length > 0;
273
+ const label = tableName === void 0 ? "any table" : `table ${formatTargetLabel(tableName)}`;
274
+ const allFormatted = nodes.map((n) => ` ${formatNodeDiagnostic(n)}`).join("\n");
275
+ const scanFormatted = scanNodes.map((n) => ` ${formatNodeDiagnostic(n)}`).join("\n");
276
+ const hints = formatIndexHintsDiagnostic(plan, scanNodes.length > 0 ? scanNodes : void 0);
277
+ return {
278
+ pass,
279
+ positiveMessage: `Expected execution plan (${plan.engine}) to scan ${label}, but no matching full scan operator was found.
280
+ Plan operators:
281
+ ${allFormatted}`,
282
+ negatedMessage: `Expected execution plan (${plan.engine}) not to scan ${label}, but found ${scanNodes.length} full scan operator(s):
283
+ ${scanFormatted}${hints}`
284
+ };
285
+ }
286
+ function evaluateToHaveZeroSpills(plan) {
287
+ const nodes = collectPlanNodes(plan);
288
+ const findings = [];
289
+ const planExtraFacts = plan.facts;
290
+ if (plan.warnings.includes("spill")) {
291
+ findings.push(' [plan] plan.warnings includes "spill"');
292
+ }
293
+ if (planExtraFacts.spilled === true) {
294
+ findings.push(" [plan] plan.facts.spilled=true");
295
+ }
296
+ for (const node of nodes) {
297
+ const reasons = describeNodeSpill(node);
298
+ if (reasons.length > 0) {
299
+ findings.push(` ${formatNodeDiagnostic(node)} -> ${reasons.join(", ")}`);
300
+ }
301
+ }
302
+ const pass = findings.length === 0;
303
+ return {
304
+ pass,
305
+ positiveMessage: `Expected execution plan (${plan.engine}) to have zero memory spills to disk/tempdb, but found ${findings.length} spill indicator(s):
306
+ ${findings.join("\n")}`,
307
+ negatedMessage: `Expected execution plan (${plan.engine}) to spill to disk/tempdb, but zero spills were recorded across ${nodes.length} operator(s).`
308
+ };
309
+ }
310
+ function evaluateToCostLessThan(plan, maxTotalCost) {
311
+ if (typeof maxTotalCost !== "number" || !Number.isFinite(maxTotalCost) || maxTotalCost < 0) {
312
+ throw new TypeError(`maxTotalCost must be a finite non-negative number (received ${String(maxTotalCost)}).`);
313
+ }
314
+ if (plan.facts.estimated_cost_unavailable === true) {
315
+ throw new Error(
316
+ `Cannot assert toCostLessThan(${maxTotalCost}): engine "${plan.engine}" does not report optimizer costs on this plan.`
317
+ );
318
+ }
319
+ const pass = plan.total_cost < maxTotalCost;
320
+ const topNodes = [...collectPlanNodes(plan)].sort((a, b) => b.self_cost - a.self_cost).slice(0, 3).map((n) => ` ${formatNodeDiagnostic(n)} [self_cost=${n.self_cost.toFixed(2)}]`).join("\n");
321
+ return {
322
+ pass,
323
+ positiveMessage: `Expected plan total_cost to be less than ${maxTotalCost}, but got ${plan.total_cost.toFixed(4)} (${plan.engine}).
324
+ Costliest operators:
325
+ ${topNodes}${formatIndexHintsDiagnostic(plan)}`,
326
+ negatedMessage: `Expected plan total_cost not to be less than ${maxTotalCost}, but got ${plan.total_cost.toFixed(4)} (${plan.engine}).`
327
+ };
328
+ }
329
+ function evaluateToCompleteWithin(plan, maxElapsedMs) {
330
+ if (typeof maxElapsedMs !== "number" || !Number.isFinite(maxElapsedMs) || maxElapsedMs < 0) {
331
+ throw new TypeError(`maxElapsedMs must be a finite non-negative number (received ${String(maxElapsedMs)}).`);
332
+ }
333
+ const elapsed = plan.facts.elapsed_ms !== null && plan.facts.elapsed_ms !== void 0 ? plan.facts.elapsed_ms : plan.kind === "actual" && plan.root.act_time_ms !== null ? plan.root.act_time_ms : null;
334
+ if (elapsed === null) {
335
+ throw new Error(
336
+ `Cannot assert toCompleteWithin(${maxElapsedMs}ms): plan (${plan.engine}, kind="${plan.kind}") has no measured elapsed_ms. Run explain() with { analyze: true } or supply an actual execution plan.`
337
+ );
338
+ }
339
+ const pass = elapsed <= maxElapsedMs;
340
+ const slowestNodes = [...collectPlanNodes(plan)].filter((n) => n.act_time_ms !== null).sort((a, b) => (b.act_time_ms ?? 0) - (a.act_time_ms ?? 0)).slice(0, 3).map((n) => ` ${formatNodeDiagnostic(n)}`).join("\n");
341
+ return {
342
+ pass,
343
+ positiveMessage: `Expected query execution to complete within ${maxElapsedMs}ms, but elapsed_ms was ${elapsed.toFixed(3)}ms (${plan.engine}).` + (slowestNodes ? `
344
+ Slowest operators:
345
+ ${slowestNodes}` : ""),
346
+ negatedMessage: `Expected query execution not to complete within ${maxElapsedMs}ms, but elapsed_ms was ${elapsed.toFixed(3)}ms (${plan.engine}).`
347
+ };
348
+ }
349
+ function evaluateToReadAtMostPages(plan, maxLogicalReads) {
350
+ if (typeof maxLogicalReads !== "number" || !Number.isFinite(maxLogicalReads) || maxLogicalReads < 0) {
351
+ throw new TypeError(
352
+ `maxLogicalReads must be a finite non-negative number (received ${String(maxLogicalReads)}).`
353
+ );
354
+ }
355
+ const nodes = collectPlanNodes(plan);
356
+ const nodesWithReads = nodes.filter(
357
+ (n) => n.runtime?.logical_reads !== null && n.runtime?.logical_reads !== void 0
358
+ );
359
+ if (nodesWithReads.length === 0 && plan.kind !== "actual") {
360
+ throw new Error(
361
+ `Cannot assert toReadAtMostPages(${maxLogicalReads}): plan (${plan.engine}, kind="${plan.kind}") has no logical_reads buffer/page counters. Run explain() with { analyze: true, buffers: true } or supply an actual plan with I/O counters.`
362
+ );
363
+ }
364
+ const totalLogicalReads = nodesWithReads.reduce(
365
+ (sum, n) => sum + (n.runtime?.logical_reads ?? 0),
366
+ 0
367
+ );
368
+ const pass = totalLogicalReads <= maxLogicalReads;
369
+ const topReaders = [...nodesWithReads].sort((a, b) => (b.runtime?.logical_reads ?? 0) - (a.runtime?.logical_reads ?? 0)).slice(0, 3).map((n) => ` ${formatNodeDiagnostic(n)}`).join("\n");
370
+ return {
371
+ pass,
372
+ positiveMessage: `Expected plan to read at most ${maxLogicalReads} logical pages/buffers, but read ${totalLogicalReads} (${plan.engine}).` + (topReaders ? `
373
+ Top I/O operators:
374
+ ${topReaders}` : "") + formatIndexHintsDiagnostic(plan),
375
+ negatedMessage: `Expected plan to read more than ${maxLogicalReads} logical pages/buffers, but read ${totalLogicalReads} (${plan.engine}).`
376
+ };
377
+ }
378
+ function evaluateToHaveZeroWarnings(plan) {
379
+ const nodes = collectPlanNodes(plan);
380
+ const issues = [];
381
+ for (const warning of plan.warnings) {
382
+ issues.push(` [plan] warning="${warning}"`);
383
+ }
384
+ for (const conv of plan.facts.conversions) {
385
+ issues.push(` [plan] implicit-conversion (${conv.issue}): ${conv.expression}`);
386
+ }
387
+ if (plan.facts.memory_grant_warning) {
388
+ issues.push(` [plan] memory_grant_warning: ${plan.facts.memory_grant_warning}`);
389
+ }
390
+ for (const node of nodes) {
391
+ const nodeProblems = [];
392
+ for (const w of node.warnings) {
393
+ nodeProblems.push(`warning="${w}"`);
394
+ }
395
+ for (const conv of node.facts.conversions) {
396
+ nodeProblems.push(`implicit-conversion (${conv.issue}): ${conv.expression}`);
397
+ }
398
+ if (nodeProblems.length > 0) {
399
+ issues.push(` ${formatNodeDiagnostic(node)} -> ${nodeProblems.join("; ")}`);
400
+ }
401
+ }
402
+ const pass = issues.length === 0;
403
+ return {
404
+ pass,
405
+ positiveMessage: `Expected execution plan (${plan.engine}) to have zero warnings or implicit conversions, but found ${issues.length}:
406
+ ${issues.join("\n")}${formatIndexHintsDiagnostic(plan)}`,
407
+ negatedMessage: `Expected execution plan (${plan.engine}) to have at least one warning or implicit conversion, but none were present.`
408
+ };
409
+ }
410
+ function evaluateToNotRegressFrom(candidatePlan, baselinePlan, opts) {
411
+ assertIsPlan(baselinePlan);
412
+ if (!isWasmReady()) {
413
+ throw new Error(
414
+ "@culpritsql/plans WebAssembly module is not initialized yet. Call `await initWasm()` or parse plans via `explain()` / `explainText()` before calling `toNotRegressFrom()`."
415
+ );
416
+ }
417
+ const maxCostRatio = opts?.maxCostRatio ?? 1.25;
418
+ const allowScanFlip = opts?.allowScanFlip ?? false;
419
+ if (typeof maxCostRatio !== "number" || !Number.isFinite(maxCostRatio) || maxCostRatio <= 0) {
420
+ throw new TypeError(`maxCostRatio must be a finite positive number (received ${String(maxCostRatio)}).`);
421
+ }
422
+ const diff = diffPlans(baselinePlan, "baseline", candidatePlan, "candidate");
423
+ const regressions = [];
424
+ const nodesA = new Map(collectPlanNodes(baselinePlan).map((n) => [n.id, n]));
425
+ const nodesB = new Map(collectPlanNodes(candidatePlan).map((n) => [n.id, n]));
426
+ if (diff.comparable && diff.cost_ratio !== null && Number.isFinite(diff.cost_ratio)) {
427
+ if (diff.cost_ratio > maxCostRatio) {
428
+ regressions.push(
429
+ ` Cost spike: ${diff.cost_ratio.toFixed(2)}x baseline (baseline=${(diff.cost_a ?? baselinePlan.total_cost).toFixed(4)}, candidate=${(diff.cost_b ?? candidatePlan.total_cost).toFixed(4)}, maxCostRatio=${maxCostRatio})`
430
+ );
431
+ }
432
+ }
433
+ if (!allowScanFlip) {
434
+ const flaggedCandidateNodeIds = /* @__PURE__ */ new Set();
435
+ for (const change of diff.changes) {
436
+ if (change.kind !== "access") continue;
437
+ const nodeA = change.a !== null ? nodesA.get(change.a) : void 0;
438
+ const nodeB = change.b !== null ? nodesB.get(change.b) : void 0;
439
+ if (!nodeB) continue;
440
+ const degradedSeekToScan = nodeA?.kind === "seek" && nodeB.kind === "scan";
441
+ const introducedFullScan = isFullTableScanNode(nodeB) && (!nodeA || !isFullTableScanNode(nodeA));
442
+ if (degradedSeekToScan || introducedFullScan) {
443
+ flaggedCandidateNodeIds.add(nodeB.id);
444
+ regressions.push(
445
+ ` Access-path regression: ${change.title}${change.detail ? ` (${change.detail})` : ""}
446
+ baseline: ${nodeA ? formatNodeDiagnostic(nodeA) : "none"}
447
+ candidate: ${formatNodeDiagnostic(nodeB)}`
448
+ );
449
+ }
450
+ }
451
+ const baselineIndexedTables = /* @__PURE__ */ new Set();
452
+ const baselineScannedTables = /* @__PURE__ */ new Set();
453
+ for (const nodeA of nodesA.values()) {
454
+ const tableKey = nodeA.object ? leafIdentifier(stripIdentifierQuotes(nodeA.object)).toLowerCase() : "";
455
+ if (!tableKey) continue;
456
+ if (isFullTableScanNode(nodeA)) {
457
+ baselineScannedTables.add(tableKey);
458
+ } else if (isIndexAccessNode(nodeA)) {
459
+ baselineIndexedTables.add(tableKey);
460
+ }
461
+ }
462
+ for (const nodeB of nodesB.values()) {
463
+ if (flaggedCandidateNodeIds.has(nodeB.id) || !isFullTableScanNode(nodeB) || !nodeB.object) {
464
+ continue;
465
+ }
466
+ const tableKey = leafIdentifier(stripIdentifierQuotes(nodeB.object)).toLowerCase();
467
+ if (baselineIndexedTables.has(tableKey) && !baselineScannedTables.has(tableKey)) {
468
+ flaggedCandidateNodeIds.add(nodeB.id);
469
+ regressions.push(
470
+ ` Access-path scan flip on "${nodeB.object}": baseline used an index without full scans, candidate performs full scan:
471
+ candidate: ${formatNodeDiagnostic(nodeB)}`
472
+ );
473
+ }
474
+ }
475
+ }
476
+ const pass = regressions.length === 0;
477
+ const headlineSummary = diff.headlines.length > 0 ? `
478
+ Diff headlines:
479
+ ${diff.headlines.map((h) => ` - ${h}`).join("\n")}` : "";
480
+ return {
481
+ pass,
482
+ positiveMessage: `Expected candidate execution plan (${candidatePlan.engine}) not to regress from baseline, but detected ${regressions.length} regression(s):
483
+ ${regressions.join("\n")}${headlineSummary}${formatIndexHintsDiagnostic(candidatePlan)}`,
484
+ negatedMessage: `Expected candidate execution plan (${candidatePlan.engine}) to regress from baseline (maxCostRatio=${maxCostRatio}, allowScanFlip=${String(allowScanFlip)}), but no regressions were detected` + (diff.cost_ratio !== null ? ` (cost_ratio=${diff.cost_ratio.toFixed(2)}x).` : ".")
485
+ };
486
+ }
487
+ var PlanAssertions = class _PlanAssertions {
488
+ #plan;
489
+ #negated;
490
+ #positiveSelf;
491
+ constructor(plan, negated = false, positiveSelf) {
492
+ assertIsPlan(plan);
493
+ this.#plan = plan;
494
+ this.#negated = negated;
495
+ this.#positiveSelf = positiveSelf ?? this;
496
+ }
497
+ /** Negates the next assertion in the chain. */
498
+ get not() {
499
+ return new _PlanAssertions(this.#plan, !this.#negated, this.#positiveSelf);
500
+ }
501
+ #check(result) {
502
+ if (this.#negated) {
503
+ if (result.pass) {
504
+ throw new PlanAssertionError(result.negatedMessage, this.#plan);
505
+ }
506
+ } else if (!result.pass) {
507
+ throw new PlanAssertionError(result.positiveMessage, this.#plan);
508
+ }
509
+ return this.#positiveSelf;
510
+ }
511
+ toUseIndex(indexName) {
512
+ return this.#check(evaluateToUseIndex(this.#plan, indexName));
513
+ }
514
+ toScanTable(tableName) {
515
+ return this.#check(evaluateToScanTable(this.#plan, tableName));
516
+ }
517
+ toHaveZeroSpills() {
518
+ return this.#check(evaluateToHaveZeroSpills(this.#plan));
519
+ }
520
+ toCostLessThan(maxTotalCost) {
521
+ return this.#check(evaluateToCostLessThan(this.#plan, maxTotalCost));
522
+ }
523
+ toCompleteWithin(maxElapsedMs) {
524
+ return this.#check(evaluateToCompleteWithin(this.#plan, maxElapsedMs));
525
+ }
526
+ toReadAtMostPages(maxLogicalReads) {
527
+ return this.#check(evaluateToReadAtMostPages(this.#plan, maxLogicalReads));
528
+ }
529
+ toHaveZeroWarnings() {
530
+ return this.#check(evaluateToHaveZeroWarnings(this.#plan));
531
+ }
532
+ toNotRegressFrom(baselinePlan, opts) {
533
+ return this.#check(evaluateToNotRegressFrom(this.#plan, baselinePlan, opts));
534
+ }
535
+ };
536
+ function assertPlan(plan) {
537
+ return new PlanAssertions(plan);
538
+ }
539
+
540
+ // src/query.ts
541
+ function isIdentStart(ch) {
542
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
543
+ }
544
+ function isIdentPart(ch) {
545
+ return isIdentStart(ch) || ch >= "0" && ch <= "9";
546
+ }
547
+ function matchDollarQuoteTag(sql, start) {
548
+ if (sql[start] !== "$") return null;
549
+ let i = start + 1;
550
+ if (i < sql.length && sql[i] === "$") {
551
+ return "$$";
552
+ }
553
+ if (i >= sql.length || !isIdentStart(sql[i])) {
554
+ return null;
555
+ }
556
+ while (i < sql.length && isIdentPart(sql[i])) {
557
+ i += 1;
558
+ }
559
+ if (i < sql.length && sql[i] === "$") {
560
+ return sql.slice(start, i + 1);
561
+ }
562
+ return null;
563
+ }
564
+ function validateSingleStatementSql(rawSql) {
565
+ const trimmed = rawSql.trim();
566
+ if (trimmed.length === 0) {
567
+ throw new Error("Cannot run EXPLAIN on an empty SQL statement.");
568
+ }
569
+ let hasMeaningfulToken = false;
570
+ let firstSemicolonAt = -1;
571
+ let i = 0;
572
+ while (i < trimmed.length) {
573
+ const ch = trimmed[i];
574
+ const next = trimmed[i + 1];
575
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
576
+ i += 1;
577
+ continue;
578
+ }
579
+ if (ch === "-" && next === "-") {
580
+ i += 2;
581
+ while (i < trimmed.length && trimmed[i] !== "\n") {
582
+ i += 1;
583
+ }
584
+ continue;
585
+ }
586
+ if (ch === "/" && next === "*") {
587
+ const end = trimmed.indexOf("*/", i + 2);
588
+ if (end === -1) {
589
+ throw new Error("Unterminated SQL block comment in EXPLAIN query.");
590
+ }
591
+ i = end + 2;
592
+ continue;
593
+ }
594
+ if (ch === ";") {
595
+ if (!hasMeaningfulToken) {
596
+ throw new Error("Cannot run EXPLAIN on an empty SQL statement.");
597
+ }
598
+ if (firstSemicolonAt === -1) {
599
+ firstSemicolonAt = i;
600
+ } else {
601
+ throw new Error("Multi-statement SQL is not permitted when wrapping EXPLAIN.");
602
+ }
603
+ i += 1;
604
+ continue;
605
+ }
606
+ if (firstSemicolonAt !== -1) {
607
+ throw new Error("Multi-statement SQL is not permitted when wrapping EXPLAIN.");
608
+ }
609
+ hasMeaningfulToken = true;
610
+ if (ch === "'") {
611
+ i += 1;
612
+ while (i < trimmed.length) {
613
+ const c = trimmed[i];
614
+ if (c === "\\" && i + 1 < trimmed.length) {
615
+ i += 2;
616
+ continue;
617
+ }
618
+ if (c === "'" && trimmed[i + 1] === "'") {
619
+ i += 2;
620
+ continue;
621
+ }
622
+ if (c === "'") {
623
+ i += 1;
624
+ break;
625
+ }
626
+ i += 1;
627
+ }
628
+ continue;
629
+ }
630
+ if (ch === '"') {
631
+ i += 1;
632
+ while (i < trimmed.length) {
633
+ if (trimmed[i] === '"' && trimmed[i + 1] === '"') {
634
+ i += 2;
635
+ continue;
636
+ }
637
+ if (trimmed[i] === '"') {
638
+ i += 1;
639
+ break;
640
+ }
641
+ i += 1;
642
+ }
643
+ continue;
644
+ }
645
+ if (ch === "`") {
646
+ i += 1;
647
+ while (i < trimmed.length) {
648
+ if (trimmed[i] === "`" && trimmed[i + 1] === "`") {
649
+ i += 2;
650
+ continue;
651
+ }
652
+ if (trimmed[i] === "`") {
653
+ i += 1;
654
+ break;
655
+ }
656
+ i += 1;
657
+ }
658
+ continue;
659
+ }
660
+ if (ch === "[") {
661
+ const end = trimmed.indexOf("]", i + 1);
662
+ i = end === -1 ? trimmed.length : end + 1;
663
+ continue;
664
+ }
665
+ if (ch === "$") {
666
+ const tag = matchDollarQuoteTag(trimmed, i);
667
+ if (tag !== null) {
668
+ const end = trimmed.indexOf(tag, i + tag.length);
669
+ if (end === -1) {
670
+ throw new Error(`Unterminated dollar-quoted SQL literal (${tag}) in EXPLAIN query.`);
671
+ }
672
+ i = end + tag.length;
673
+ continue;
674
+ }
675
+ }
676
+ i += 1;
677
+ }
678
+ if (!hasMeaningfulToken) {
679
+ throw new Error("Cannot run EXPLAIN on an empty SQL statement.");
680
+ }
681
+ if (firstSemicolonAt !== -1) {
682
+ return trimmed.slice(0, firstSemicolonAt).trimEnd();
683
+ }
684
+ return trimmed;
685
+ }
686
+ function extractNamedParameters(sql) {
687
+ const names = /* @__PURE__ */ new Set();
688
+ scanSqlWithNamedParams(sql, (name) => {
689
+ names.add(name);
690
+ return name;
691
+ });
692
+ return names;
693
+ }
694
+ function bindNamedParams(sql, named, style = "dollar") {
695
+ const params = [];
696
+ const dollarPositions = /* @__PURE__ */ new Map();
697
+ const rewritten = scanSqlWithNamedParams(sql, (name) => {
698
+ if (!Object.hasOwn(named, name)) {
699
+ throw new Error(`Missing value for named SQL parameter "${name}".`);
700
+ }
701
+ const value = named[name];
702
+ if (style === "dollar") {
703
+ const existing = dollarPositions.get(name);
704
+ if (existing !== void 0) {
705
+ return `$${existing}`;
706
+ }
707
+ params.push(value);
708
+ const index = params.length;
709
+ dollarPositions.set(name, index);
710
+ return `$${index}`;
711
+ }
712
+ params.push(value);
713
+ return "?";
714
+ });
715
+ return { sql: rewritten, params };
716
+ }
717
+ function scanSqlWithNamedParams(sql, onParam) {
718
+ let out = "";
719
+ let i = 0;
720
+ while (i < sql.length) {
721
+ const ch = sql[i];
722
+ const next = sql[i + 1];
723
+ if (ch === "-" && next === "-") {
724
+ const nl = sql.indexOf("\n", i + 2);
725
+ const end = nl === -1 ? sql.length : nl + 1;
726
+ out += sql.slice(i, end);
727
+ i = end;
728
+ continue;
729
+ }
730
+ if (ch === "/" && next === "*") {
731
+ const endIdx = sql.indexOf("*/", i + 2);
732
+ const end = endIdx === -1 ? sql.length : endIdx + 2;
733
+ out += sql.slice(i, end);
734
+ i = end;
735
+ continue;
736
+ }
737
+ if (ch === "'") {
738
+ const start = i;
739
+ i += 1;
740
+ while (i < sql.length) {
741
+ const c = sql[i];
742
+ if (c === "\\" && i + 1 < sql.length) {
743
+ i += 2;
744
+ continue;
745
+ }
746
+ if (c === "'" && sql[i + 1] === "'") {
747
+ i += 2;
748
+ continue;
749
+ }
750
+ if (c === "'") {
751
+ i += 1;
752
+ break;
753
+ }
754
+ i += 1;
755
+ }
756
+ out += sql.slice(start, i);
757
+ continue;
758
+ }
759
+ if (ch === '"' || ch === "`") {
760
+ const quote = ch;
761
+ const start = i;
762
+ i += 1;
763
+ while (i < sql.length) {
764
+ if (sql[i] === quote && sql[i + 1] === quote) {
765
+ i += 2;
766
+ continue;
767
+ }
768
+ if (sql[i] === quote) {
769
+ i += 1;
770
+ break;
771
+ }
772
+ i += 1;
773
+ }
774
+ out += sql.slice(start, i);
775
+ continue;
776
+ }
777
+ if (ch === "[") {
778
+ const endIdx = sql.indexOf("]", i + 1);
779
+ const end = endIdx === -1 ? sql.length : endIdx + 1;
780
+ out += sql.slice(i, end);
781
+ i = end;
782
+ continue;
783
+ }
784
+ if (ch === ":" && (next === ":" || next === "=")) {
785
+ out += sql.slice(i, i + 2);
786
+ i += 2;
787
+ continue;
788
+ }
789
+ if (ch === "$") {
790
+ const tag = matchDollarQuoteTag(sql, i);
791
+ if (tag !== null) {
792
+ const closeIdx = sql.indexOf(tag, i + tag.length);
793
+ const end = closeIdx === -1 ? sql.length : closeIdx + tag.length;
794
+ out += sql.slice(i, end);
795
+ i = end;
796
+ continue;
797
+ }
798
+ if (next !== void 0 && isIdentStart(next) && (i === 0 || !isIdentPart(sql[i - 1]))) {
799
+ let end = i + 2;
800
+ while (end < sql.length && isIdentPart(sql[end])) {
801
+ end += 1;
802
+ }
803
+ const name = sql.slice(i + 1, end);
804
+ out += onParam(name, "$");
805
+ i = end;
806
+ continue;
807
+ }
808
+ }
809
+ if (ch === ":" && next !== void 0 && isIdentStart(next) && (i === 0 || !isIdentPart(sql[i - 1]))) {
810
+ let end = i + 2;
811
+ while (end < sql.length && isIdentPart(sql[end])) {
812
+ end += 1;
813
+ }
814
+ const name = sql.slice(i + 1, end);
815
+ out += onParam(name, ":");
816
+ i = end;
817
+ continue;
818
+ }
819
+ out += ch;
820
+ i += 1;
821
+ }
822
+ return out;
823
+ }
824
+ function isQueryBuilder(input) {
825
+ return "toSQL" in input && typeof input.toSQL === "function";
826
+ }
827
+ function isReyloSqlModule(input) {
828
+ if ("sql" in input && typeof input.sql === "string") {
829
+ return true;
830
+ }
831
+ if ("raw" in input && typeof input.raw === "string") {
832
+ return true;
833
+ }
834
+ return false;
835
+ }
836
+ function extractRawQuery(query) {
837
+ if (typeof query === "string") {
838
+ return { rawSql: query, embeddedParams: void 0 };
839
+ }
840
+ if (query !== null && typeof query === "object") {
841
+ if (isQueryBuilder(query)) {
842
+ const built = query.toSQL();
843
+ if (!built || typeof built.sql !== "string") {
844
+ throw new TypeError("Query builder .toSQL() must return an object with a string `sql` property.");
845
+ }
846
+ const embeddedParams = Array.isArray(built.params) ? built.params : Array.isArray(built.bindings) ? built.bindings : void 0;
847
+ return { rawSql: built.sql, embeddedParams };
848
+ }
849
+ if (isReyloSqlModule(query)) {
850
+ const rawSql = "sql" in query ? query.sql : query.raw;
851
+ const embeddedParams = Array.isArray(query.params) ? query.params : void 0;
852
+ return { rawSql, embeddedParams };
853
+ }
854
+ }
855
+ throw new TypeError(
856
+ "Unsupported query input: expected a SQL string, a Reylo { sql } / { raw } module, or a query builder with .toSQL()."
857
+ );
858
+ }
859
+ function normalizeQuery(query, params, style = "dollar") {
860
+ const { rawSql, embeddedParams } = extractRawQuery(query);
861
+ const cleanSql = validateSingleStatementSql(rawSql);
862
+ if (params !== void 0) {
863
+ if (Array.isArray(params)) {
864
+ return { sql: cleanSql, params: [...params] };
865
+ }
866
+ return bindNamedParams(cleanSql, params, style);
867
+ }
868
+ return {
869
+ sql: cleanSql,
870
+ params: embeddedParams ? [...embeddedParams] : []
871
+ };
872
+ }
873
+
874
+ // src/drivers.ts
875
+ var KNOWN_OPTION_KEYS = /* @__PURE__ */ new Set([
876
+ "engine",
877
+ "analyze",
878
+ "buffers",
879
+ "allowMutatingAnalyze"
880
+ ]);
881
+ var RollbackSentinel = class {
882
+ rows;
883
+ constructor(rows) {
884
+ this.rows = rows;
885
+ }
886
+ };
887
+ async function explainText(rawPlan, engine) {
888
+ if (typeof rawPlan !== "string" || rawPlan.trim().length === 0) {
889
+ throw new Error("Cannot parse an empty execution plan string.");
890
+ }
891
+ await ensureWasmInit();
892
+ return parsePlan(rawPlan, engine);
893
+ }
894
+ function formatSqliteExplainRows(rows) {
895
+ if (rows.length === 0) {
896
+ throw new Error("SQLite EXPLAIN QUERY PLAN returned zero rows.");
897
+ }
898
+ const steps = rows.map((row, idx) => {
899
+ if (Array.isArray(row)) {
900
+ const id = Number(row[0] ?? idx + 1);
901
+ const parent = Number(row[1] ?? 0);
902
+ const detail = String(row[3] ?? row[2] ?? "").trim();
903
+ return { id, parent, detail };
904
+ }
905
+ if (row !== null && typeof row === "object") {
906
+ const rec = row;
907
+ const detailRaw = rec.detail ?? rec.DETAIL ?? "";
908
+ const detail = String(detailRaw).trim();
909
+ if ("id" in rec || "ID" in rec) {
910
+ const id = Number(rec.id ?? rec.ID);
911
+ const parent = Number(rec.parent ?? rec.PARENT ?? 0);
912
+ return { id, parent, detail };
913
+ }
914
+ return { id: idx + 1, parent: 0, detail };
915
+ }
916
+ return { id: idx + 1, parent: 0, detail: String(row).trim() };
917
+ });
918
+ if (steps.some((s) => s.detail.length === 0)) {
919
+ throw new Error("SQLite EXPLAIN QUERY PLAN row is missing a `detail` description.");
920
+ }
921
+ const knownIds = new Set(steps.map((s) => s.id));
922
+ const childrenByParent = /* @__PURE__ */ new Map();
923
+ const roots = [];
924
+ for (const step of steps) {
925
+ if (!knownIds.has(step.parent) || step.parent === step.id) {
926
+ roots.push(step);
927
+ } else {
928
+ let list = childrenByParent.get(step.parent);
929
+ if (!list) {
930
+ list = [];
931
+ childrenByParent.set(step.parent, list);
932
+ }
933
+ list.push(step);
934
+ }
935
+ }
936
+ const lines = ["QUERY PLAN"];
937
+ const visited = /* @__PURE__ */ new Set();
938
+ function walk(items, prefix) {
939
+ for (let i = 0; i < items.length; i += 1) {
940
+ const item = items[i];
941
+ const isLast = i === items.length - 1;
942
+ const branch = isLast ? "`--" : "|--";
943
+ lines.push(`${prefix}${branch}${item.detail}`);
944
+ if (!visited.has(item.id)) {
945
+ visited.add(item.id);
946
+ const kids = childrenByParent.get(item.id);
947
+ if (kids && kids.length > 0) {
948
+ walk(kids, `${prefix}${isLast ? " " : "| "}`);
949
+ }
950
+ }
951
+ }
952
+ }
953
+ walk(roots, "");
954
+ return lines.join("\n");
955
+ }
956
+ function isExplainOptionsCandidate(arg, sql) {
957
+ if (arg === null || typeof arg !== "object" || Array.isArray(arg)) {
958
+ return false;
959
+ }
960
+ const keys = Object.keys(arg);
961
+ if (keys.length === 0) {
962
+ return true;
963
+ }
964
+ if (!keys.every((k) => KNOWN_OPTION_KEYS.has(k))) {
965
+ return false;
966
+ }
967
+ const referencedParams = extractNamedParameters(sql);
968
+ return !keys.some((k) => referencedParams.has(k));
969
+ }
970
+ function detectDriverKind(client, explicitEngine) {
971
+ if (typeof client !== "object" && typeof client !== "function" || client === null) {
972
+ throw new TypeError("Unsupported database client: expected a driver connection, pool, or SQL tag.");
973
+ }
974
+ const candidate = client;
975
+ if (explicitEngine === "sqlite") {
976
+ return "sqlite";
977
+ }
978
+ if (explicitEngine === "mysql") {
979
+ return "mysql2";
980
+ }
981
+ if (explicitEngine === "postgres" || explicitEngine === "yugabyte") {
982
+ if (typeof candidate.unsafe === "function") {
983
+ return "postgres-unsafe";
984
+ }
985
+ if (typeof candidate.query === "function") {
986
+ return "pg";
987
+ }
988
+ throw new TypeError(
989
+ `Client does not expose PostgreSQL .query() or .unsafe() methods required for engine "${explicitEngine}".`
990
+ );
991
+ }
992
+ if (typeof candidate.unsafe === "function") {
993
+ return "postgres-unsafe";
994
+ }
995
+ if (typeof candidate.prepare === "function" || typeof candidate.all === "function" || typeof candidate.execute === "function" && typeof candidate.query !== "function") {
996
+ return "sqlite";
997
+ }
998
+ if (typeof candidate.query === "function" && typeof candidate.execute === "function") {
999
+ return "mysql2";
1000
+ }
1001
+ if (typeof candidate.query === "function") {
1002
+ return "pg";
1003
+ }
1004
+ throw new TypeError(
1005
+ "Unable to auto-detect database driver from client shape. Pass `options.engine` or a supported pg, postgres.js, Bun.sql, mysql2, or SQLite client."
1006
+ );
1007
+ }
1008
+ function extractPostgresPlanJson(rows) {
1009
+ if (rows.length === 0) {
1010
+ throw new Error("PostgreSQL EXPLAIN returned zero rows.");
1011
+ }
1012
+ const first = rows[0];
1013
+ if (typeof first === "string") {
1014
+ return first;
1015
+ }
1016
+ if (Array.isArray(first)) {
1017
+ const val = first[0];
1018
+ return typeof val === "string" ? val : JSON.stringify(val);
1019
+ }
1020
+ if (first !== null && typeof first === "object") {
1021
+ const rec = first;
1022
+ const planValue = rec["QUERY PLAN"] ?? rec["query plan"] ?? rec.query_plan ?? Object.values(rec)[0];
1023
+ if (typeof planValue === "string") {
1024
+ if (rows.length > 1) {
1025
+ return rows.map((r) => String(Object.values(r)[0] ?? "")).join("\n");
1026
+ }
1027
+ return planValue;
1028
+ }
1029
+ if (planValue !== void 0) {
1030
+ return JSON.stringify(planValue);
1031
+ }
1032
+ }
1033
+ throw new Error("Unrecognized PostgreSQL EXPLAIN result row format.");
1034
+ }
1035
+ async function runPgExplain(client, sql, params, options) {
1036
+ const engine = options.engine === "yugabyte" ? "yugabyte" : "postgres";
1037
+ const analyze = options.analyze === true;
1038
+ const buffers = options.buffers ?? analyze;
1039
+ const formatOpts = [];
1040
+ if (analyze) formatOpts.push("ANALYZE");
1041
+ if (buffers) formatOpts.push("BUFFERS");
1042
+ formatOpts.push("FORMAT JSON");
1043
+ const explainSql = `EXPLAIN (${formatOpts.join(", ")}) ${sql}`;
1044
+ if (!analyze) {
1045
+ const res2 = await client.query(explainSql, params);
1046
+ const json2 = extractPostgresPlanJson(res2.rows);
1047
+ const plan2 = await explainText(json2, engine);
1048
+ if (plan2.statement === null) {
1049
+ plan2.statement = sql;
1050
+ }
1051
+ return plan2;
1052
+ }
1053
+ if (client.supportsTransactions === false) {
1054
+ if (!options.allowMutatingAnalyze) {
1055
+ throw new Error(
1056
+ "Refusing EXPLAIN ANALYZE: PostgreSQL client reports `supportsTransactions: false` and cannot guarantee a safe BEGIN READ ONLY ... ROLLBACK wrapper. Set `{ allowMutatingAnalyze: true }` to override."
1057
+ );
1058
+ }
1059
+ const res2 = await client.query(explainSql, params);
1060
+ const json2 = extractPostgresPlanJson(res2.rows);
1061
+ const plan2 = await explainText(json2, engine);
1062
+ if (plan2.statement === null) plan2.statement = sql;
1063
+ return plan2;
1064
+ }
1065
+ const isClientInstance = typeof client.processID === "number";
1066
+ if (!isClientInstance && typeof client.connect === "function") {
1067
+ const acquired = await client.connect();
1068
+ if (acquired !== null && typeof acquired === "object" && "query" in acquired && typeof acquired.query === "function") {
1069
+ try {
1070
+ await acquired.query("BEGIN READ ONLY");
1071
+ let res2;
1072
+ try {
1073
+ res2 = await acquired.query(explainSql, params);
1074
+ } finally {
1075
+ await acquired.query("ROLLBACK");
1076
+ }
1077
+ const json2 = extractPostgresPlanJson(res2.rows);
1078
+ const plan2 = await explainText(json2, engine);
1079
+ if (plan2.statement === null) plan2.statement = sql;
1080
+ return plan2;
1081
+ } finally {
1082
+ acquired.release();
1083
+ }
1084
+ }
1085
+ }
1086
+ const looksLikePoolWithoutConnect = typeof client.totalCount === "number" && typeof client.connect !== "function";
1087
+ if (looksLikePoolWithoutConnect) {
1088
+ if (!options.allowMutatingAnalyze) {
1089
+ throw new Error(
1090
+ "Refusing EXPLAIN ANALYZE: pooled PostgreSQL client lacks `.connect()` to pin a session for `BEGIN READ ONLY ... ROLLBACK`. Supply a pool with `.connect()`, a dedicated Client, or `{ allowMutatingAnalyze: true }`."
1091
+ );
1092
+ }
1093
+ const res2 = await client.query(explainSql, params);
1094
+ const json2 = extractPostgresPlanJson(res2.rows);
1095
+ const plan2 = await explainText(json2, engine);
1096
+ if (plan2.statement === null) plan2.statement = sql;
1097
+ return plan2;
1098
+ }
1099
+ await client.query("BEGIN READ ONLY");
1100
+ let res;
1101
+ try {
1102
+ res = await client.query(explainSql, params);
1103
+ } finally {
1104
+ await client.query("ROLLBACK");
1105
+ }
1106
+ const json = extractPostgresPlanJson(res.rows);
1107
+ const plan = await explainText(json, engine);
1108
+ if (plan.statement === null) plan.statement = sql;
1109
+ return plan;
1110
+ }
1111
+ async function runPostgresUnsafeExplain(client, sql, params, options) {
1112
+ const engine = options.engine === "yugabyte" ? "yugabyte" : "postgres";
1113
+ const analyze = options.analyze === true;
1114
+ const buffers = options.buffers ?? analyze;
1115
+ const formatOpts = [];
1116
+ if (analyze) formatOpts.push("ANALYZE");
1117
+ if (buffers) formatOpts.push("BUFFERS");
1118
+ formatOpts.push("FORMAT JSON");
1119
+ const explainSql = `EXPLAIN (${formatOpts.join(", ")}) ${sql}`;
1120
+ if (!analyze) {
1121
+ const rows2 = await client.unsafe(explainSql, params);
1122
+ const json2 = extractPostgresPlanJson(rows2);
1123
+ const plan2 = await explainText(json2, engine);
1124
+ if (plan2.statement === null) plan2.statement = sql;
1125
+ return plan2;
1126
+ }
1127
+ if (typeof client.reserve === "function") {
1128
+ const reserved = await client.reserve();
1129
+ try {
1130
+ await reserved.unsafe("BEGIN READ ONLY");
1131
+ let rows2;
1132
+ try {
1133
+ rows2 = await reserved.unsafe(explainSql, params);
1134
+ } finally {
1135
+ await reserved.unsafe("ROLLBACK");
1136
+ }
1137
+ const json2 = extractPostgresPlanJson(rows2);
1138
+ const plan2 = await explainText(json2, engine);
1139
+ if (plan2.statement === null) plan2.statement = sql;
1140
+ return plan2;
1141
+ } finally {
1142
+ await reserved.release?.();
1143
+ }
1144
+ }
1145
+ if (typeof client.begin === "function") {
1146
+ let capturedRows;
1147
+ try {
1148
+ await client.begin(async (tx) => {
1149
+ await tx.unsafe("SET TRANSACTION READ ONLY");
1150
+ const rows2 = await tx.unsafe(explainSql, params);
1151
+ throw new RollbackSentinel(rows2);
1152
+ });
1153
+ } catch (err) {
1154
+ if (err instanceof RollbackSentinel) {
1155
+ capturedRows = err.rows;
1156
+ } else {
1157
+ throw err;
1158
+ }
1159
+ }
1160
+ const json2 = extractPostgresPlanJson(capturedRows ?? []);
1161
+ const plan2 = await explainText(json2, engine);
1162
+ if (plan2.statement === null) plan2.statement = sql;
1163
+ return plan2;
1164
+ }
1165
+ if (!options.allowMutatingAnalyze) {
1166
+ throw new Error(
1167
+ "Refusing EXPLAIN ANALYZE: PostgreSQL `.unsafe()` driver lacks `.reserve()` or `.begin()` transaction control for a safe `BEGIN READ ONLY ... ROLLBACK` wrapper. Provide transaction control or pass `{ allowMutatingAnalyze: true }`."
1168
+ );
1169
+ }
1170
+ const rows = await client.unsafe(explainSql, params);
1171
+ const json = extractPostgresPlanJson(rows);
1172
+ const plan = await explainText(json, engine);
1173
+ if (plan.statement === null) plan.statement = sql;
1174
+ return plan;
1175
+ }
1176
+ function unwrapMysqlRows(rawResult) {
1177
+ if (Array.isArray(rawResult)) {
1178
+ if (rawResult.length >= 1 && Array.isArray(rawResult[0])) {
1179
+ return rawResult[0];
1180
+ }
1181
+ return rawResult;
1182
+ }
1183
+ if (rawResult !== null && typeof rawResult === "object" && "rows" in rawResult) {
1184
+ const r = rawResult.rows;
1185
+ if (Array.isArray(r)) return r;
1186
+ }
1187
+ throw new Error("Unrecognized MySQL EXPLAIN result shape.");
1188
+ }
1189
+ async function runMysqlExplain(client, sql, params, options) {
1190
+ const analyze = options.analyze === true;
1191
+ const explainSql = analyze ? `EXPLAIN ANALYZE ${sql}` : `EXPLAIN FORMAT=JSON ${sql}`;
1192
+ const rawResult = await client.query(explainSql, params);
1193
+ const rows = unwrapMysqlRows(rawResult);
1194
+ if (rows.length === 0) {
1195
+ throw new Error("MySQL EXPLAIN returned zero rows.");
1196
+ }
1197
+ const lines = rows.map((row) => {
1198
+ if (typeof row === "string") return row;
1199
+ if (row !== null && typeof row === "object") {
1200
+ const rec = row;
1201
+ const val = rec.EXPLAIN ?? rec.explain ?? Object.values(rec)[0];
1202
+ if (typeof val === "string") return val;
1203
+ if (val !== null && typeof val === "object") return JSON.stringify(val);
1204
+ }
1205
+ throw new Error("Unrecognized MySQL EXPLAIN row payload.");
1206
+ });
1207
+ const rawPlan = lines.join("\n");
1208
+ const plan = await explainText(rawPlan, "mysql");
1209
+ if (plan.statement === null) {
1210
+ plan.statement = sql;
1211
+ }
1212
+ return plan;
1213
+ }
1214
+ async function runSqliteExplain(client, sql, params) {
1215
+ const explainSql = `EXPLAIN QUERY PLAN ${sql}`;
1216
+ let rows;
1217
+ if ("prepare" in client && typeof client.prepare === "function") {
1218
+ const stmt = client.prepare(explainSql);
1219
+ const isD1Like = typeof stmt.bind === "function" && "batch" in client && typeof client.batch === "function";
1220
+ const rawOut = isD1Like ? await (params.length > 0 ? stmt.bind(...params) : stmt).all() : await stmt.all(...params);
1221
+ if (Array.isArray(rawOut)) {
1222
+ rows = rawOut;
1223
+ } else if (rawOut !== null && typeof rawOut === "object" && "results" in rawOut && Array.isArray(rawOut.results)) {
1224
+ rows = rawOut.results;
1225
+ } else {
1226
+ throw new Error("Unrecognized SQLite `.prepare().all()` result shape.");
1227
+ }
1228
+ } else if ("all" in client && typeof client.all === "function") {
1229
+ const rawOut = await (params.length > 0 ? client.all(explainSql, params) : client.all(explainSql));
1230
+ if (!Array.isArray(rawOut)) {
1231
+ throw new Error("Unrecognized SQLite `.all()` result shape.");
1232
+ }
1233
+ rows = rawOut;
1234
+ } else if ("execute" in client && typeof client.execute === "function") {
1235
+ const rawOut = await client.execute({ sql: explainSql, args: params });
1236
+ rows = rawOut.rows;
1237
+ } else {
1238
+ throw new TypeError("Unsupported SQLite client: expected `.prepare()`, `.all()`, or `.execute()`.");
1239
+ }
1240
+ const treeText = formatSqliteExplainRows(rows);
1241
+ const plan = await explainText(treeText, "sqlite");
1242
+ if (plan.statement === null) {
1243
+ plan.statement = sql;
1244
+ }
1245
+ return plan;
1246
+ }
1247
+ async function explain(client, query, paramsOrOptions, maybeOptions) {
1248
+ const { rawSql } = extractRawQuery(query);
1249
+ let params;
1250
+ let options;
1251
+ if (maybeOptions !== void 0) {
1252
+ params = paramsOrOptions;
1253
+ options = maybeOptions;
1254
+ } else if (isExplainOptionsCandidate(paramsOrOptions, rawSql)) {
1255
+ params = void 0;
1256
+ options = paramsOrOptions;
1257
+ } else {
1258
+ params = paramsOrOptions;
1259
+ options = {};
1260
+ }
1261
+ if (options.engine === "mssql") {
1262
+ throw new Error(
1263
+ 'Direct SQL Server driver execution is not bundled in `explain()`; capture `.sqlplan` Showplan XML and pass it to `explainText(xml, "mssql")`.'
1264
+ );
1265
+ }
1266
+ const driver = detectDriverKind(client, options.engine);
1267
+ const paramStyle = driver === "pg" || driver === "postgres-unsafe" ? "dollar" : "question";
1268
+ const normalized = normalizeQuery(query, params, paramStyle);
1269
+ switch (driver) {
1270
+ case "pg":
1271
+ return runPgExplain(client, normalized.sql, normalized.params, options);
1272
+ case "postgres-unsafe":
1273
+ return runPostgresUnsafeExplain(
1274
+ client,
1275
+ normalized.sql,
1276
+ normalized.params,
1277
+ options
1278
+ );
1279
+ case "mysql2":
1280
+ return runMysqlExplain(
1281
+ client,
1282
+ normalized.sql,
1283
+ normalized.params,
1284
+ options
1285
+ );
1286
+ case "sqlite":
1287
+ return runSqliteExplain(client, normalized.sql, normalized.params);
1288
+ }
1289
+ }
1290
+
1291
+ // src/matchers.ts
1292
+ function toMatcherResult(evaluation) {
1293
+ return {
1294
+ pass: evaluation.pass,
1295
+ message: () => evaluation.pass ? evaluation.negatedMessage : evaluation.positiveMessage
1296
+ };
1297
+ }
1298
+ var culpritMatchers = {
1299
+ toUseIndex(received, indexName) {
1300
+ assertIsPlan(received);
1301
+ return toMatcherResult(evaluateToUseIndex(received, indexName));
1302
+ },
1303
+ toScanTable(received, tableName) {
1304
+ assertIsPlan(received);
1305
+ return toMatcherResult(evaluateToScanTable(received, tableName));
1306
+ },
1307
+ toHaveZeroSpills(received) {
1308
+ assertIsPlan(received);
1309
+ return toMatcherResult(evaluateToHaveZeroSpills(received));
1310
+ },
1311
+ toCostLessThan(received, maxTotalCost) {
1312
+ assertIsPlan(received);
1313
+ return toMatcherResult(evaluateToCostLessThan(received, maxTotalCost));
1314
+ },
1315
+ toCompleteWithin(received, maxElapsedMs) {
1316
+ assertIsPlan(received);
1317
+ return toMatcherResult(evaluateToCompleteWithin(received, maxElapsedMs));
1318
+ },
1319
+ toReadAtMostPages(received, maxLogicalReads) {
1320
+ assertIsPlan(received);
1321
+ return toMatcherResult(evaluateToReadAtMostPages(received, maxLogicalReads));
1322
+ },
1323
+ toHaveZeroWarnings(received) {
1324
+ assertIsPlan(received);
1325
+ return toMatcherResult(evaluateToHaveZeroWarnings(received));
1326
+ },
1327
+ toNotRegressFrom(received, baselinePlan, opts) {
1328
+ assertIsPlan(received);
1329
+ return toMatcherResult(evaluateToNotRegressFrom(received, baselinePlan, opts));
1330
+ }
1331
+ };
1332
+ export {
1333
+ ParserError,
1334
+ PlanAssertionError,
1335
+ PlanAssertions,
1336
+ assertIsPlan,
1337
+ assertPlan,
1338
+ bindNamedParams,
1339
+ collectPlanNodes,
1340
+ culpritMatchers,
1341
+ diffPlans,
1342
+ ensureWasmInit,
1343
+ evaluateToCompleteWithin,
1344
+ evaluateToCostLessThan,
1345
+ evaluateToHaveZeroSpills,
1346
+ evaluateToHaveZeroWarnings,
1347
+ evaluateToNotRegressFrom,
1348
+ evaluateToReadAtMostPages,
1349
+ evaluateToScanTable,
1350
+ evaluateToUseIndex,
1351
+ explain,
1352
+ explainText,
1353
+ exportPlan,
1354
+ extractNamedParameters,
1355
+ extractRawQuery,
1356
+ formatNodeDiagnostic,
1357
+ formatSqliteExplainRows,
1358
+ init,
1359
+ initWasm,
1360
+ isFullTableScanNode,
1361
+ isIndexAccessNode,
1362
+ isWasmReady,
1363
+ normalizeQuery,
1364
+ parseDeadlock,
1365
+ parsePlan,
1366
+ validateSingleStatementSql
1367
+ };
1368
+ //# sourceMappingURL=index.js.map