1use crate::{
7 db::{
8 predicate::{CoercionId, CompareOp, MissingRowPolicy, Predicate},
9 query::{
10 builder::aggregate::AggregateExpr,
11 explain::{
12 ExplainAccessPath, ExplainExecutionNodeDescriptor, ExplainExecutionNodeType,
13 ExplainOrderPushdown, ExplainPlan, ExplainPredicate,
14 },
15 expr::{FilterExpr, SortExpr},
16 intent::{QueryError, access_plan_to_entity_keys, model::QueryModel},
17 plan::{AccessPlannedQuery, LoadSpec, QueryMode},
18 },
19 },
20 traits::{EntityKind, EntityValue, SingletonEntity},
21 value::Value,
22};
23
24#[derive(Debug)]
36pub struct Query<E: EntityKind> {
37 intent: QueryModel<'static, E::Key>,
38}
39
40impl<E: EntityKind> Query<E> {
41 #[must_use]
45 pub const fn new(consistency: MissingRowPolicy) -> Self {
46 Self {
47 intent: QueryModel::new(E::MODEL, consistency),
48 }
49 }
50
51 #[must_use]
53 pub const fn mode(&self) -> QueryMode {
54 self.intent.mode()
55 }
56
57 #[must_use]
58 pub(crate) fn has_explicit_order(&self) -> bool {
59 self.intent.has_explicit_order()
60 }
61
62 #[must_use]
63 pub(crate) const fn has_grouping(&self) -> bool {
64 self.intent.has_grouping()
65 }
66
67 #[must_use]
68 pub(crate) const fn load_spec(&self) -> Option<LoadSpec> {
69 match self.intent.mode() {
70 QueryMode::Load(spec) => Some(spec),
71 QueryMode::Delete(_) => None,
72 }
73 }
74
75 #[must_use]
77 pub fn filter(mut self, predicate: Predicate) -> Self {
78 self.intent = self.intent.filter(predicate);
79 self
80 }
81
82 pub fn filter_expr(self, expr: FilterExpr) -> Result<Self, QueryError> {
84 let Self { intent } = self;
85 let intent = intent.filter_expr(expr)?;
86
87 Ok(Self { intent })
88 }
89
90 pub fn sort_expr(self, expr: SortExpr) -> Result<Self, QueryError> {
92 let Self { intent } = self;
93 let intent = intent.sort_expr(expr)?;
94
95 Ok(Self { intent })
96 }
97
98 #[must_use]
100 pub fn order_by(mut self, field: impl AsRef<str>) -> Self {
101 self.intent = self.intent.order_by(field);
102 self
103 }
104
105 #[must_use]
107 pub fn order_by_desc(mut self, field: impl AsRef<str>) -> Self {
108 self.intent = self.intent.order_by_desc(field);
109 self
110 }
111
112 #[must_use]
114 pub fn distinct(mut self) -> Self {
115 self.intent = self.intent.distinct();
116 self
117 }
118
119 pub fn group_by(self, field: impl AsRef<str>) -> Result<Self, QueryError> {
121 let Self { intent } = self;
122 let intent = intent.push_group_field(field.as_ref())?;
123
124 Ok(Self { intent })
125 }
126
127 #[must_use]
129 pub fn aggregate(mut self, aggregate: AggregateExpr) -> Self {
130 self.intent = self.intent.push_group_aggregate(aggregate);
131 self
132 }
133
134 #[must_use]
136 pub fn grouped_limits(mut self, max_groups: u64, max_group_bytes: u64) -> Self {
137 self.intent = self.intent.grouped_limits(max_groups, max_group_bytes);
138 self
139 }
140
141 pub fn having_group(
143 self,
144 field: impl AsRef<str>,
145 op: CompareOp,
146 value: Value,
147 ) -> Result<Self, QueryError> {
148 let field = field.as_ref().to_owned();
149 let Self { intent } = self;
150 let intent = intent.push_having_group_clause(&field, op, value)?;
151
152 Ok(Self { intent })
153 }
154
155 pub fn having_aggregate(
157 self,
158 aggregate_index: usize,
159 op: CompareOp,
160 value: Value,
161 ) -> Result<Self, QueryError> {
162 let Self { intent } = self;
163 let intent = intent.push_having_aggregate_clause(aggregate_index, op, value)?;
164
165 Ok(Self { intent })
166 }
167
168 pub(crate) fn by_id(self, id: E::Key) -> Self {
170 let Self { intent } = self;
171 Self {
172 intent: intent.by_id(id),
173 }
174 }
175
176 pub(crate) fn by_ids<I>(self, ids: I) -> Self
178 where
179 I: IntoIterator<Item = E::Key>,
180 {
181 let Self { intent } = self;
182 Self {
183 intent: intent.by_ids(ids),
184 }
185 }
186
187 #[must_use]
189 pub fn delete(mut self) -> Self {
190 self.intent = self.intent.delete();
191 self
192 }
193
194 #[must_use]
201 pub fn limit(mut self, limit: u32) -> Self {
202 self.intent = self.intent.limit(limit);
203 self
204 }
205
206 #[must_use]
212 pub fn offset(mut self, offset: u32) -> Self {
213 self.intent = self.intent.offset(offset);
214 self
215 }
216
217 pub fn explain(&self) -> Result<ExplainPlan, QueryError> {
219 let plan = self.planned()?;
220
221 Ok(plan.explain())
222 }
223
224 pub fn plan_hash_hex(&self) -> Result<String, QueryError> {
229 let plan = self.build_plan()?;
230
231 Ok(plan.fingerprint().to_string())
232 }
233
234 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError>
236 where
237 E: EntityValue,
238 {
239 let executable = self.plan()?.into_executable();
240
241 executable
242 .explain_load_execution_node_descriptor()
243 .map_err(QueryError::execute)
244 }
245
246 pub fn explain_execution_text(&self) -> Result<String, QueryError>
248 where
249 E: EntityValue,
250 {
251 Ok(self.explain_execution()?.render_text_tree())
252 }
253
254 pub fn explain_execution_json(&self) -> Result<String, QueryError>
256 where
257 E: EntityValue,
258 {
259 Ok(self.explain_execution()?.render_json_canonical())
260 }
261
262 pub fn explain_execution_verbose(&self) -> Result<String, QueryError>
264 where
265 E: EntityValue,
266 {
267 let executable = self.plan()?.into_executable();
268 let descriptor = executable
269 .explain_load_execution_node_descriptor()
270 .map_err(QueryError::execute)?;
271 let route_diagnostics = executable
272 .explain_load_execution_verbose_diagnostics()
273 .map_err(QueryError::execute)?;
274 let explain = self.explain()?;
275
276 let mut lines = vec![descriptor.render_text_tree_verbose()];
278 lines.extend(route_diagnostics);
279
280 lines.push(format!(
282 "diagnostic.descriptor.has_top_n_seek={}",
283 contains_execution_node_type(&descriptor, ExplainExecutionNodeType::TopNSeek)
284 ));
285 lines.push(format!(
286 "diagnostic.descriptor.has_index_range_limit_pushdown={}",
287 contains_execution_node_type(
288 &descriptor,
289 ExplainExecutionNodeType::IndexRangeLimitPushdown,
290 )
291 ));
292 lines.push(format!(
293 "diagnostic.descriptor.has_index_predicate_prefilter={}",
294 contains_execution_node_type(
295 &descriptor,
296 ExplainExecutionNodeType::IndexPredicatePrefilter,
297 )
298 ));
299 lines.push(format!(
300 "diagnostic.descriptor.has_residual_predicate_filter={}",
301 contains_execution_node_type(
302 &descriptor,
303 ExplainExecutionNodeType::ResidualPredicateFilter,
304 )
305 ));
306
307 lines.push(format!("diagnostic.plan.mode={:?}", explain.mode()));
309 lines.push(format!(
310 "diagnostic.plan.order_pushdown={}",
311 plan_order_pushdown_label(explain.order_pushdown())
312 ));
313 lines.push(format!(
314 "diagnostic.plan.predicate_pushdown={}",
315 plan_predicate_pushdown_label(explain.predicate(), explain.access())
316 ));
317 lines.push(format!("diagnostic.plan.distinct={}", explain.distinct()));
318 lines.push(format!("diagnostic.plan.page={:?}", explain.page()));
319 lines.push(format!(
320 "diagnostic.plan.consistency={:?}",
321 explain.consistency()
322 ));
323
324 Ok(lines.join("\n"))
325 }
326
327 pub fn planned(&self) -> Result<PlannedQuery<E>, QueryError> {
329 let plan = self.build_plan()?;
330 let _projection = plan.projection_spec(E::MODEL);
331
332 Ok(PlannedQuery::new(plan))
333 }
334
335 pub fn plan(&self) -> Result<CompiledQuery<E>, QueryError> {
339 let plan = self.build_plan()?;
340 let _projection = plan.projection_spec(E::MODEL);
341
342 Ok(CompiledQuery::new(plan))
343 }
344
345 fn build_plan(&self) -> Result<AccessPlannedQuery<E::Key>, QueryError> {
347 let plan_value = self.intent.build_plan_model()?;
348 let (logical, access) = plan_value.into_parts();
349 let access = access_plan_to_entity_keys::<E>(E::MODEL, access)?;
350 let plan = AccessPlannedQuery::from_parts(logical, access);
351
352 Ok(plan)
353 }
354}
355
356fn contains_execution_node_type(
357 descriptor: &ExplainExecutionNodeDescriptor,
358 target: ExplainExecutionNodeType,
359) -> bool {
360 descriptor.node_type() == target
361 || descriptor
362 .children()
363 .iter()
364 .any(|child| contains_execution_node_type(child, target))
365}
366
367fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
368 match order_pushdown {
369 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
370 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
371 format!("eligible(index={index},prefix_len={prefix_len})",)
372 }
373 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
374 }
375}
376
377fn plan_predicate_pushdown_label(
378 predicate: &ExplainPredicate,
379 access: &ExplainAccessPath,
380) -> String {
381 let access_label = match access {
382 ExplainAccessPath::ByKey { .. } => "by_key",
383 ExplainAccessPath::ByKeys { keys } if keys.is_empty() => "empty_access_contract",
384 ExplainAccessPath::ByKeys { .. } => "by_keys",
385 ExplainAccessPath::KeyRange { .. } => "key_range",
386 ExplainAccessPath::IndexPrefix { .. } => "index_prefix",
387 ExplainAccessPath::IndexMultiLookup { .. } => "index_multi_lookup",
388 ExplainAccessPath::IndexRange { .. } => "index_range",
389 ExplainAccessPath::FullScan => "full_scan",
390 ExplainAccessPath::Union(_) => "union",
391 ExplainAccessPath::Intersection(_) => "intersection",
392 };
393 if matches!(predicate, ExplainPredicate::None) {
394 return "none".to_string();
395 }
396 if matches!(access, ExplainAccessPath::FullScan) {
397 if explain_predicate_contains_non_strict_compare(predicate) {
398 return "fallback(non_strict_compare_coercion)".to_string();
399 }
400 if explain_predicate_contains_empty_prefix_starts_with(predicate) {
401 return "fallback(starts_with_empty_prefix)".to_string();
402 }
403 if explain_predicate_contains_is_null(predicate) {
404 return "fallback(is_null_full_scan)".to_string();
405 }
406 if explain_predicate_contains_text_scan_operator(predicate) {
407 return "fallback(text_operator_full_scan)".to_string();
408 }
409
410 return format!("fallback({access_label})");
411 }
412
413 format!("applied({access_label})")
414}
415
416fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
417 match predicate {
418 ExplainPredicate::Compare { coercion, .. } => coercion.id != CoercionId::Strict,
419 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
420 .iter()
421 .any(explain_predicate_contains_non_strict_compare),
422 ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
423 ExplainPredicate::None
424 | ExplainPredicate::True
425 | ExplainPredicate::False
426 | ExplainPredicate::IsNull { .. }
427 | ExplainPredicate::IsMissing { .. }
428 | ExplainPredicate::IsEmpty { .. }
429 | ExplainPredicate::IsNotEmpty { .. }
430 | ExplainPredicate::TextContains { .. }
431 | ExplainPredicate::TextContainsCi { .. } => false,
432 }
433}
434
435fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
436 match predicate {
437 ExplainPredicate::IsNull { .. } => true,
438 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
439 children.iter().any(explain_predicate_contains_is_null)
440 }
441 ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
442 ExplainPredicate::None
443 | ExplainPredicate::True
444 | ExplainPredicate::False
445 | ExplainPredicate::Compare { .. }
446 | ExplainPredicate::IsMissing { .. }
447 | ExplainPredicate::IsEmpty { .. }
448 | ExplainPredicate::IsNotEmpty { .. }
449 | ExplainPredicate::TextContains { .. }
450 | ExplainPredicate::TextContainsCi { .. } => false,
451 }
452}
453
454fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
455 match predicate {
456 ExplainPredicate::Compare {
457 op: CompareOp::StartsWith,
458 value: Value::Text(prefix),
459 ..
460 } => prefix.is_empty(),
461 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
462 .iter()
463 .any(explain_predicate_contains_empty_prefix_starts_with),
464 ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
465 ExplainPredicate::None
466 | ExplainPredicate::True
467 | ExplainPredicate::False
468 | ExplainPredicate::Compare { .. }
469 | ExplainPredicate::IsNull { .. }
470 | ExplainPredicate::IsMissing { .. }
471 | ExplainPredicate::IsEmpty { .. }
472 | ExplainPredicate::IsNotEmpty { .. }
473 | ExplainPredicate::TextContains { .. }
474 | ExplainPredicate::TextContainsCi { .. } => false,
475 }
476}
477
478fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
479 match predicate {
480 ExplainPredicate::Compare {
481 op: CompareOp::EndsWith,
482 ..
483 }
484 | ExplainPredicate::TextContains { .. }
485 | ExplainPredicate::TextContainsCi { .. } => true,
486 ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
487 .iter()
488 .any(explain_predicate_contains_text_scan_operator),
489 ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
490 ExplainPredicate::Compare { .. }
491 | ExplainPredicate::None
492 | ExplainPredicate::True
493 | ExplainPredicate::False
494 | ExplainPredicate::IsNull { .. }
495 | ExplainPredicate::IsMissing { .. }
496 | ExplainPredicate::IsEmpty { .. }
497 | ExplainPredicate::IsNotEmpty { .. } => false,
498 }
499}
500
501impl<E> Query<E>
502where
503 E: EntityKind + SingletonEntity,
504 E::Key: Default,
505{
506 pub(crate) fn only(self) -> Self {
508 let Self { intent } = self;
509
510 Self {
511 intent: intent.only(E::Key::default()),
512 }
513 }
514}
515
516#[derive(Debug)]
524pub struct PlannedQuery<E: EntityKind> {
525 plan: AccessPlannedQuery<E::Key>,
526}
527
528impl<E: EntityKind> PlannedQuery<E> {
529 #[must_use]
530 pub(in crate::db) const fn new(plan: AccessPlannedQuery<E::Key>) -> Self {
531 Self { plan }
532 }
533
534 #[must_use]
535 pub fn explain(&self) -> ExplainPlan {
536 self.plan.explain_with_model(E::MODEL)
537 }
538
539 #[must_use]
541 pub fn plan_hash_hex(&self) -> String {
542 self.plan.fingerprint().to_string()
543 }
544}
545
546#[derive(Clone, Debug)]
555pub struct CompiledQuery<E: EntityKind> {
556 plan: AccessPlannedQuery<E::Key>,
557}
558
559impl<E: EntityKind> CompiledQuery<E> {
560 #[must_use]
561 pub(in crate::db) const fn new(plan: AccessPlannedQuery<E::Key>) -> Self {
562 Self { plan }
563 }
564
565 #[must_use]
566 pub fn explain(&self) -> ExplainPlan {
567 self.plan.explain_with_model(E::MODEL)
568 }
569
570 #[must_use]
572 pub fn plan_hash_hex(&self) -> String {
573 self.plan.fingerprint().to_string()
574 }
575
576 #[must_use]
578 #[cfg(test)]
579 pub(crate) fn projection_spec(&self) -> crate::db::query::plan::expr::ProjectionSpec {
580 self.plan.projection_spec(E::MODEL)
581 }
582
583 #[must_use]
584 pub(in crate::db) fn into_inner(self) -> AccessPlannedQuery<E::Key> {
585 self.plan
586 }
587}
588
589#[cfg(test)]
594mod tests {
595 use super::*;
596 use crate::{db::predicate::CoercionSpec, types::Ulid};
597
598 fn strict_compare(field: &str, op: CompareOp, value: Value) -> ExplainPredicate {
599 ExplainPredicate::Compare {
600 field: field.to_string(),
601 op,
602 value,
603 coercion: CoercionSpec::new(CoercionId::Strict),
604 }
605 }
606
607 #[test]
608 fn predicate_pushdown_label_prefix_like_and_equivalent_range_share_label() {
609 let starts_with_predicate = strict_compare(
610 "name",
611 CompareOp::StartsWith,
612 Value::Text("foo".to_string()),
613 );
614 let equivalent_range_predicate = ExplainPredicate::And(vec![
615 strict_compare("name", CompareOp::Gte, Value::Text("foo".to_string())),
616 strict_compare("name", CompareOp::Lt, Value::Text("fop".to_string())),
617 ]);
618 let access = ExplainAccessPath::IndexRange {
619 name: "idx_name",
620 fields: vec!["name"],
621 prefix_len: 0,
622 prefix: Vec::new(),
623 lower: std::ops::Bound::Included(Value::Text("foo".to_string())),
624 upper: std::ops::Bound::Excluded(Value::Text("fop".to_string())),
625 };
626
627 assert_eq!(
628 plan_predicate_pushdown_label(&starts_with_predicate, &access),
629 plan_predicate_pushdown_label(&equivalent_range_predicate, &access),
630 "equivalent prefix-like and bounded-range shapes should report identical pushdown reason labels",
631 );
632 assert_eq!(
633 plan_predicate_pushdown_label(&starts_with_predicate, &access),
634 "applied(index_range)"
635 );
636 }
637
638 #[test]
639 fn predicate_pushdown_label_distinguishes_is_null_and_non_strict_full_scan_fallbacks() {
640 let is_null_predicate = ExplainPredicate::IsNull {
641 field: "group".to_string(),
642 };
643 let non_strict_predicate = ExplainPredicate::Compare {
644 field: "group".to_string(),
645 op: CompareOp::Eq,
646 value: Value::Uint(7),
647 coercion: CoercionSpec::new(CoercionId::NumericWiden),
648 };
649 let access = ExplainAccessPath::FullScan;
650
651 assert_eq!(
652 plan_predicate_pushdown_label(&is_null_predicate, &access),
653 "fallback(is_null_full_scan)"
654 );
655 assert_eq!(
656 plan_predicate_pushdown_label(&non_strict_predicate, &access),
657 "fallback(non_strict_compare_coercion)"
658 );
659 }
660
661 #[test]
662 fn predicate_pushdown_label_reports_none_when_no_predicate_is_present() {
663 let predicate = ExplainPredicate::None;
664 let access = ExplainAccessPath::ByKey {
665 key: Value::Ulid(Ulid::from_u128(7)),
666 };
667
668 assert_eq!(plan_predicate_pushdown_label(&predicate, &access), "none");
669 }
670
671 #[test]
672 fn predicate_pushdown_label_reports_empty_access_contract_for_impossible_shapes() {
673 let predicate = ExplainPredicate::Or(vec![
674 ExplainPredicate::IsNull {
675 field: "id".to_string(),
676 },
677 ExplainPredicate::And(vec![
678 ExplainPredicate::Compare {
679 field: "id".to_string(),
680 op: CompareOp::In,
681 value: Value::List(Vec::new()),
682 coercion: CoercionSpec::new(CoercionId::Strict),
683 },
684 ExplainPredicate::True,
685 ]),
686 ]);
687 let access = ExplainAccessPath::ByKeys { keys: Vec::new() };
688
689 assert_eq!(
690 plan_predicate_pushdown_label(&predicate, &access),
691 "applied(empty_access_contract)"
692 );
693 }
694
695 #[test]
696 fn predicate_pushdown_label_distinguishes_empty_prefix_starts_with_full_scan_fallback() {
697 let empty_prefix_predicate = ExplainPredicate::Compare {
698 field: "label".to_string(),
699 op: CompareOp::StartsWith,
700 value: Value::Text(String::new()),
701 coercion: CoercionSpec::new(CoercionId::Strict),
702 };
703 let non_empty_prefix_predicate = ExplainPredicate::Compare {
704 field: "label".to_string(),
705 op: CompareOp::StartsWith,
706 value: Value::Text("l".to_string()),
707 coercion: CoercionSpec::new(CoercionId::Strict),
708 };
709 let access = ExplainAccessPath::FullScan;
710
711 assert_eq!(
712 plan_predicate_pushdown_label(&empty_prefix_predicate, &access),
713 "fallback(starts_with_empty_prefix)"
714 );
715 assert_eq!(
716 plan_predicate_pushdown_label(&non_empty_prefix_predicate, &access),
717 "fallback(full_scan)"
718 );
719 }
720
721 #[test]
722 fn predicate_pushdown_label_reports_text_operator_full_scan_fallback() {
723 let text_contains = ExplainPredicate::TextContainsCi {
724 field: "label".to_string(),
725 value: Value::Text("needle".to_string()),
726 };
727 let ends_with = ExplainPredicate::Compare {
728 field: "label".to_string(),
729 op: CompareOp::EndsWith,
730 value: Value::Text("fix".to_string()),
731 coercion: CoercionSpec::new(CoercionId::Strict),
732 };
733 let access = ExplainAccessPath::FullScan;
734
735 assert_eq!(
736 plan_predicate_pushdown_label(&text_contains, &access),
737 "fallback(text_operator_full_scan)"
738 );
739 assert_eq!(
740 plan_predicate_pushdown_label(&ends_with, &access),
741 "fallback(text_operator_full_scan)"
742 );
743 }
744
745 #[test]
746 fn predicate_pushdown_label_keeps_collection_contains_on_generic_full_scan_fallback() {
747 let collection_contains = ExplainPredicate::Compare {
748 field: "tags".to_string(),
749 op: CompareOp::Contains,
750 value: Value::Uint(7),
751 coercion: CoercionSpec::new(CoercionId::CollectionElement),
752 };
753 let access = ExplainAccessPath::FullScan;
754
755 assert_eq!(
756 plan_predicate_pushdown_label(&collection_contains, &access),
757 "fallback(non_strict_compare_coercion)"
758 );
759 assert_ne!(
760 plan_predicate_pushdown_label(&collection_contains, &access),
761 "fallback(text_operator_full_scan)"
762 );
763 }
764
765 #[test]
766 fn predicate_pushdown_label_non_strict_ends_with_uses_non_strict_fallback_precedence() {
767 let non_strict_ends_with = ExplainPredicate::Compare {
768 field: "label".to_string(),
769 op: CompareOp::EndsWith,
770 value: Value::Text("fix".to_string()),
771 coercion: CoercionSpec::new(CoercionId::TextCasefold),
772 };
773 let access = ExplainAccessPath::FullScan;
774
775 assert_eq!(
776 plan_predicate_pushdown_label(&non_strict_ends_with, &access),
777 "fallback(non_strict_compare_coercion)"
778 );
779 assert_ne!(
780 plan_predicate_pushdown_label(&non_strict_ends_with, &access),
781 "fallback(text_operator_full_scan)"
782 );
783 }
784}