@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.
@@ -2398,8 +2398,26 @@ __webpack_require__.d(__webpack_exports__, {
2398
2398
  class QueryOptionsCollection {
2399
2399
  options = new Map();
2400
2400
  nextExecutionTarget = "database";
2401
+ nextExecutionReason = null;
2401
2402
  nextIndex = 0;
2402
2403
  enumeratedItems = [];
2404
+ /** Cuts over to memory execution, keeping the first cause. See `MemoryExecutionReason`. */ cutOverToMemory(reason) {
2405
+ this.nextExecutionTarget = "memory";
2406
+ if (this.nextExecutionReason == null) {
2407
+ this.nextExecutionReason = reason;
2408
+ }
2409
+ }
2410
+ /**
2411
+ * True when `split()` or `splitAt()` produced this collection.
2412
+ *
2413
+ * Those rebuild each half by re-adding its options, which re-derives execution targets
2414
+ * without the options that caused them — a post-join filter alone in the memory half
2415
+ * derives back to `"database"`. Anything reading `target` as a report of where work runs
2416
+ * has to reject a derived collection; see `explainQuery`.
2417
+ */ derived = false;
2418
+ get isDerived() {
2419
+ return this.derived;
2420
+ }
2403
2421
  get items() {
2404
2422
  return this.options;
2405
2423
  }
@@ -2420,7 +2438,7 @@ class QueryOptionsCollection {
2420
2438
  if (mapValue.fields.some((x)=>x.isRename === true) || mapValue.fields.some((x)=>x.property?.isUnmapped === true)) {
2421
2439
  // Cut over to memory execution since we are renaming a property with .map
2422
2440
  // We do not want to figure out how the new name flows through the entire query
2423
- this.nextExecutionTarget = "memory";
2441
+ this.cutOverToMemory("map-rename");
2424
2442
  }
2425
2443
  }
2426
2444
  if (name === "filter") {
@@ -2432,13 +2450,13 @@ class QueryOptionsCollection {
2432
2450
  return;
2433
2451
  }
2434
2452
  if (filterValue.expression.type === "not-parsable") {
2435
- this.nextExecutionTarget = "memory";
2453
+ this.cutOverToMemory("not-parsable");
2436
2454
  } else {
2437
2455
  (0,_expressions_utils__rspack_import_0/* .forEach */.j)(filterValue.expression, (expression)=>{
2438
2456
  if ((0,_assertions__rspack_import_1.isPropertyExpression)(expression) && expression.property.isUnmapped) {
2439
2457
  // Cut over to memory execution, unmapped properties are not in the database and
2440
2458
  // cannot be queried
2441
- this.nextExecutionTarget = "memory";
2459
+ this.cutOverToMemory("unmapped-property");
2442
2460
  return false;
2443
2461
  }
2444
2462
  if ((0,_assertions__rspack_import_1.isPropertyExpression)(expression) && expression.property.hasRenamedSegments) {
@@ -2446,7 +2464,7 @@ class QueryOptionsCollection {
2446
2464
  // `from` (storage) names, but filter selectors reference the
2447
2465
  // in-memory names. Memory execution runs after deserialization,
2448
2466
  // where the in-memory names exist
2449
- this.nextExecutionTarget = "memory";
2467
+ this.cutOverToMemory("renamed-property");
2450
2468
  return false;
2451
2469
  }
2452
2470
  return true;
@@ -2457,8 +2475,10 @@ class QueryOptionsCollection {
2457
2475
  const sortValue = value;
2458
2476
  // Same rule as filters: sort selectors reference in-memory names, which
2459
2477
  // only exist after deserialization when the property is renamed or unmapped
2460
- if (sortValue.property != null && (sortValue.property.isUnmapped || sortValue.property.hasRenamedSegments)) {
2461
- this.nextExecutionTarget = "memory";
2478
+ if (sortValue.property != null && sortValue.property.isUnmapped) {
2479
+ this.cutOverToMemory("unmapped-property");
2480
+ } else if (sortValue.property != null && sortValue.property.hasRenamedSegments) {
2481
+ this.cutOverToMemory("renamed-property");
2462
2482
  }
2463
2483
  }
2464
2484
  if (name === "nearest") {
@@ -2469,8 +2489,10 @@ class QueryOptionsCollection {
2469
2489
  //
2470
2490
  // This is also what lets every translator's in-memory fallback read the column by
2471
2491
  // its resolved name — anything whose storage name differs never reaches them.
2472
- if (nearestValue.property != null && (nearestValue.property.isUnmapped || nearestValue.property.hasRenamedSegments)) {
2473
- this.nextExecutionTarget = "memory";
2492
+ if (nearestValue.property != null && nearestValue.property.isUnmapped) {
2493
+ this.cutOverToMemory("unmapped-property");
2494
+ } else if (nearestValue.property != null && nearestValue.property.hasRenamedSegments) {
2495
+ this.cutOverToMemory("renamed-property");
2474
2496
  }
2475
2497
  }
2476
2498
  if (name === "join") {
@@ -2482,7 +2504,7 @@ class QueryOptionsCollection {
2482
2504
  // Set BEFORE the item is created, unlike `nearest`'s ratchet below, because this
2483
2505
  // moves the join option itself rather than everything after it.
2484
2506
  if (joinValue.crossPlugin === true) {
2485
- this.nextExecutionTarget = "memory";
2507
+ this.cutOverToMemory("cross-plugin-join");
2486
2508
  }
2487
2509
  }
2488
2510
  const item = {
@@ -2490,7 +2512,10 @@ class QueryOptionsCollection {
2490
2512
  option: {
2491
2513
  name,
2492
2514
  target: this.nextExecutionTarget,
2493
- value
2515
+ value,
2516
+ ...this.nextExecutionReason == null ? {} : {
2517
+ reason: this.nextExecutionReason
2518
+ }
2494
2519
  }
2495
2520
  };
2496
2521
  this.nextIndex++;
@@ -2513,7 +2538,7 @@ class QueryOptionsCollection {
2513
2538
  //
2514
2539
  // A plugin that DID push the search down loses nothing but the chance to also
2515
2540
  // push down what follows it, which is a limit over ten rows.
2516
- this.nextExecutionTarget = "memory";
2541
+ this.cutOverToMemory("after-nearest");
2517
2542
  }
2518
2543
  if (name === "join") {
2519
2544
  // Everything AFTER a join runs in memory, for the same reason as `nearest`: this
@@ -2524,7 +2549,7 @@ class QueryOptionsCollection {
2524
2549
  // OUTER rows read, not the pairs produced — a plausible-looking result with the
2525
2550
  // wrong number of rows in it. Conjuncts that can safely run earlier are split off
2526
2551
  // by the query builder BEFORE dispatch, which is the only exception.
2527
- this.nextExecutionTarget = "memory";
2552
+ this.cutOverToMemory("after-join");
2528
2553
  }
2529
2554
  }
2530
2555
  /**
@@ -2538,6 +2563,8 @@ class QueryOptionsCollection {
2538
2563
  const sortedItems = this.enumeratedItems.toSorted((a, b)=>a.index - b.index);
2539
2564
  const before = new QueryOptionsCollection();
2540
2565
  const after = new QueryOptionsCollection();
2566
+ before.derived = true;
2567
+ after.derived = true;
2541
2568
  let at = null;
2542
2569
  for(let i = 0, length = sortedItems.length; i < length; i++){
2543
2570
  const { option } = sortedItems[i];
@@ -2571,10 +2598,12 @@ class QueryOptionsCollection {
2571
2598
  ]
2572
2599
  ]));
2573
2600
  const nextExecutionTarget = this.nextExecutionTarget;
2601
+ const nextExecutionReason = this.nextExecutionReason;
2574
2602
  const nextIndex = this.nextIndex;
2575
2603
  return ()=>{
2576
2604
  this.options = new Map(options);
2577
2605
  this.nextExecutionTarget = nextExecutionTarget;
2606
+ this.nextExecutionReason = nextExecutionReason;
2578
2607
  this.nextIndex = nextIndex;
2579
2608
  this.enumeratedItems = [];
2580
2609
  };
@@ -2584,6 +2613,8 @@ class QueryOptionsCollection {
2584
2613
  const sortedItems = this.enumeratedItems.toSorted((a, b)=>a.index - b.index);
2585
2614
  const memoryQueryOptionsCollection = new QueryOptionsCollection();
2586
2615
  const databaseQueryOptionsCollection = new QueryOptionsCollection();
2616
+ memoryQueryOptionsCollection.derived = true;
2617
+ databaseQueryOptionsCollection.derived = true;
2587
2618
  for(let i = 0, length = sortedItems.length; i < length; i++){
2588
2619
  const sortedItem = sortedItems[i];
2589
2620
  if (sortedItem.option.target === "database") {
@@ -3033,27 +3064,32 @@ __webpack_require__.d(__webpack_exports__, {
3033
3064
  Query: () => (/* reexport */ Query),
3034
3065
  splitSendableOptions: () => (/* reexport */ splitSendableOptions),
3035
3066
  executeJoin: () => (/* reexport */ executeJoin),
3067
+ formatExplanation: () => (/* reexport */ formatExplanation),
3036
3068
  serializePersistResult: () => (/* reexport */ serializePersistResult),
3069
+ explainQuery: () => (/* reexport */ explainQuery),
3070
+ cosineDistance: () => (/* reexport */ cosineDistance),
3037
3071
  RetryDbPlugin: () => (/* reexport */ RetryDbPlugin),
3038
- nearestBy: () => (/* reexport */ nearestBy),
3039
3072
  BatchingDbPlugin: () => (/* reexport */ BatchingDbPlugin),
3040
3073
  applyInnerOptions: () => (/* reexport */ applyInnerOptions),
3041
- TranslatedSingleValue: () => (/* reexport */ TranslatedSingleValue),
3074
+ MEMORY_EXECUTION_EXPLANATIONS: () => (/* reexport */ MEMORY_EXECUTION_EXPLANATIONS),
3042
3075
  TupleTranslator: () => (/* reexport */ TupleTranslator),
3043
- cosineDistance: () => (/* reexport */ cosineDistance),
3076
+ TranslatedSingleValue: () => (/* reexport */ TranslatedSingleValue),
3044
3077
  ConcurrencyDbPlugin: () => (/* reexport */ ConcurrencyDbPlugin),
3045
3078
  TranslatedGroupValue: () => (/* reexport */ TranslatedGroupValue),
3046
3079
  deserializeBulkPersist: () => (/* reexport */ deserializeBulkPersist),
3080
+ EXECUTED_QUERIES_UNSUPPORTED: () => (/* reexport */ EXECUTED_QUERIES_UNSUPPORTED),
3047
3081
  joinInPlugin: () => (/* reexport */ joinInPlugin),
3048
- readJoinKey: () => (/* reexport */ readJoinKey),
3049
3082
  deserializePersistResult: () => (/* reexport */ deserializePersistResult),
3050
- toEntityShape: () => (/* reexport */ toEntityShape),
3083
+ nearestBy: () => (/* reexport */ nearestBy),
3084
+ readJoinKey: () => (/* reexport */ readJoinKey),
3051
3085
  serializeBulkPersist: () => (/* reexport */ serializeBulkPersist),
3052
3086
  hashJoin: () => (/* reexport */ hashJoin),
3053
3087
  EphemeralDataPlugin: () => (/* reexport */ EphemeralDataPlugin),
3054
3088
  QueryOptionsCollection: () => (/* reexport */ QueryOptionsCollection/* .QueryOptionsCollection */.H),
3089
+ toEntityShape: () => (/* reexport */ toEntityShape),
3055
3090
  loadJoinInnerSide: () => (/* reexport */ loadJoinInnerSide),
3056
3091
  DataTranslator: () => (/* reexport */ DataTranslator),
3092
+ withExecutedQueries: () => (/* reexport */ withExecutedQueries),
3057
3093
  createRequestHandler: () => (/* reexport */ createRequestHandler),
3058
3094
  SqlTranslator: () => (/* reexport */ SqlTranslator),
3059
3095
  QueryOrdering: () => (/* reexport */ types_QueryOrdering),
@@ -3595,7 +3631,11 @@ class Query {
3595
3631
  id: `${event.id}-inner`,
3596
3632
  source: event.source,
3597
3633
  action: "query",
3598
- reason: "join inner side"
3634
+ reason: "join inner side",
3635
+ explain: event.explain,
3636
+ // The same array the outer read pushes into, so a join reports BOTH reads in execution
3637
+ // order. Built fresh rather than spread, so this has to be carried explicitly.
3638
+ executedQueries: event.executedQueries
3599
3639
  };
3600
3640
  query(innerEvent, (result)=>{
3601
3641
  if (result.ok === Result/* .PluginEventResult.ERROR */.D.ERROR) {
@@ -4295,6 +4335,386 @@ class SqlTranslator extends DataTranslator {
4295
4335
 
4296
4336
 
4297
4337
 
4338
+ ;// CONCATENATED MODULE: ./src/plugins/query/explain.ts
4339
+
4340
+ /**
4341
+ * One sentence per reason code, written for someone meeting pushdown for the first time.
4342
+ *
4343
+ * Beside the codes rather than in the formatter, so console output, a failing test and the
4344
+ * docs all say the same thing.
4345
+ */ const MEMORY_EXECUTION_EXPLANATIONS = {
4346
+ "not-parsable": "A filter could not be parsed into an expression tree, so it and every option after it run in memory.",
4347
+ "unmapped-property": "The property is not stored in the database, so it can only be read after deserialization.",
4348
+ "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.",
4349
+ "map-rename": "A map renames or drops properties, so every option after it refers to names the database does not have.",
4350
+ "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.",
4351
+ "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.",
4352
+ "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."
4353
+ };
4354
+ const EXECUTED_QUERIES_UNSUPPORTED = "This plugin did not report what it executed. It may not support explain.";
4355
+ const DATABASE_STEP_DESCRIPTION = "These options are sent to the plugin.";
4356
+ const MEMORY_STEP_DESCRIPTION = "Routier runs these over the rows the database returned, after deserializing them.";
4357
+ const UNNARROWED_READ_DESCRIPTION = "No option could be pushed down, so the plugin reads the whole collection.";
4358
+ /**
4359
+ * The reportable shape of one option's value.
4360
+ *
4361
+ * Serializable facts only, never the live selector functions — an explanation is a document a
4362
+ * caller may log, diff in a test, or send to a server, and a closure survives none of that.
4363
+ */ const detailOf = (option)=>{
4364
+ if (option.name === "filter") {
4365
+ const value = option.value;
4366
+ if (value.expression == null) {
4367
+ return undefined;
4368
+ }
4369
+ try {
4370
+ return {
4371
+ expression: types/* .Expression.toJson */.r4.toJson(value.expression)
4372
+ };
4373
+ } catch {
4374
+ // `valueToJson` rejects a value no wire can carry. Reporting the rest of the
4375
+ // explanation beats taking the diagnostic down with the query it describes.
4376
+ return {
4377
+ expressionUnavailable: "This filter holds a value that cannot be serialized."
4378
+ };
4379
+ }
4380
+ }
4381
+ if (option.name === "sort") {
4382
+ const value = option.value;
4383
+ return {
4384
+ propertyName: value.propertyName,
4385
+ direction: value.direction
4386
+ };
4387
+ }
4388
+ if (option.name === "skip" || option.name === "take") {
4389
+ return {
4390
+ value: option.value
4391
+ };
4392
+ }
4393
+ if (option.name === "nearest") {
4394
+ const value = option.value;
4395
+ return {
4396
+ propertyName: value.propertyName,
4397
+ dimensions: value.vector.length,
4398
+ count: value.count
4399
+ };
4400
+ }
4401
+ if (option.name === "join") {
4402
+ const value = option.value;
4403
+ return {
4404
+ kind: value.kind,
4405
+ outerKey: value.outerKey.propertyName,
4406
+ innerKey: value.innerKey.propertyName,
4407
+ crossPlugin: value.crossPlugin,
4408
+ innerOptions: explainedOptionsOf(value.innerOptions)
4409
+ };
4410
+ }
4411
+ if (option.name === "map" || option.name === "group") {
4412
+ const value = option.value;
4413
+ return {
4414
+ fields: value.fields.map((x)=>({
4415
+ from: x.sourceName,
4416
+ to: x.destinationName
4417
+ }))
4418
+ };
4419
+ }
4420
+ return undefined;
4421
+ };
4422
+ const explainedOptionOf = (option, index)=>{
4423
+ const detail = detailOf(option);
4424
+ return {
4425
+ index,
4426
+ name: option.name,
4427
+ ...detail == null ? {} : {
4428
+ detail
4429
+ }
4430
+ };
4431
+ };
4432
+ const explainedOptionsOf = (options)=>{
4433
+ const explained = [];
4434
+ let index = 0;
4435
+ options.forEach((option)=>explained.push(explainedOptionOf(option, index++)));
4436
+ return explained;
4437
+ };
4438
+ const summarize = (steps)=>{
4439
+ const reasons = [];
4440
+ let database = 0;
4441
+ let memory = 0;
4442
+ for (const step of steps){
4443
+ if (step.executedIn === "database") {
4444
+ database += step.options.length;
4445
+ continue;
4446
+ }
4447
+ memory += step.options.length;
4448
+ if (step.reason != null && reasons.includes(step.reason) === false) {
4449
+ reasons.push(step.reason);
4450
+ }
4451
+ }
4452
+ const counts = `${database} ${database === 1 ? "option ran" : "options ran"} in the database, ${memory} ran in memory.`;
4453
+ const causes = reasons.map((reason)=>MEMORY_EXECUTION_EXPLANATIONS[reason]).join(" ");
4454
+ return {
4455
+ database,
4456
+ memory,
4457
+ reasons,
4458
+ explanation: causes.length === 0 ? counts : `${counts} ${causes}`
4459
+ };
4460
+ };
4461
+ /**
4462
+ * Groups options into consecutive runs that execute in the same place.
4463
+ *
4464
+ * A step boundary is where execution moves, and a reader has to see the statement as step 1 OF
4465
+ * 2 to understand it is not the whole query. Cutting over to memory is a ratchet, so the
4466
+ * database options are always a prefix and there are at most two steps.
4467
+ *
4468
+ * A database step is emitted even when NO option pushed down, because the plugin is dispatched
4469
+ * either way — `createQueryPayload` always builds a database event. Without it, the worst case
4470
+ * the feature exists to expose reports "0 in the database" while the backend reads the whole
4471
+ * table, which is the opposite of the truth.
4472
+ */ const toExecutionSteps = (options)=>{
4473
+ const steps = [];
4474
+ let index = 0;
4475
+ options.forEach((option)=>{
4476
+ const explained = explainedOptionOf(option, index++);
4477
+ const current = steps[steps.length - 1];
4478
+ if (current != null && current.executedIn === option.target) {
4479
+ current.options.push(explained);
4480
+ return;
4481
+ }
4482
+ steps.push({
4483
+ step: steps.length + 1,
4484
+ of: 0,
4485
+ executedIn: option.target,
4486
+ description: option.target === "database" ? DATABASE_STEP_DESCRIPTION : MEMORY_STEP_DESCRIPTION,
4487
+ options: [
4488
+ explained
4489
+ ],
4490
+ ...option.reason == null ? {} : {
4491
+ reason: option.reason,
4492
+ explanation: MEMORY_EXECUTION_EXPLANATIONS[option.reason]
4493
+ }
4494
+ });
4495
+ });
4496
+ if (steps[0]?.executedIn !== "database") {
4497
+ steps.unshift({
4498
+ step: 0,
4499
+ of: 0,
4500
+ executedIn: "database",
4501
+ description: UNNARROWED_READ_DESCRIPTION,
4502
+ options: []
4503
+ });
4504
+ }
4505
+ for(let i = 0; i < steps.length; i++){
4506
+ steps[i].step = i + 1;
4507
+ steps[i].of = steps.length;
4508
+ }
4509
+ return steps;
4510
+ };
4511
+ /**
4512
+ * Builds the explanation from the resolved options, with no plugin involvement.
4513
+ *
4514
+ * Takes the collection BEFORE `split()`, and throws otherwise. Splitting re-adds each half
4515
+ * into a fresh collection, which re-derives targets without the options that caused them — a
4516
+ * post-join filter alone in the memory half derives back to `"database"`, and the document
4517
+ * would report memory work as having run in the database.
4518
+ */ const explainQuery = (options, context)=>{
4519
+ if (options.isDerived === true) {
4520
+ 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.");
4521
+ }
4522
+ const executionSteps = toExecutionSteps(options);
4523
+ return {
4524
+ collection: context.collection,
4525
+ database: context.database,
4526
+ summary: summarize(executionSteps),
4527
+ executionSteps,
4528
+ plugin: {
4529
+ kind: context.pluginKind
4530
+ }
4531
+ };
4532
+ };
4533
+ /**
4534
+ * Attaches what the backend reported to the step that was sent to it.
4535
+ *
4536
+ * Reporting is optional for a plugin, so an empty report is not an error: the step is marked
4537
+ * `executedQueriesUnsupported` instead, and the rest of the explanation stands — the pushdown
4538
+ * analysis comes from the options and is correct with or without the plugin's statements.
4539
+ *
4540
+ * Copies the steps rather than writing into them, so the explanation a caller already holds
4541
+ * does not gain statements after the fact. Options and their details are shared with the
4542
+ * original — nothing mutates them, and copying deeper would only look safer than it is.
4543
+ */ const withExecutedQueries = (explanation, executedQueries)=>{
4544
+ let attached = false;
4545
+ const executionSteps = explanation.executionSteps.map((step)=>{
4546
+ // Only the first database step: a plugin reports what IT ran, and everything it ran
4547
+ // was sent as one dispatch. Stamping the same statements onto a second database step
4548
+ // would claim they ran twice.
4549
+ if (step.executedIn !== "database" || attached === true) {
4550
+ return {
4551
+ ...step,
4552
+ options: [
4553
+ ...step.options
4554
+ ]
4555
+ };
4556
+ }
4557
+ attached = true;
4558
+ if (executedQueries.length === 0) {
4559
+ return {
4560
+ ...step,
4561
+ options: [
4562
+ ...step.options
4563
+ ],
4564
+ executedQueriesUnsupported: EXECUTED_QUERIES_UNSUPPORTED
4565
+ };
4566
+ }
4567
+ return {
4568
+ ...step,
4569
+ options: [
4570
+ ...step.options
4571
+ ],
4572
+ executedQueries: [
4573
+ ...executedQueries
4574
+ ]
4575
+ };
4576
+ });
4577
+ return {
4578
+ ...explanation,
4579
+ executionSteps
4580
+ };
4581
+ };
4582
+
4583
+ ;// CONCATENATED MODULE: ./src/plugins/query/formatExplanation.ts
4584
+ const OPTION_LABEL_WIDTH = 8;
4585
+ const WRAP_WIDTH = 68;
4586
+ /** Wraps `text` to `WRAP_WIDTH`, prefixing every line with `indent`. */ const wrap = (text, indent)=>{
4587
+ const lines = [];
4588
+ let line = "";
4589
+ for (const word of text.split(" ")){
4590
+ if (line.length > 0 && line.length + word.length + 1 > WRAP_WIDTH) {
4591
+ lines.push(indent + line);
4592
+ line = word;
4593
+ continue;
4594
+ }
4595
+ line = line.length === 0 ? word : `${line} ${word}`;
4596
+ }
4597
+ if (line.length > 0) {
4598
+ lines.push(indent + line);
4599
+ }
4600
+ return lines;
4601
+ };
4602
+ const COMPARATOR_SYMBOLS = {
4603
+ "equals": "===",
4604
+ "greater-than": ">",
4605
+ "greater-than-equals": ">=",
4606
+ "less-than": "<",
4607
+ "less-than-equals": "<="
4608
+ };
4609
+ const describeValue = (value)=>{
4610
+ if (value == null) {
4611
+ return "?";
4612
+ }
4613
+ if (value.k === "raw") {
4614
+ return typeof value.v === "string" ? `"${value.v}"` : String(value.v);
4615
+ }
4616
+ if (value.k === "date") {
4617
+ return value.v;
4618
+ }
4619
+ if (value.k === "array") {
4620
+ return `[${value.v.map(describeValue).join(", ")}]`;
4621
+ }
4622
+ return value.k === "undefined" ? "undefined" : String(value.v);
4623
+ };
4624
+ /** Renders a serialized expression back to something close to the source predicate. */ const describeExpression = (expression)=>{
4625
+ if (expression == null) {
4626
+ return "?";
4627
+ }
4628
+ if (expression.t === "operator") {
4629
+ return `${describeExpression(expression.left)} ${expression.operator} ${describeExpression(expression.right)}`;
4630
+ }
4631
+ if (expression.t === "comparator") {
4632
+ const left = describeExpression(expression.left);
4633
+ const right = describeExpression(expression.right);
4634
+ const symbol = COMPARATOR_SYMBOLS[expression.comparator];
4635
+ if (symbol == null) {
4636
+ return `${left}.${expression.comparator}(${right})${expression.negated === true ? " === false" : ""}`;
4637
+ }
4638
+ return `${left} ${expression.negated === true ? "!==" : symbol} ${right}`;
4639
+ }
4640
+ if (expression.t === "property") {
4641
+ return expression.path;
4642
+ }
4643
+ if (expression.t === "value") {
4644
+ return describeValue(expression.value);
4645
+ }
4646
+ return expression.t === "empty" ? "(no filter)" : "(not parsable)";
4647
+ };
4648
+ const describeOption = (option)=>{
4649
+ const detail = option.detail;
4650
+ if (detail == null) {
4651
+ return "";
4652
+ }
4653
+ if (option.name === "filter") {
4654
+ return detail.expression == null ? String(detail.expressionUnavailable ?? "") : describeExpression(detail.expression);
4655
+ }
4656
+ if (option.name === "sort") {
4657
+ return `${detail.propertyName} ${detail.direction}`;
4658
+ }
4659
+ if (option.name === "skip" || option.name === "take") {
4660
+ return String(detail.value);
4661
+ }
4662
+ if (option.name === "join") {
4663
+ return `${detail.kind} → ${detail.outerKey} = ${detail.innerKey}`;
4664
+ }
4665
+ if (option.name === "nearest") {
4666
+ return `${detail.propertyName}, ${detail.count} nearest`;
4667
+ }
4668
+ if (option.name === "map" || option.name === "group") {
4669
+ const fields = detail.fields;
4670
+ return fields.map((x)=>x.from === x.to ? x.from : `${x.from} → ${x.to}`).join(", ");
4671
+ }
4672
+ return "";
4673
+ };
4674
+ const formatStep = (step, lines)=>{
4675
+ const reason = step.reason == null ? "" : ` [${step.reason}]`;
4676
+ lines.push(` STEP ${step.step} of ${step.of} — ${step.executedIn}${reason}`);
4677
+ lines.push(...wrap(step.description, " "));
4678
+ if (step.explanation != null) {
4679
+ lines.push(...wrap(step.explanation, " "));
4680
+ }
4681
+ lines.push("");
4682
+ for (const option of step.options){
4683
+ lines.push(` ${option.name.padEnd(OPTION_LABEL_WIDTH)} ${describeOption(option)}`.trimEnd());
4684
+ }
4685
+ for (const executed of step.executedQueries ?? []){
4686
+ lines.push("");
4687
+ lines.push(...executed.text.split("\n").map((line)=>` ${line}`));
4688
+ if (executed.parameters != null && executed.parameters.length > 0) {
4689
+ lines.push(` parameters: ${JSON.stringify(executed.parameters)}`);
4690
+ }
4691
+ }
4692
+ if (step.executedQueriesUnsupported != null) {
4693
+ lines.push("");
4694
+ lines.push(...wrap(step.executedQueriesUnsupported, " "));
4695
+ }
4696
+ lines.push("");
4697
+ };
4698
+ /**
4699
+ * Renders an explanation for a terminal.
4700
+ *
4701
+ * The STEP headers carry the whole lesson: a reader who has never heard of pushdown still sees
4702
+ * that the statement in step 1 is not the entire query. Nobody should have to notice a missing
4703
+ * ORDER BY to work that out.
4704
+ */ const formatExplanation = (explanation)=>{
4705
+ const { collection, database, summary, executionSteps } = explanation;
4706
+ const stepCount = `${executionSteps.length} ${executionSteps.length === 1 ? "step" : "steps"}`;
4707
+ const lines = [
4708
+ `${collection} · ${database} · ${stepCount}`,
4709
+ ""
4710
+ ];
4711
+ for (const step of executionSteps){
4712
+ formatStep(step, lines);
4713
+ }
4714
+ lines.push(...wrap(summary.explanation, " "));
4715
+ return lines.join("\n");
4716
+ };
4717
+
4298
4718
  ;// CONCATENATED MODULE: ./src/plugins/query/types.ts
4299
4719
  var types_QueryOrdering = /*#__PURE__*/ function(QueryOrdering) {
4300
4720
  QueryOrdering["Descending"] = "desc";
@@ -4309,6 +4729,8 @@ var types_QueryOrdering = /*#__PURE__*/ function(QueryOrdering) {
4309
4729
 
4310
4730
 
4311
4731
 
4732
+
4733
+
4312
4734
  // EXTERNAL MODULE: ./src/expressions/evaluate.ts
4313
4735
  var evaluate = __webpack_require__(379);
4314
4736
  ;// CONCATENATED MODULE: ./src/plugins/wire/query.ts
@@ -4780,6 +5202,7 @@ const createRequestHandler = (options)=>{
4780
5202
  const queryOptions = deserializeQueryOptions(request.options, schema, resolveSchema, // Applied to the outer collection AND to every collection a join reaches, so a
4781
5203
  // join cannot be used to read around a scope
4782
5204
  (target)=>scopeExpressionFor(target, context, "query"));
5205
+ const executedQueries = [];
4783
5206
  return await new Promise((resolve)=>{
4784
5207
  plugin.query({
4785
5208
  // `false`: nothing here attaches to a change tracker — the tracker lives on
@@ -4788,7 +5211,9 @@ const createRequestHandler = (options)=>{
4788
5211
  schemas: schemas,
4789
5212
  id: (0,uuid/* .uuid */.u)(8),
4790
5213
  source: "RequestHandler",
4791
- action: "query"
5214
+ action: "query",
5215
+ explain: request.explain,
5216
+ executedQueries
4792
5217
  }, (result)=>{
4793
5218
  if (result.ok === Result/* .PluginEventResult.ERROR */.D.ERROR) {
4794
5219
  resolve(failed(result.error));
@@ -4797,7 +5222,13 @@ const createRequestHandler = (options)=>{
4797
5222
  resolve({
4798
5223
  ok: true,
4799
5224
  kind: "query",
4800
- value: result.data.value
5225
+ value: result.data.value,
5226
+ // Only when asked, and only what the plugin reported. A plugin
5227
+ // that reported nothing sends nothing, and the caller marks the
5228
+ // remote step as not reported.
5229
+ ...request.explain === true && executedQueries.length > 0 ? {
5230
+ executedQueries
5231
+ } : {}
4801
5232
  });
4802
5233
  });
4803
5234
  });
@@ -5446,6 +5877,10 @@ class EphemeralDataPlugin {
5446
5877
  }
5447
5878
  innerRows.push(cloneRecord(record));
5448
5879
  }
5880
+ const narrowing = outerKeys == null ? "full scan" : `narrowed by ${outerKeys.size} outer ${outerKeys.size === 1 ? "key" : "keys"}`;
5881
+ event.executedQueries.push({
5882
+ text: `${innerSchema.collectionName}: scanned ${innerRows.length} in-memory ${innerRows.length === 1 ? "record" : "records"} for join inner side (${narrowing})`
5883
+ });
5449
5884
  done({
5450
5885
  ok: "success",
5451
5886
  innerSide: {
@@ -5555,7 +5990,13 @@ class EphemeralDataPlugin {
5555
5990
  * collection to pair it with three rows.
5556
5991
  *
5557
5992
  * `cloned` is in storage shape, so the keys are read by resolved column name.
5558
- */ const joinOption = operation.options.getLast("join");
5993
+ */ // No statement to quote — an ephemeral store walks its own records. Said
5994
+ // plainly so `.explain()` does not leave a reader wondering whether the
5995
+ // plugin simply failed to report. Before the inner side, to match execution order.
5996
+ event.executedQueries.push({
5997
+ text: `${operation.schema.collectionName}: scanned ${cloned.length} in-memory ${cloned.length === 1 ? "record" : "records"}`
5998
+ });
5999
+ const joinOption = operation.options.getLast("join");
5559
6000
  const outerKeys = joinOption == null ? null : distinctJoinKeys(cloned, joinOption.value.outerKey, joinOption.value.semiJoinKeyThreshold, {
5560
6001
  storageShape: true
5561
6002
  });
@@ -5648,7 +6089,7 @@ class RetryDbPlugin {
5648
6089
  * `PropertyInfo` objects carrying functions and would not survive `JSON.stringify`. A filter is
5649
6090
  * identified by its source text plus its params, which is what the expression is derived from
5650
6091
  * anyway — two queries with the same source and params are the same query.
5651
- */ const describeOption = (option)=>{
6092
+ */ const CacheDbPlugin_describeOption = (option)=>{
5652
6093
  const value = option.value;
5653
6094
  switch(option.name){
5654
6095
  case "filter":
@@ -5682,7 +6123,7 @@ class CacheDbPlugin {
5682
6123
  /** `schemaId` first, so invalidating a schema is a prefix match. */ keyFor(event) {
5683
6124
  const parts = [];
5684
6125
  event.operation.options.forEach((option)=>{
5685
- parts.push(`${option.name}:${describeOption(option)}`);
6126
+ parts.push(`${option.name}:${CacheDbPlugin_describeOption(option)}`);
5686
6127
  });
5687
6128
  return `${String(event.operation.schema.id)}\u0000${parts.join("\u0001")}`;
5688
6129
  }
@@ -5712,6 +6153,12 @@ class CacheDbPlugin {
5712
6153
  // Re-set to move it to the end of the insertion order: most recently used.
5713
6154
  this.entries.delete(key);
5714
6155
  this.entries.set(key, cached);
6156
+ // Said rather than left blank. A hit means no database was touched, which is a fact
6157
+ // worth reporting — and an empty report would otherwise read as a plugin that failed
6158
+ // to say what it ran.
6159
+ event.executedQueries.push({
6160
+ text: "cache hit — no query was executed"
6161
+ });
5715
6162
  done(Result/* .PluginEventResult.success */.D.success(event.id, this.rebuild(cached)));
5716
6163
  return;
5717
6164
  }