@routier/core 0.3.0 → 0.4.0

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.
@@ -2396,8 +2396,26 @@ __webpack_require__.d(__webpack_exports__, {
2396
2396
  class QueryOptionsCollection {
2397
2397
  options = new Map();
2398
2398
  nextExecutionTarget = "database";
2399
+ nextExecutionReason = null;
2399
2400
  nextIndex = 0;
2400
2401
  enumeratedItems = [];
2402
+ /** Cuts over to memory execution, keeping the first cause. See `MemoryExecutionReason`. */ cutOverToMemory(reason) {
2403
+ this.nextExecutionTarget = "memory";
2404
+ if (this.nextExecutionReason == null) {
2405
+ this.nextExecutionReason = reason;
2406
+ }
2407
+ }
2408
+ /**
2409
+ * True when `split()` or `splitAt()` produced this collection.
2410
+ *
2411
+ * Those rebuild each half by re-adding its options, which re-derives execution targets
2412
+ * without the options that caused them — a post-join filter alone in the memory half
2413
+ * derives back to `"database"`. Anything reading `target` as a report of where work runs
2414
+ * has to reject a derived collection; see `explainQuery`.
2415
+ */ derived = false;
2416
+ get isDerived() {
2417
+ return this.derived;
2418
+ }
2401
2419
  get items() {
2402
2420
  return this.options;
2403
2421
  }
@@ -2418,7 +2436,7 @@ class QueryOptionsCollection {
2418
2436
  if (mapValue.fields.some((x)=>x.isRename === true) || mapValue.fields.some((x)=>x.property?.isUnmapped === true)) {
2419
2437
  // Cut over to memory execution since we are renaming a property with .map
2420
2438
  // We do not want to figure out how the new name flows through the entire query
2421
- this.nextExecutionTarget = "memory";
2439
+ this.cutOverToMemory("map-rename");
2422
2440
  }
2423
2441
  }
2424
2442
  if (name === "filter") {
@@ -2430,13 +2448,13 @@ class QueryOptionsCollection {
2430
2448
  return;
2431
2449
  }
2432
2450
  if (filterValue.expression.type === "not-parsable") {
2433
- this.nextExecutionTarget = "memory";
2451
+ this.cutOverToMemory("not-parsable");
2434
2452
  } else {
2435
2453
  (0,_expressions_utils__rspack_import_0/* .forEach */.j)(filterValue.expression, (expression)=>{
2436
2454
  if ((0,_assertions__rspack_import_1/* .isPropertyExpression */.e3)(expression) && expression.property.isUnmapped) {
2437
2455
  // Cut over to memory execution, unmapped properties are not in the database and
2438
2456
  // cannot be queried
2439
- this.nextExecutionTarget = "memory";
2457
+ this.cutOverToMemory("unmapped-property");
2440
2458
  return false;
2441
2459
  }
2442
2460
  if ((0,_assertions__rspack_import_1/* .isPropertyExpression */.e3)(expression) && expression.property.hasRenamedSegments) {
@@ -2444,7 +2462,7 @@ class QueryOptionsCollection {
2444
2462
  // `from` (storage) names, but filter selectors reference the
2445
2463
  // in-memory names. Memory execution runs after deserialization,
2446
2464
  // where the in-memory names exist
2447
- this.nextExecutionTarget = "memory";
2465
+ this.cutOverToMemory("renamed-property");
2448
2466
  return false;
2449
2467
  }
2450
2468
  return true;
@@ -2455,8 +2473,10 @@ class QueryOptionsCollection {
2455
2473
  const sortValue = value;
2456
2474
  // Same rule as filters: sort selectors reference in-memory names, which
2457
2475
  // only exist after deserialization when the property is renamed or unmapped
2458
- if (sortValue.property != null && (sortValue.property.isUnmapped || sortValue.property.hasRenamedSegments)) {
2459
- this.nextExecutionTarget = "memory";
2476
+ if (sortValue.property != null && sortValue.property.isUnmapped) {
2477
+ this.cutOverToMemory("unmapped-property");
2478
+ } else if (sortValue.property != null && sortValue.property.hasRenamedSegments) {
2479
+ this.cutOverToMemory("renamed-property");
2460
2480
  }
2461
2481
  }
2462
2482
  if (name === "nearest") {
@@ -2467,8 +2487,10 @@ class QueryOptionsCollection {
2467
2487
  //
2468
2488
  // This is also what lets every translator's in-memory fallback read the column by
2469
2489
  // its resolved name — anything whose storage name differs never reaches them.
2470
- if (nearestValue.property != null && (nearestValue.property.isUnmapped || nearestValue.property.hasRenamedSegments)) {
2471
- this.nextExecutionTarget = "memory";
2490
+ if (nearestValue.property != null && nearestValue.property.isUnmapped) {
2491
+ this.cutOverToMemory("unmapped-property");
2492
+ } else if (nearestValue.property != null && nearestValue.property.hasRenamedSegments) {
2493
+ this.cutOverToMemory("renamed-property");
2472
2494
  }
2473
2495
  }
2474
2496
  if (name === "join") {
@@ -2480,7 +2502,7 @@ class QueryOptionsCollection {
2480
2502
  // Set BEFORE the item is created, unlike `nearest`'s ratchet below, because this
2481
2503
  // moves the join option itself rather than everything after it.
2482
2504
  if (joinValue.crossPlugin === true) {
2483
- this.nextExecutionTarget = "memory";
2505
+ this.cutOverToMemory("cross-plugin-join");
2484
2506
  }
2485
2507
  }
2486
2508
  const item = {
@@ -2488,7 +2510,10 @@ class QueryOptionsCollection {
2488
2510
  option: {
2489
2511
  name,
2490
2512
  target: this.nextExecutionTarget,
2491
- value
2513
+ value,
2514
+ ...this.nextExecutionReason == null ? {} : {
2515
+ reason: this.nextExecutionReason
2516
+ }
2492
2517
  }
2493
2518
  };
2494
2519
  this.nextIndex++;
@@ -2511,7 +2536,7 @@ class QueryOptionsCollection {
2511
2536
  //
2512
2537
  // A plugin that DID push the search down loses nothing but the chance to also
2513
2538
  // push down what follows it, which is a limit over ten rows.
2514
- this.nextExecutionTarget = "memory";
2539
+ this.cutOverToMemory("after-nearest");
2515
2540
  }
2516
2541
  if (name === "join") {
2517
2542
  // Everything AFTER a join runs in memory, for the same reason as `nearest`: this
@@ -2522,7 +2547,7 @@ class QueryOptionsCollection {
2522
2547
  // OUTER rows read, not the pairs produced — a plausible-looking result with the
2523
2548
  // wrong number of rows in it. Conjuncts that can safely run earlier are split off
2524
2549
  // by the query builder BEFORE dispatch, which is the only exception.
2525
- this.nextExecutionTarget = "memory";
2550
+ this.cutOverToMemory("after-join");
2526
2551
  }
2527
2552
  }
2528
2553
  /**
@@ -2536,6 +2561,8 @@ class QueryOptionsCollection {
2536
2561
  const sortedItems = this.enumeratedItems.toSorted((a, b)=>a.index - b.index);
2537
2562
  const before = new QueryOptionsCollection();
2538
2563
  const after = new QueryOptionsCollection();
2564
+ before.derived = true;
2565
+ after.derived = true;
2539
2566
  let at = null;
2540
2567
  for(let i = 0, length = sortedItems.length; i < length; i++){
2541
2568
  const { option } = sortedItems[i];
@@ -2569,10 +2596,12 @@ class QueryOptionsCollection {
2569
2596
  ]
2570
2597
  ]));
2571
2598
  const nextExecutionTarget = this.nextExecutionTarget;
2599
+ const nextExecutionReason = this.nextExecutionReason;
2572
2600
  const nextIndex = this.nextIndex;
2573
2601
  return ()=>{
2574
2602
  this.options = new Map(options);
2575
2603
  this.nextExecutionTarget = nextExecutionTarget;
2604
+ this.nextExecutionReason = nextExecutionReason;
2576
2605
  this.nextIndex = nextIndex;
2577
2606
  this.enumeratedItems = [];
2578
2607
  };
@@ -2582,6 +2611,8 @@ class QueryOptionsCollection {
2582
2611
  const sortedItems = this.enumeratedItems.toSorted((a, b)=>a.index - b.index);
2583
2612
  const memoryQueryOptionsCollection = new QueryOptionsCollection();
2584
2613
  const databaseQueryOptionsCollection = new QueryOptionsCollection();
2614
+ memoryQueryOptionsCollection.derived = true;
2615
+ databaseQueryOptionsCollection.derived = true;
2585
2616
  for(let i = 0, length = sortedItems.length; i < length; i++){
2586
2617
  const sortedItem = sortedItems[i];
2587
2618
  if (sortedItem.option.target === "database") {
@@ -3012,7 +3043,9 @@ var __webpack_exports__ = {};
3012
3043
 
3013
3044
  // EXPORTS
3014
3045
  __webpack_require__.d(__webpack_exports__, {
3046
+ jO: () => (/* reexport */ TupleTranslator),
3015
3047
  Mr: () => (/* reexport */ deserializeBulkPersist),
3048
+ ae: () => (/* reexport */ explainQuery),
3016
3049
  bX: () => (/* reexport */ ConcurrencyDbPlugin),
3017
3050
  _b: () => (/* reexport */ DEFAULT_SEMI_JOIN_KEY_THRESHOLD),
3018
3051
  pt: () => (/* reexport */ types_QueryOrdering),
@@ -3036,17 +3069,20 @@ __webpack_require__.d(__webpack_exports__, {
3036
3069
  JF: () => (/* reexport */ DataTranslator),
3037
3070
  HM: () => (/* reexport */ QueryOptionsCollection/* .QueryOptionsCollection */.H),
3038
3071
  KB: () => (/* reexport */ createRequestHandler),
3039
- n: () => (/* reexport */ serializeBulkPersist),
3072
+ vZ: () => (/* reexport */ formatExplanation),
3040
3073
  II: () => (/* reexport */ deserializeQueryOptions),
3074
+ n: () => (/* reexport */ serializeBulkPersist),
3041
3075
  as: () => (/* reexport */ loadJoinInnerSide),
3042
3076
  lA: () => (/* reexport */ semiJoinFilter),
3043
3077
  kX: () => (/* reexport */ BatchingDbPlugin),
3044
3078
  DF: () => (/* reexport */ SqlTranslator),
3079
+ gH: () => (/* reexport */ MEMORY_EXECUTION_EXPLANATIONS),
3045
3080
  BL: () => (/* reexport */ serializeQueryOptions),
3081
+ Kg: () => (/* reexport */ withExecutedQueries),
3046
3082
  xw: () => (/* reexport */ TranslatedArrayValue),
3047
3083
  zH: () => (/* reexport */ joinInPlugin),
3048
3084
  XK: () => (/* reexport */ Query),
3049
- jO: () => (/* reexport */ TupleTranslator)
3085
+ jE: () => (/* reexport */ EXECUTED_QUERIES_UNSUPPORTED)
3050
3086
  });
3051
3087
 
3052
3088
  ;// CONCATENATED MODULE: ./src/plugins/translators/TranslatedArrayValue.ts
@@ -3581,7 +3617,11 @@ class Query {
3581
3617
  id: `${event.id}-inner`,
3582
3618
  source: event.source,
3583
3619
  action: "query",
3584
- reason: "join inner side"
3620
+ reason: "join inner side",
3621
+ explain: event.explain,
3622
+ // The same array the outer read pushes into, so a join reports BOTH reads in execution
3623
+ // order. Built fresh rather than spread, so this has to be carried explicitly.
3624
+ executedQueries: event.executedQueries
3585
3625
  };
3586
3626
  query(innerEvent, (result)=>{
3587
3627
  if (result.ok === Result/* .PluginEventResult.ERROR */.D.ERROR) {
@@ -4281,6 +4321,386 @@ class SqlTranslator extends DataTranslator {
4281
4321
 
4282
4322
 
4283
4323
 
4324
+ ;// CONCATENATED MODULE: ./src/plugins/query/explain.ts
4325
+
4326
+ /**
4327
+ * One sentence per reason code, written for someone meeting pushdown for the first time.
4328
+ *
4329
+ * Beside the codes rather than in the formatter, so console output, a failing test and the
4330
+ * docs all say the same thing.
4331
+ */ const MEMORY_EXECUTION_EXPLANATIONS = {
4332
+ "not-parsable": "A filter could not be parsed into an expression tree, so it and every option after it run in memory.",
4333
+ "unmapped-property": "The property is not stored in the database, so it can only be read after deserialization.",
4334
+ "renamed-property": "The property is stored under a different name, and selectors use the in-memory name, so it can only be read after deserialization.",
4335
+ "map-rename": "A map renames or drops properties, so every option after it refers to names the database does not have.",
4336
+ "after-nearest": "A similarity search orders and limits rows, and the plugin cannot report whether it performed the search, so every option after it runs in memory.",
4337
+ "after-join": "A join produces [outer, inner] tuples rather than entities, and the plugin cannot report how it joined, so every option after it runs in memory.",
4338
+ "cross-plugin-join": "The two sides of this join live on different plugins, so neither can read the other's rows and the join runs in the datastore."
4339
+ };
4340
+ const EXECUTED_QUERIES_UNSUPPORTED = "This plugin did not report what it executed. It may not support explain.";
4341
+ const DATABASE_STEP_DESCRIPTION = "These options are sent to the plugin.";
4342
+ const MEMORY_STEP_DESCRIPTION = "Routier runs these over the rows the database returned, after deserializing them.";
4343
+ const UNNARROWED_READ_DESCRIPTION = "No option could be pushed down, so the plugin reads the whole collection.";
4344
+ /**
4345
+ * The reportable shape of one option's value.
4346
+ *
4347
+ * Serializable facts only, never the live selector functions — an explanation is a document a
4348
+ * caller may log, diff in a test, or send to a server, and a closure survives none of that.
4349
+ */ const detailOf = (option)=>{
4350
+ if (option.name === "filter") {
4351
+ const value = option.value;
4352
+ if (value.expression == null) {
4353
+ return undefined;
4354
+ }
4355
+ try {
4356
+ return {
4357
+ expression: types/* .Expression.toJson */.r4.toJson(value.expression)
4358
+ };
4359
+ } catch {
4360
+ // `valueToJson` rejects a value no wire can carry. Reporting the rest of the
4361
+ // explanation beats taking the diagnostic down with the query it describes.
4362
+ return {
4363
+ expressionUnavailable: "This filter holds a value that cannot be serialized."
4364
+ };
4365
+ }
4366
+ }
4367
+ if (option.name === "sort") {
4368
+ const value = option.value;
4369
+ return {
4370
+ propertyName: value.propertyName,
4371
+ direction: value.direction
4372
+ };
4373
+ }
4374
+ if (option.name === "skip" || option.name === "take") {
4375
+ return {
4376
+ value: option.value
4377
+ };
4378
+ }
4379
+ if (option.name === "nearest") {
4380
+ const value = option.value;
4381
+ return {
4382
+ propertyName: value.propertyName,
4383
+ dimensions: value.vector.length,
4384
+ count: value.count
4385
+ };
4386
+ }
4387
+ if (option.name === "join") {
4388
+ const value = option.value;
4389
+ return {
4390
+ kind: value.kind,
4391
+ outerKey: value.outerKey.propertyName,
4392
+ innerKey: value.innerKey.propertyName,
4393
+ crossPlugin: value.crossPlugin,
4394
+ innerOptions: explainedOptionsOf(value.innerOptions)
4395
+ };
4396
+ }
4397
+ if (option.name === "map" || option.name === "group") {
4398
+ const value = option.value;
4399
+ return {
4400
+ fields: value.fields.map((x)=>({
4401
+ from: x.sourceName,
4402
+ to: x.destinationName
4403
+ }))
4404
+ };
4405
+ }
4406
+ return undefined;
4407
+ };
4408
+ const explainedOptionOf = (option, index)=>{
4409
+ const detail = detailOf(option);
4410
+ return {
4411
+ index,
4412
+ name: option.name,
4413
+ ...detail == null ? {} : {
4414
+ detail
4415
+ }
4416
+ };
4417
+ };
4418
+ const explainedOptionsOf = (options)=>{
4419
+ const explained = [];
4420
+ let index = 0;
4421
+ options.forEach((option)=>explained.push(explainedOptionOf(option, index++)));
4422
+ return explained;
4423
+ };
4424
+ const summarize = (steps)=>{
4425
+ const reasons = [];
4426
+ let database = 0;
4427
+ let memory = 0;
4428
+ for (const step of steps){
4429
+ if (step.executedIn === "database") {
4430
+ database += step.options.length;
4431
+ continue;
4432
+ }
4433
+ memory += step.options.length;
4434
+ if (step.reason != null && reasons.includes(step.reason) === false) {
4435
+ reasons.push(step.reason);
4436
+ }
4437
+ }
4438
+ const counts = `${database} ${database === 1 ? "option ran" : "options ran"} in the database, ${memory} ran in memory.`;
4439
+ const causes = reasons.map((reason)=>MEMORY_EXECUTION_EXPLANATIONS[reason]).join(" ");
4440
+ return {
4441
+ database,
4442
+ memory,
4443
+ reasons,
4444
+ explanation: causes.length === 0 ? counts : `${counts} ${causes}`
4445
+ };
4446
+ };
4447
+ /**
4448
+ * Groups options into consecutive runs that execute in the same place.
4449
+ *
4450
+ * A step boundary is where execution moves, and a reader has to see the statement as step 1 OF
4451
+ * 2 to understand it is not the whole query. Cutting over to memory is a ratchet, so the
4452
+ * database options are always a prefix and there are at most two steps.
4453
+ *
4454
+ * A database step is emitted even when NO option pushed down, because the plugin is dispatched
4455
+ * either way — `createQueryPayload` always builds a database event. Without it, the worst case
4456
+ * the feature exists to expose reports "0 in the database" while the backend reads the whole
4457
+ * table, which is the opposite of the truth.
4458
+ */ const toExecutionSteps = (options)=>{
4459
+ const steps = [];
4460
+ let index = 0;
4461
+ options.forEach((option)=>{
4462
+ const explained = explainedOptionOf(option, index++);
4463
+ const current = steps[steps.length - 1];
4464
+ if (current != null && current.executedIn === option.target) {
4465
+ current.options.push(explained);
4466
+ return;
4467
+ }
4468
+ steps.push({
4469
+ step: steps.length + 1,
4470
+ of: 0,
4471
+ executedIn: option.target,
4472
+ description: option.target === "database" ? DATABASE_STEP_DESCRIPTION : MEMORY_STEP_DESCRIPTION,
4473
+ options: [
4474
+ explained
4475
+ ],
4476
+ ...option.reason == null ? {} : {
4477
+ reason: option.reason,
4478
+ explanation: MEMORY_EXECUTION_EXPLANATIONS[option.reason]
4479
+ }
4480
+ });
4481
+ });
4482
+ if (steps[0]?.executedIn !== "database") {
4483
+ steps.unshift({
4484
+ step: 0,
4485
+ of: 0,
4486
+ executedIn: "database",
4487
+ description: UNNARROWED_READ_DESCRIPTION,
4488
+ options: []
4489
+ });
4490
+ }
4491
+ for(let i = 0; i < steps.length; i++){
4492
+ steps[i].step = i + 1;
4493
+ steps[i].of = steps.length;
4494
+ }
4495
+ return steps;
4496
+ };
4497
+ /**
4498
+ * Builds the explanation from the resolved options, with no plugin involvement.
4499
+ *
4500
+ * Takes the collection BEFORE `split()`, and throws otherwise. Splitting re-adds each half
4501
+ * into a fresh collection, which re-derives targets without the options that caused them — a
4502
+ * post-join filter alone in the memory half derives back to `"database"`, and the document
4503
+ * would report memory work as having run in the database.
4504
+ */ const explainQuery = (options, context)=>{
4505
+ if (options.isDerived === true) {
4506
+ throw new Error("explainQuery was given a collection produced by split() or splitAt(). Those re-derive " + "execution targets without the options that caused them, so the explanation would report " + "memory work as having run in the database. Pass the collection as it was resolved, " + "before splitting.");
4507
+ }
4508
+ const executionSteps = toExecutionSteps(options);
4509
+ return {
4510
+ collection: context.collection,
4511
+ database: context.database,
4512
+ summary: summarize(executionSteps),
4513
+ executionSteps,
4514
+ plugin: {
4515
+ kind: context.pluginKind
4516
+ }
4517
+ };
4518
+ };
4519
+ /**
4520
+ * Attaches what the backend reported to the step that was sent to it.
4521
+ *
4522
+ * Reporting is optional for a plugin, so an empty report is not an error: the step is marked
4523
+ * `executedQueriesUnsupported` instead, and the rest of the explanation stands — the pushdown
4524
+ * analysis comes from the options and is correct with or without the plugin's statements.
4525
+ *
4526
+ * Copies the steps rather than writing into them, so the explanation a caller already holds
4527
+ * does not gain statements after the fact. Options and their details are shared with the
4528
+ * original — nothing mutates them, and copying deeper would only look safer than it is.
4529
+ */ const withExecutedQueries = (explanation, executedQueries)=>{
4530
+ let attached = false;
4531
+ const executionSteps = explanation.executionSteps.map((step)=>{
4532
+ // Only the first database step: a plugin reports what IT ran, and everything it ran
4533
+ // was sent as one dispatch. Stamping the same statements onto a second database step
4534
+ // would claim they ran twice.
4535
+ if (step.executedIn !== "database" || attached === true) {
4536
+ return {
4537
+ ...step,
4538
+ options: [
4539
+ ...step.options
4540
+ ]
4541
+ };
4542
+ }
4543
+ attached = true;
4544
+ if (executedQueries.length === 0) {
4545
+ return {
4546
+ ...step,
4547
+ options: [
4548
+ ...step.options
4549
+ ],
4550
+ executedQueriesUnsupported: EXECUTED_QUERIES_UNSUPPORTED
4551
+ };
4552
+ }
4553
+ return {
4554
+ ...step,
4555
+ options: [
4556
+ ...step.options
4557
+ ],
4558
+ executedQueries: [
4559
+ ...executedQueries
4560
+ ]
4561
+ };
4562
+ });
4563
+ return {
4564
+ ...explanation,
4565
+ executionSteps
4566
+ };
4567
+ };
4568
+
4569
+ ;// CONCATENATED MODULE: ./src/plugins/query/formatExplanation.ts
4570
+ const OPTION_LABEL_WIDTH = 8;
4571
+ const WRAP_WIDTH = 68;
4572
+ /** Wraps `text` to `WRAP_WIDTH`, prefixing every line with `indent`. */ const wrap = (text, indent)=>{
4573
+ const lines = [];
4574
+ let line = "";
4575
+ for (const word of text.split(" ")){
4576
+ if (line.length > 0 && line.length + word.length + 1 > WRAP_WIDTH) {
4577
+ lines.push(indent + line);
4578
+ line = word;
4579
+ continue;
4580
+ }
4581
+ line = line.length === 0 ? word : `${line} ${word}`;
4582
+ }
4583
+ if (line.length > 0) {
4584
+ lines.push(indent + line);
4585
+ }
4586
+ return lines;
4587
+ };
4588
+ const COMPARATOR_SYMBOLS = {
4589
+ "equals": "===",
4590
+ "greater-than": ">",
4591
+ "greater-than-equals": ">=",
4592
+ "less-than": "<",
4593
+ "less-than-equals": "<="
4594
+ };
4595
+ const describeValue = (value)=>{
4596
+ if (value == null) {
4597
+ return "?";
4598
+ }
4599
+ if (value.k === "raw") {
4600
+ return typeof value.v === "string" ? `"${value.v}"` : String(value.v);
4601
+ }
4602
+ if (value.k === "date") {
4603
+ return value.v;
4604
+ }
4605
+ if (value.k === "array") {
4606
+ return `[${value.v.map(describeValue).join(", ")}]`;
4607
+ }
4608
+ return value.k === "undefined" ? "undefined" : String(value.v);
4609
+ };
4610
+ /** Renders a serialized expression back to something close to the source predicate. */ const describeExpression = (expression)=>{
4611
+ if (expression == null) {
4612
+ return "?";
4613
+ }
4614
+ if (expression.t === "operator") {
4615
+ return `${describeExpression(expression.left)} ${expression.operator} ${describeExpression(expression.right)}`;
4616
+ }
4617
+ if (expression.t === "comparator") {
4618
+ const left = describeExpression(expression.left);
4619
+ const right = describeExpression(expression.right);
4620
+ const symbol = COMPARATOR_SYMBOLS[expression.comparator];
4621
+ if (symbol == null) {
4622
+ return `${left}.${expression.comparator}(${right})${expression.negated === true ? " === false" : ""}`;
4623
+ }
4624
+ return `${left} ${expression.negated === true ? "!==" : symbol} ${right}`;
4625
+ }
4626
+ if (expression.t === "property") {
4627
+ return expression.path;
4628
+ }
4629
+ if (expression.t === "value") {
4630
+ return describeValue(expression.value);
4631
+ }
4632
+ return expression.t === "empty" ? "(no filter)" : "(not parsable)";
4633
+ };
4634
+ const describeOption = (option)=>{
4635
+ const detail = option.detail;
4636
+ if (detail == null) {
4637
+ return "";
4638
+ }
4639
+ if (option.name === "filter") {
4640
+ return detail.expression == null ? String(detail.expressionUnavailable ?? "") : describeExpression(detail.expression);
4641
+ }
4642
+ if (option.name === "sort") {
4643
+ return `${detail.propertyName} ${detail.direction}`;
4644
+ }
4645
+ if (option.name === "skip" || option.name === "take") {
4646
+ return String(detail.value);
4647
+ }
4648
+ if (option.name === "join") {
4649
+ return `${detail.kind} → ${detail.outerKey} = ${detail.innerKey}`;
4650
+ }
4651
+ if (option.name === "nearest") {
4652
+ return `${detail.propertyName}, ${detail.count} nearest`;
4653
+ }
4654
+ if (option.name === "map" || option.name === "group") {
4655
+ const fields = detail.fields;
4656
+ return fields.map((x)=>x.from === x.to ? x.from : `${x.from} → ${x.to}`).join(", ");
4657
+ }
4658
+ return "";
4659
+ };
4660
+ const formatStep = (step, lines)=>{
4661
+ const reason = step.reason == null ? "" : ` [${step.reason}]`;
4662
+ lines.push(` STEP ${step.step} of ${step.of} — ${step.executedIn}${reason}`);
4663
+ lines.push(...wrap(step.description, " "));
4664
+ if (step.explanation != null) {
4665
+ lines.push(...wrap(step.explanation, " "));
4666
+ }
4667
+ lines.push("");
4668
+ for (const option of step.options){
4669
+ lines.push(` ${option.name.padEnd(OPTION_LABEL_WIDTH)} ${describeOption(option)}`.trimEnd());
4670
+ }
4671
+ for (const executed of step.executedQueries ?? []){
4672
+ lines.push("");
4673
+ lines.push(...executed.text.split("\n").map((line)=>` ${line}`));
4674
+ if (executed.parameters != null && executed.parameters.length > 0) {
4675
+ lines.push(` parameters: ${JSON.stringify(executed.parameters)}`);
4676
+ }
4677
+ }
4678
+ if (step.executedQueriesUnsupported != null) {
4679
+ lines.push("");
4680
+ lines.push(...wrap(step.executedQueriesUnsupported, " "));
4681
+ }
4682
+ lines.push("");
4683
+ };
4684
+ /**
4685
+ * Renders an explanation for a terminal.
4686
+ *
4687
+ * The STEP headers carry the whole lesson: a reader who has never heard of pushdown still sees
4688
+ * that the statement in step 1 is not the entire query. Nobody should have to notice a missing
4689
+ * ORDER BY to work that out.
4690
+ */ const formatExplanation = (explanation)=>{
4691
+ const { collection, database, summary, executionSteps } = explanation;
4692
+ const stepCount = `${executionSteps.length} ${executionSteps.length === 1 ? "step" : "steps"}`;
4693
+ const lines = [
4694
+ `${collection} · ${database} · ${stepCount}`,
4695
+ ""
4696
+ ];
4697
+ for (const step of executionSteps){
4698
+ formatStep(step, lines);
4699
+ }
4700
+ lines.push(...wrap(summary.explanation, " "));
4701
+ return lines.join("\n");
4702
+ };
4703
+
4284
4704
  ;// CONCATENATED MODULE: ./src/plugins/query/types.ts
4285
4705
  var types_QueryOrdering = /*#__PURE__*/ function(QueryOrdering) {
4286
4706
  QueryOrdering["Descending"] = "desc";
@@ -4295,6 +4715,8 @@ var types_QueryOrdering = /*#__PURE__*/ function(QueryOrdering) {
4295
4715
 
4296
4716
 
4297
4717
 
4718
+
4719
+
4298
4720
  // EXTERNAL MODULE: ./src/expressions/evaluate.ts
4299
4721
  var evaluate = __webpack_require__(379);
4300
4722
  ;// CONCATENATED MODULE: ./src/plugins/wire/query.ts
@@ -4766,6 +5188,7 @@ const createRequestHandler = (options)=>{
4766
5188
  const queryOptions = deserializeQueryOptions(request.options, schema, resolveSchema, // Applied to the outer collection AND to every collection a join reaches, so a
4767
5189
  // join cannot be used to read around a scope
4768
5190
  (target)=>scopeExpressionFor(target, context, "query"));
5191
+ const executedQueries = [];
4769
5192
  return await new Promise((resolve)=>{
4770
5193
  plugin.query({
4771
5194
  // `false`: nothing here attaches to a change tracker — the tracker lives on
@@ -4774,7 +5197,9 @@ const createRequestHandler = (options)=>{
4774
5197
  schemas: schemas,
4775
5198
  id: (0,uuid/* .uuid */.u)(8),
4776
5199
  source: "RequestHandler",
4777
- action: "query"
5200
+ action: "query",
5201
+ explain: request.explain,
5202
+ executedQueries
4778
5203
  }, (result)=>{
4779
5204
  if (result.ok === Result/* .PluginEventResult.ERROR */.D.ERROR) {
4780
5205
  resolve(failed(result.error));
@@ -4783,7 +5208,13 @@ const createRequestHandler = (options)=>{
4783
5208
  resolve({
4784
5209
  ok: true,
4785
5210
  kind: "query",
4786
- value: result.data.value
5211
+ value: result.data.value,
5212
+ // Only when asked, and only what the plugin reported. A plugin
5213
+ // that reported nothing sends nothing, and the caller marks the
5214
+ // remote step as not reported.
5215
+ ...request.explain === true && executedQueries.length > 0 ? {
5216
+ executedQueries
5217
+ } : {}
4787
5218
  });
4788
5219
  });
4789
5220
  });
@@ -5432,6 +5863,10 @@ class EphemeralDataPlugin {
5432
5863
  }
5433
5864
  innerRows.push(cloneRecord(record));
5434
5865
  }
5866
+ const narrowing = outerKeys == null ? "full scan" : `narrowed by ${outerKeys.size} outer ${outerKeys.size === 1 ? "key" : "keys"}`;
5867
+ event.executedQueries.push({
5868
+ text: `${innerSchema.collectionName}: scanned ${innerRows.length} in-memory ${innerRows.length === 1 ? "record" : "records"} for join inner side (${narrowing})`
5869
+ });
5435
5870
  done({
5436
5871
  ok: "success",
5437
5872
  innerSide: {
@@ -5541,7 +5976,13 @@ class EphemeralDataPlugin {
5541
5976
  * collection to pair it with three rows.
5542
5977
  *
5543
5978
  * `cloned` is in storage shape, so the keys are read by resolved column name.
5544
- */ const joinOption = operation.options.getLast("join");
5979
+ */ // No statement to quote — an ephemeral store walks its own records. Said
5980
+ // plainly so `.explain()` does not leave a reader wondering whether the
5981
+ // plugin simply failed to report. Before the inner side, to match execution order.
5982
+ event.executedQueries.push({
5983
+ text: `${operation.schema.collectionName}: scanned ${cloned.length} in-memory ${cloned.length === 1 ? "record" : "records"}`
5984
+ });
5985
+ const joinOption = operation.options.getLast("join");
5545
5986
  const outerKeys = joinOption == null ? null : distinctJoinKeys(cloned, joinOption.value.outerKey, joinOption.value.semiJoinKeyThreshold, {
5546
5987
  storageShape: true
5547
5988
  });
@@ -5634,7 +6075,7 @@ class RetryDbPlugin {
5634
6075
  * `PropertyInfo` objects carrying functions and would not survive `JSON.stringify`. A filter is
5635
6076
  * identified by its source text plus its params, which is what the expression is derived from
5636
6077
  * anyway — two queries with the same source and params are the same query.
5637
- */ const describeOption = (option)=>{
6078
+ */ const CacheDbPlugin_describeOption = (option)=>{
5638
6079
  const value = option.value;
5639
6080
  switch(option.name){
5640
6081
  case "filter":
@@ -5668,7 +6109,7 @@ class CacheDbPlugin {
5668
6109
  /** `schemaId` first, so invalidating a schema is a prefix match. */ keyFor(event) {
5669
6110
  const parts = [];
5670
6111
  event.operation.options.forEach((option)=>{
5671
- parts.push(`${option.name}:${describeOption(option)}`);
6112
+ parts.push(`${option.name}:${CacheDbPlugin_describeOption(option)}`);
5672
6113
  });
5673
6114
  return `${String(event.operation.schema.id)}\u0000${parts.join("\u0001")}`;
5674
6115
  }
@@ -5698,6 +6139,12 @@ class CacheDbPlugin {
5698
6139
  // Re-set to move it to the end of the insertion order: most recently used.
5699
6140
  this.entries.delete(key);
5700
6141
  this.entries.set(key, cached);
6142
+ // Said rather than left blank. A hit means no database was touched, which is a fact
6143
+ // worth reporting — and an empty report would otherwise read as a plugin that failed
6144
+ // to say what it ran.
6145
+ event.executedQueries.push({
6146
+ text: "cache hit — no query was executed"
6147
+ });
5701
6148
  done(Result/* .PluginEventResult.success */.D.success(event.id, this.rebuild(cached)));
5702
6149
  return;
5703
6150
  }
@@ -6089,8 +6536,10 @@ var __webpack_exports__CacheDbPlugin = __webpack_exports__.y4;
6089
6536
  var __webpack_exports__ConcurrencyDbPlugin = __webpack_exports__.bX;
6090
6537
  var __webpack_exports__DEFAULT_SEMI_JOIN_KEY_THRESHOLD = __webpack_exports__._b;
6091
6538
  var __webpack_exports__DataTranslator = __webpack_exports__.JF;
6539
+ var __webpack_exports__EXECUTED_QUERIES_UNSUPPORTED = __webpack_exports__.jE;
6092
6540
  var __webpack_exports__EphemeralDataPlugin = __webpack_exports__.Jd;
6093
6541
  var __webpack_exports__JsonTranslator = __webpack_exports__.d0;
6542
+ var __webpack_exports__MEMORY_EXECUTION_EXPLANATIONS = __webpack_exports__.gH;
6094
6543
  var __webpack_exports__Query = __webpack_exports__.XK;
6095
6544
  var __webpack_exports__QueryOptionsCollection = __webpack_exports__.HM;
6096
6545
  var __webpack_exports__QueryOrdering = __webpack_exports__.pt;
@@ -6108,6 +6557,8 @@ var __webpack_exports__deserializePersistResult = __webpack_exports__.Pl;
6108
6557
  var __webpack_exports__deserializeQueryOptions = __webpack_exports__.II;
6109
6558
  var __webpack_exports__distinctJoinKeys = __webpack_exports__.RK;
6110
6559
  var __webpack_exports__executeJoin = __webpack_exports__.m6;
6560
+ var __webpack_exports__explainQuery = __webpack_exports__.ae;
6561
+ var __webpack_exports__formatExplanation = __webpack_exports__.vZ;
6111
6562
  var __webpack_exports__hashJoin = __webpack_exports__.Bg;
6112
6563
  var __webpack_exports__joinInPlugin = __webpack_exports__.zH;
6113
6564
  var __webpack_exports__loadJoinInnerSide = __webpack_exports__.as;
@@ -6119,6 +6570,7 @@ var __webpack_exports__serializePersistResult = __webpack_exports__.yR;
6119
6570
  var __webpack_exports__serializeQueryOptions = __webpack_exports__.BL;
6120
6571
  var __webpack_exports__splitSendableOptions = __webpack_exports__.PP;
6121
6572
  var __webpack_exports__toEntityShape = __webpack_exports__.__;
6122
- export { __webpack_exports__BatchingDbPlugin as BatchingDbPlugin, __webpack_exports__CacheDbPlugin as CacheDbPlugin, __webpack_exports__ConcurrencyDbPlugin as ConcurrencyDbPlugin, __webpack_exports__DEFAULT_SEMI_JOIN_KEY_THRESHOLD as DEFAULT_SEMI_JOIN_KEY_THRESHOLD, __webpack_exports__DataTranslator as DataTranslator, __webpack_exports__EphemeralDataPlugin as EphemeralDataPlugin, __webpack_exports__JsonTranslator as JsonTranslator, __webpack_exports__Query as Query, __webpack_exports__QueryOptionsCollection as QueryOptionsCollection, __webpack_exports__QueryOrdering as QueryOrdering, __webpack_exports__RetryDbPlugin as RetryDbPlugin, __webpack_exports__SqlTranslator as SqlTranslator, __webpack_exports__TranslatedArrayValue as TranslatedArrayValue, __webpack_exports__TranslatedGroupValue as TranslatedGroupValue, __webpack_exports__TranslatedSingleValue as TranslatedSingleValue, __webpack_exports__TupleTranslator as TupleTranslator, __webpack_exports__applyInnerOptions as applyInnerOptions, __webpack_exports__cosineDistance as cosineDistance, __webpack_exports__createRequestHandler as createRequestHandler, __webpack_exports__deserializeBulkPersist as deserializeBulkPersist, __webpack_exports__deserializePersistResult as deserializePersistResult, __webpack_exports__deserializeQueryOptions as deserializeQueryOptions, __webpack_exports__distinctJoinKeys as distinctJoinKeys, __webpack_exports__executeJoin as executeJoin, __webpack_exports__hashJoin as hashJoin, __webpack_exports__joinInPlugin as joinInPlugin, __webpack_exports__loadJoinInnerSide as loadJoinInnerSide, __webpack_exports__nearestBy as nearestBy, __webpack_exports__readJoinKey as readJoinKey, __webpack_exports__semiJoinFilter as semiJoinFilter, __webpack_exports__serializeBulkPersist as serializeBulkPersist, __webpack_exports__serializePersistResult as serializePersistResult, __webpack_exports__serializeQueryOptions as serializeQueryOptions, __webpack_exports__splitSendableOptions as splitSendableOptions, __webpack_exports__toEntityShape as toEntityShape };
6573
+ var __webpack_exports__withExecutedQueries = __webpack_exports__.Kg;
6574
+ export { __webpack_exports__BatchingDbPlugin as BatchingDbPlugin, __webpack_exports__CacheDbPlugin as CacheDbPlugin, __webpack_exports__ConcurrencyDbPlugin as ConcurrencyDbPlugin, __webpack_exports__DEFAULT_SEMI_JOIN_KEY_THRESHOLD as DEFAULT_SEMI_JOIN_KEY_THRESHOLD, __webpack_exports__DataTranslator as DataTranslator, __webpack_exports__EXECUTED_QUERIES_UNSUPPORTED as EXECUTED_QUERIES_UNSUPPORTED, __webpack_exports__EphemeralDataPlugin as EphemeralDataPlugin, __webpack_exports__JsonTranslator as JsonTranslator, __webpack_exports__MEMORY_EXECUTION_EXPLANATIONS as MEMORY_EXECUTION_EXPLANATIONS, __webpack_exports__Query as Query, __webpack_exports__QueryOptionsCollection as QueryOptionsCollection, __webpack_exports__QueryOrdering as QueryOrdering, __webpack_exports__RetryDbPlugin as RetryDbPlugin, __webpack_exports__SqlTranslator as SqlTranslator, __webpack_exports__TranslatedArrayValue as TranslatedArrayValue, __webpack_exports__TranslatedGroupValue as TranslatedGroupValue, __webpack_exports__TranslatedSingleValue as TranslatedSingleValue, __webpack_exports__TupleTranslator as TupleTranslator, __webpack_exports__applyInnerOptions as applyInnerOptions, __webpack_exports__cosineDistance as cosineDistance, __webpack_exports__createRequestHandler as createRequestHandler, __webpack_exports__deserializeBulkPersist as deserializeBulkPersist, __webpack_exports__deserializePersistResult as deserializePersistResult, __webpack_exports__deserializeQueryOptions as deserializeQueryOptions, __webpack_exports__distinctJoinKeys as distinctJoinKeys, __webpack_exports__executeJoin as executeJoin, __webpack_exports__explainQuery as explainQuery, __webpack_exports__formatExplanation as formatExplanation, __webpack_exports__hashJoin as hashJoin, __webpack_exports__joinInPlugin as joinInPlugin, __webpack_exports__loadJoinInnerSide as loadJoinInnerSide, __webpack_exports__nearestBy as nearestBy, __webpack_exports__readJoinKey as readJoinKey, __webpack_exports__semiJoinFilter as semiJoinFilter, __webpack_exports__serializeBulkPersist as serializeBulkPersist, __webpack_exports__serializePersistResult as serializePersistResult, __webpack_exports__serializeQueryOptions as serializeQueryOptions, __webpack_exports__splitSendableOptions as splitSendableOptions, __webpack_exports__toEntityShape as toEntityShape, __webpack_exports__withExecutedQueries as withExecutedQueries };
6123
6575
 
6124
6576
  //# sourceMappingURL=index.js.map