1use crate::{
7 db::{
8 access::{AccessPlan, ExecutableAccessPlan},
9 predicate::{IndexCompileTarget, MissingRowPolicy, Predicate, PredicateProgram},
10 query::plan::{
11 AccessPlannedQuery, ContinuationPolicy, DistinctExecutionStrategy,
12 EffectiveRuntimeFilterProgram, ExecutionShapeSignature, GroupPlan,
13 GroupedAggregateExecutionSpec, GroupedDistinctExecutionStrategy, GroupedPlanStrategy,
14 LogicalPlan, PlannerRouteProfile, QueryMode, ResolvedOrder, ResolvedOrderField,
15 ResolvedOrderValueSource, ScalarPlan, StaticPlanningShape,
16 derive_logical_pushdown_eligibility,
17 expr::{
18 CompiledExpr, Expr, ProjectionSpec, compile_scalar_projection_expr_with_schema,
19 compile_scalar_projection_plan_with_schema,
20 },
21 grouped_aggregate_execution_specs, grouped_aggregate_specs_from_projection_spec,
22 grouped_cursor_policy_violation, grouped_plan_strategy,
23 lower_data_row_direct_projection_slots_with_schema,
24 lower_direct_projection_slots_with_schema, lower_projection_identity,
25 lower_projection_intent, residual_query_predicate_after_access_path_bounds,
26 residual_query_predicate_after_filtered_access,
27 resolved_grouped_distinct_execution_strategy_for_model,
28 },
29 schema::SchemaInfo,
30 },
31 error::InternalError,
32 model::{entity::EntityModel, index::IndexKeyItemsRef},
33};
34
35impl QueryMode {
36 #[must_use]
38 pub const fn is_load(&self) -> bool {
39 match self {
40 Self::Load(_) => true,
41 Self::Delete(_) => false,
42 }
43 }
44
45 #[must_use]
47 pub const fn is_delete(&self) -> bool {
48 match self {
49 Self::Delete(_) => true,
50 Self::Load(_) => false,
51 }
52 }
53}
54
55impl LogicalPlan {
56 #[must_use]
58 pub(in crate::db) const fn scalar_semantics(&self) -> &ScalarPlan {
59 match self {
60 Self::Scalar(plan) => plan,
61 Self::Grouped(plan) => &plan.scalar,
62 }
63 }
64
65 #[must_use]
67 #[cfg(test)]
68 pub(in crate::db) const fn scalar_semantics_mut(&mut self) -> &mut ScalarPlan {
69 match self {
70 Self::Scalar(plan) => plan,
71 Self::Grouped(plan) => &mut plan.scalar,
72 }
73 }
74
75 #[must_use]
77 #[cfg(test)]
78 pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
79 self.scalar_semantics()
80 }
81
82 #[must_use]
84 #[cfg(test)]
85 pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
86 self.scalar_semantics_mut()
87 }
88}
89
90impl AccessPlannedQuery {
91 #[must_use]
93 pub(in crate::db) const fn scalar_plan(&self) -> &ScalarPlan {
94 self.logical.scalar_semantics()
95 }
96
97 #[must_use]
100 pub(in crate::db) const fn scalar_consistency(&self) -> MissingRowPolicy {
101 self.scalar_plan().consistency
102 }
103
104 #[must_use]
106 #[cfg(test)]
107 pub(in crate::db) const fn scalar_plan_mut(&mut self) -> &mut ScalarPlan {
108 self.logical.scalar_semantics_mut()
109 }
110
111 #[must_use]
113 #[cfg(test)]
114 pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
115 self.scalar_plan()
116 }
117
118 #[must_use]
120 #[cfg(test)]
121 pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
122 self.scalar_plan_mut()
123 }
124
125 #[must_use]
127 pub(in crate::db) const fn grouped_plan(&self) -> Option<&GroupPlan> {
128 match &self.logical {
129 LogicalPlan::Scalar(_) => None,
130 LogicalPlan::Grouped(plan) => Some(plan),
131 }
132 }
133
134 #[must_use]
136 pub(in crate::db) fn projection_spec(&self, model: &EntityModel) -> ProjectionSpec {
137 if let Some(static_shape) = &self.static_planning_shape {
138 return static_shape.projection_spec.clone();
139 }
140
141 lower_projection_intent(model, &self.logical, &self.projection_selection)
142 }
143
144 #[must_use]
146 pub(in crate::db::query) fn projection_spec_for_identity(&self) -> ProjectionSpec {
147 lower_projection_identity(&self.logical, &self.projection_selection)
148 }
149
150 #[must_use]
156 pub(in crate::db) fn execution_preparation_predicate(&self) -> Option<Predicate> {
157 if let Some(static_shape) = self.static_planning_shape.as_ref() {
158 return static_shape.execution_preparation_predicate.clone();
159 }
160
161 derive_execution_preparation_predicate(self)
162 }
163
164 #[must_use]
168 pub(in crate::db) fn effective_execution_predicate(&self) -> Option<Predicate> {
169 if let Some(static_shape) = self.static_planning_shape.as_ref() {
170 return static_shape.residual_filter_predicate.clone();
171 }
172
173 derive_residual_filter_predicate(self)
174 }
175
176 #[must_use]
179 pub(in crate::db) fn has_residual_filter_predicate(&self) -> bool {
180 self.effective_execution_predicate().is_some()
181 }
182
183 #[must_use]
186 pub(in crate::db) fn residual_filter_expr(&self) -> Option<&Expr> {
187 if let Some(static_shape) = self.static_planning_shape.as_ref() {
188 return static_shape.residual_filter_expr.as_ref();
189 }
190
191 if !derive_has_residual_filter(self) {
192 return None;
193 }
194
195 self.scalar_plan().filter_expr.as_ref()
196 }
197
198 #[must_use]
201 pub(in crate::db) fn has_residual_filter_expr(&self) -> bool {
202 self.residual_filter_expr().is_some()
203 }
204
205 #[must_use]
207 pub(in crate::db) const fn execution_preparation_compiled_predicate(
208 &self,
209 ) -> Option<&PredicateProgram> {
210 self.static_planning_shape()
211 .execution_preparation_compiled_predicate
212 .as_ref()
213 }
214
215 #[must_use]
217 pub(in crate::db) const fn effective_runtime_compiled_predicate(
218 &self,
219 ) -> Option<&PredicateProgram> {
220 match self
221 .static_planning_shape()
222 .effective_runtime_filter_program
223 .as_ref()
224 {
225 Some(program) => program.predicate_program(),
226 None => None,
227 }
228 }
229
230 #[cfg(test)]
232 #[must_use]
233 pub(in crate::db) const fn effective_runtime_compiled_filter_expr(
234 &self,
235 ) -> Option<&CompiledExpr> {
236 match self
237 .static_planning_shape()
238 .effective_runtime_filter_program
239 .as_ref()
240 {
241 Some(program) => program.expression_filter(),
242 None => None,
243 }
244 }
245
246 #[must_use]
248 pub(in crate::db) const fn effective_runtime_filter_program(
249 &self,
250 ) -> Option<&EffectiveRuntimeFilterProgram> {
251 self.static_planning_shape()
252 .effective_runtime_filter_program
253 .as_ref()
254 }
255
256 #[must_use]
258 pub(in crate::db) fn distinct_execution_strategy(&self) -> DistinctExecutionStrategy {
259 if !self.scalar_plan().distinct {
260 return DistinctExecutionStrategy::None;
261 }
262
263 match distinct_runtime_dedup_strategy(&self.access) {
267 Some(strategy) => strategy,
268 None => DistinctExecutionStrategy::None,
269 }
270 }
271
272 pub(in crate::db) fn finalize_planner_route_profile_for_model(&mut self, model: &EntityModel) {
274 self.set_planner_route_profile(project_planner_route_profile_for_model(model, self));
275 }
276
277 pub(in crate::db) fn finalize_static_planning_shape_for_model(
279 &mut self,
280 model: &EntityModel,
281 ) -> Result<(), InternalError> {
282 self.finalize_static_planning_shape_for_model_with_schema(
283 model,
284 SchemaInfo::cached_for_entity_model(model),
285 )
286 }
287
288 pub(in crate::db) fn finalize_static_planning_shape_for_model_with_schema(
290 &mut self,
291 model: &EntityModel,
292 schema_info: &SchemaInfo,
293 ) -> Result<(), InternalError> {
294 self.static_planning_shape = Some(project_static_planning_shape_for_model(
295 model,
296 schema_info,
297 self,
298 )?);
299
300 Ok(())
301 }
302
303 #[must_use]
305 pub(in crate::db) fn execution_shape_signature(
306 &self,
307 entity_path: &'static str,
308 ) -> ExecutionShapeSignature {
309 ExecutionShapeSignature::new(self.continuation_signature(entity_path))
310 }
311
312 #[must_use]
315 pub(in crate::db) fn predicate_fully_satisfied_by_access_contract(&self) -> bool {
316 if let Some(static_shape) = self.static_planning_shape.as_ref() {
317 return self.scalar_plan().predicate.is_some()
318 && static_shape.residual_filter_predicate.is_none()
319 && static_shape.residual_filter_expr.is_none();
320 }
321
322 derive_predicate_fully_satisfied_by_access_contract(self)
323 }
324
325 #[must_use]
327 pub(in crate::db) fn scalar_projection_plan(&self) -> Option<&[CompiledExpr]> {
328 self.static_planning_shape()
329 .scalar_projection_plan
330 .as_deref()
331 }
332
333 #[must_use]
335 pub(in crate::db) const fn has_static_planning_shape(&self) -> bool {
336 self.static_planning_shape.is_some()
337 }
338
339 #[must_use]
341 pub(in crate::db) const fn primary_key_name(&self) -> &'static str {
342 self.static_planning_shape().primary_key_name
343 }
344
345 #[must_use]
347 pub(in crate::db) const fn projection_referenced_slots(&self) -> &[usize] {
348 self.static_planning_shape()
349 .projection_referenced_slots
350 .as_slice()
351 }
352
353 #[must_use]
355 #[cfg(any(test, feature = "diagnostics"))]
356 pub(in crate::db) const fn projected_slot_mask(&self) -> &[bool] {
357 self.static_planning_shape().projected_slot_mask.as_slice()
358 }
359
360 #[must_use]
362 pub(in crate::db) const fn projection_is_model_identity(&self) -> bool {
363 self.static_planning_shape().projection_is_model_identity
364 }
365
366 #[must_use]
368 pub(in crate::db) fn order_referenced_slots(&self) -> Option<&[usize]> {
369 self.static_planning_shape()
370 .order_referenced_slots
371 .as_deref()
372 }
373
374 #[must_use]
376 pub(in crate::db) const fn resolved_order(&self) -> Option<&ResolvedOrder> {
377 self.static_planning_shape().resolved_order.as_ref()
378 }
379
380 #[must_use]
382 pub(in crate::db) fn slot_map(&self) -> Option<&[usize]> {
383 self.static_planning_shape().slot_map.as_deref()
384 }
385
386 #[must_use]
388 pub(in crate::db) fn grouped_aggregate_execution_specs(
389 &self,
390 ) -> Option<&[GroupedAggregateExecutionSpec]> {
391 self.static_planning_shape()
392 .grouped_aggregate_execution_specs
393 .as_deref()
394 }
395
396 #[must_use]
398 pub(in crate::db) const fn grouped_distinct_execution_strategy(
399 &self,
400 ) -> Option<&GroupedDistinctExecutionStrategy> {
401 self.static_planning_shape()
402 .grouped_distinct_execution_strategy
403 .as_ref()
404 }
405
406 #[must_use]
408 pub(in crate::db) const fn frozen_projection_spec(&self) -> &ProjectionSpec {
409 &self.static_planning_shape().projection_spec
410 }
411
412 #[must_use]
414 pub(in crate::db) fn frozen_direct_projection_slots(&self) -> Option<&[usize]> {
415 self.static_planning_shape()
416 .projection_direct_slots
417 .as_deref()
418 }
419
420 #[must_use]
422 pub(in crate::db) fn frozen_data_row_direct_projection_slots(&self) -> Option<&[usize]> {
423 self.static_planning_shape()
424 .projection_data_row_direct_slots
425 .as_deref()
426 }
427
428 #[must_use]
430 pub(in crate::db) fn index_compile_targets(&self) -> Option<&[IndexCompileTarget]> {
431 self.static_planning_shape()
432 .index_compile_targets
433 .as_deref()
434 }
435
436 const fn static_planning_shape(&self) -> &StaticPlanningShape {
437 self.static_planning_shape
438 .as_ref()
439 .expect("access-planned queries must freeze static planning shape before execution")
440 }
441}
442
443fn distinct_runtime_dedup_strategy<K>(access: &AccessPlan<K>) -> Option<DistinctExecutionStrategy> {
444 match access {
445 AccessPlan::Union(_) | AccessPlan::Intersection(_) => {
446 Some(DistinctExecutionStrategy::PreOrdered)
447 }
448 AccessPlan::Path(path) if path.as_ref().is_index_multi_lookup() => {
449 Some(DistinctExecutionStrategy::HashMaterialize)
450 }
451 AccessPlan::Path(_) => None,
452 }
453}
454
455fn derive_continuation_policy_validated(plan: &AccessPlannedQuery) -> ContinuationPolicy {
456 let is_grouped_safe = plan
457 .grouped_plan()
458 .is_none_or(|grouped| grouped_cursor_policy_violation(grouped, true).is_none());
459
460 ContinuationPolicy::new(
461 true, true, is_grouped_safe,
464 )
465}
466
467#[must_use]
469pub(in crate::db) fn project_planner_route_profile_for_model(
470 model: &EntityModel,
471 plan: &AccessPlannedQuery,
472) -> PlannerRouteProfile {
473 let secondary_order_contract = plan
474 .scalar_plan()
475 .order
476 .as_ref()
477 .and_then(|order| order.deterministic_secondary_order_contract(model.primary_key.name));
478
479 PlannerRouteProfile::new(
480 derive_continuation_policy_validated(plan),
481 derive_logical_pushdown_eligibility(plan, secondary_order_contract.as_ref()),
482 secondary_order_contract,
483 )
484}
485
486fn project_static_planning_shape_for_model(
487 model: &EntityModel,
488 schema_info: &SchemaInfo,
489 plan: &AccessPlannedQuery,
490) -> Result<StaticPlanningShape, InternalError> {
491 let projection_spec = lower_projection_intent(model, &plan.logical, &plan.projection_selection);
492 let execution_preparation_predicate = plan.execution_preparation_predicate();
493 let residual_filter_predicate = derive_residual_filter_predicate(plan);
494 let residual_filter_expr = derive_residual_filter_expr_for_model(model, plan);
495 let execution_preparation_compiled_predicate =
496 compile_optional_predicate(model, execution_preparation_predicate.as_ref());
497 let effective_runtime_filter_program = compile_effective_runtime_filter_program(
498 model,
499 schema_info,
500 residual_filter_expr.as_ref(),
501 residual_filter_predicate.as_ref(),
502 )?;
503 let scalar_projection_plan = if plan.grouped_plan().is_none() {
504 Some(
505 compile_scalar_projection_plan_with_schema(model, schema_info, &projection_spec)
506 .ok_or_else(|| {
507 InternalError::query_executor_invariant(
508 "scalar projection program must compile during static planning finalization",
509 )
510 })?
511 .iter()
512 .map(CompiledExpr::compile)
513 .collect(),
514 )
515 } else {
516 None
517 };
518 let (grouped_aggregate_execution_specs, grouped_distinct_execution_strategy) =
519 resolve_grouped_static_planning_semantics(model, schema_info, plan, &projection_spec)?;
520 let projection_direct_slots = lower_direct_projection_slots_with_schema(
521 model,
522 schema_info,
523 &plan.logical,
524 &plan.projection_selection,
525 );
526 let projection_data_row_direct_slots = lower_data_row_direct_projection_slots_with_schema(
527 model,
528 schema_info,
529 &plan.logical,
530 &plan.projection_selection,
531 );
532 let projection_referenced_slots =
533 projection_spec.referenced_slots_for_schema(model, schema_info)?;
534 let projected_slot_mask =
535 projected_slot_mask_for_spec(model, projection_direct_slots.as_deref());
536 let projection_is_model_identity = projection_spec.is_model_identity_for(model);
537 let resolved_order = resolved_order_for_plan(model, schema_info, plan)?;
538 let order_referenced_slots = order_referenced_slots_for_resolved_order(resolved_order.as_ref());
539 let slot_map = slot_map_for_schema_plan(schema_info, plan);
540 let index_compile_targets = index_compile_targets_for_schema_plan(schema_info, plan);
541
542 Ok(StaticPlanningShape {
543 primary_key_name: model.primary_key.name,
544 projection_spec,
545 execution_preparation_predicate,
546 residual_filter_expr,
547 residual_filter_predicate,
548 execution_preparation_compiled_predicate,
549 effective_runtime_filter_program,
550 scalar_projection_plan,
551 grouped_aggregate_execution_specs,
552 grouped_distinct_execution_strategy,
553 projection_direct_slots,
554 projection_data_row_direct_slots,
555 projection_referenced_slots,
556 projected_slot_mask,
557 projection_is_model_identity,
558 resolved_order,
559 order_referenced_slots,
560 slot_map,
561 index_compile_targets,
562 })
563}
564
565fn compile_effective_runtime_filter_program(
569 model: &EntityModel,
570 schema_info: &SchemaInfo,
571 residual_filter_expr: Option<&Expr>,
572 residual_filter_predicate: Option<&Predicate>,
573) -> Result<Option<EffectiveRuntimeFilterProgram>, InternalError> {
574 if let Some(predicate) = residual_filter_predicate {
579 return Ok(Some(EffectiveRuntimeFilterProgram::predicate(
580 PredicateProgram::compile(model, predicate),
581 )));
582 }
583
584 if let Some(filter_expr) = residual_filter_expr {
585 let compiled = compile_scalar_projection_expr_with_schema(model, schema_info, filter_expr)
586 .ok_or_else(|| {
587 InternalError::query_invalid_logical_plan(
588 "effective runtime scalar filter expression must compile during static planning finalization",
589 )
590 })?;
591
592 return Ok(Some(EffectiveRuntimeFilterProgram::expression(
593 CompiledExpr::compile(&compiled),
594 )));
595 }
596
597 Ok(None)
598}
599
600fn derive_execution_preparation_predicate(plan: &AccessPlannedQuery) -> Option<Predicate> {
604 let query_predicate = plan.scalar_plan().predicate.as_ref()?;
605
606 match plan.access.selected_index_model() {
607 Some(index) => residual_query_predicate_after_filtered_access(index, query_predicate),
608 None => Some(query_predicate.clone()),
609 }
610}
611
612fn derive_residual_filter_predicate(plan: &AccessPlannedQuery) -> Option<Predicate> {
616 let filtered_residual = derive_execution_preparation_predicate(plan);
617 let filtered_residual = filtered_residual.as_ref()?;
618
619 residual_query_predicate_after_access_path_bounds(plan.access.as_path(), filtered_residual)
620}
621
622fn derive_residual_filter_expr(plan: &AccessPlannedQuery) -> Option<Expr> {
626 let filter_expr = plan.scalar_plan().filter_expr.as_ref()?;
627 if derive_semantic_filter_fully_satisfied_by_access_contract(plan) {
628 return None;
629 }
630
631 Some(filter_expr.clone())
632}
633
634fn derive_residual_filter_expr_for_model(
638 model: &EntityModel,
639 plan: &AccessPlannedQuery,
640) -> Option<Expr> {
641 let filter_expr = plan.scalar_plan().filter_expr.as_ref()?;
642 if derive_semantic_filter_fully_satisfied_by_access_contract_for_model(model, plan) {
643 return None;
644 }
645
646 Some(filter_expr.clone())
647}
648
649fn derive_has_residual_filter(plan: &AccessPlannedQuery) -> bool {
653 match (
654 plan.scalar_plan().filter_expr.as_ref(),
655 plan.scalar_plan().predicate.as_ref(),
656 ) {
657 (None, None) => false,
658 (Some(_), None) => true,
659 (Some(_) | None, Some(_)) => !plan.predicate_fully_satisfied_by_access_contract(),
660 }
661}
662
663fn derive_predicate_fully_satisfied_by_access_contract(plan: &AccessPlannedQuery) -> bool {
666 plan.scalar_plan().predicate.is_some()
667 && derive_residual_filter_predicate(plan).is_none()
668 && derive_residual_filter_expr(plan).is_none()
669}
670
671const fn derive_semantic_filter_fully_satisfied_by_access_contract(
675 plan: &AccessPlannedQuery,
676) -> bool {
677 plan.scalar_plan().filter_expr.is_some()
678 && plan.scalar_plan().predicate.is_some()
679 && plan.scalar_plan().predicate_covers_filter_expr
680}
681
682const fn derive_semantic_filter_fully_satisfied_by_access_contract_for_model(
686 _model: &EntityModel,
687 plan: &AccessPlannedQuery,
688) -> bool {
689 derive_semantic_filter_fully_satisfied_by_access_contract(plan)
690}
691
692fn compile_optional_predicate(
695 model: &EntityModel,
696 predicate: Option<&Predicate>,
697) -> Option<PredicateProgram> {
698 predicate.map(|predicate| PredicateProgram::compile(model, predicate))
699}
700
701fn resolve_grouped_static_planning_semantics(
705 model: &EntityModel,
706 schema_info: &SchemaInfo,
707 plan: &AccessPlannedQuery,
708 projection_spec: &ProjectionSpec,
709) -> Result<
710 (
711 Option<Vec<GroupedAggregateExecutionSpec>>,
712 Option<GroupedDistinctExecutionStrategy>,
713 ),
714 InternalError,
715> {
716 let Some(grouped) = plan.grouped_plan() else {
717 return Ok((None, None));
718 };
719
720 let mut aggregate_specs = grouped_aggregate_specs_from_projection_spec(
721 projection_spec,
722 grouped.group.group_fields.as_slice(),
723 grouped.group.aggregates.as_slice(),
724 )?;
725 extend_grouped_having_aggregate_specs(&mut aggregate_specs, grouped)?;
726
727 let grouped_aggregate_execution_specs = Some(grouped_aggregate_execution_specs(
728 model,
729 schema_info,
730 aggregate_specs.as_slice(),
731 )?);
732 let grouped_distinct_execution_strategy =
733 Some(resolved_grouped_distinct_execution_strategy_for_model(
734 model,
735 schema_info,
736 grouped.group.group_fields.as_slice(),
737 grouped.group.aggregates.as_slice(),
738 grouped.having_expr.as_ref(),
739 )?);
740
741 Ok((
742 grouped_aggregate_execution_specs,
743 grouped_distinct_execution_strategy,
744 ))
745}
746
747fn extend_grouped_having_aggregate_specs(
748 aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
749 grouped: &GroupPlan,
750) -> Result<(), InternalError> {
751 if let Some(having_expr) = grouped.having_expr.as_ref() {
752 collect_grouped_having_expr_aggregate_specs(aggregate_specs, having_expr)?;
753 }
754
755 Ok(())
756}
757
758fn collect_grouped_having_expr_aggregate_specs(
759 aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
760 expr: &Expr,
761) -> Result<(), InternalError> {
762 if !expr.contains_aggregate() {
763 return Ok(());
764 }
765
766 expr.try_for_each_tree_aggregate(&mut |aggregate_expr| {
767 let aggregate_spec = GroupedAggregateExecutionSpec::from_aggregate_expr(aggregate_expr);
768
769 if aggregate_specs
770 .iter()
771 .all(|current| current != &aggregate_spec)
772 {
773 aggregate_specs.push(aggregate_spec);
774 }
775
776 Ok(())
777 })
778}
779
780fn projected_slot_mask_for_spec(
781 model: &EntityModel,
782 direct_projection_slots: Option<&[usize]>,
783) -> Vec<bool> {
784 let schema_slot_len = direct_projection_slots
785 .and_then(|slots| slots.iter().copied().max())
786 .map_or(0, |slot| slot.saturating_add(1));
787 let mut projected_slots = vec![false; model.fields().len().max(schema_slot_len)];
788
789 let Some(direct_projection_slots) = direct_projection_slots else {
790 return projected_slots;
791 };
792
793 for slot in direct_projection_slots.iter().copied() {
794 if let Some(projected) = projected_slots.get_mut(slot) {
795 *projected = true;
796 }
797 }
798
799 projected_slots
800}
801
802fn resolved_order_for_plan(
803 model: &EntityModel,
804 schema_info: &SchemaInfo,
805 plan: &AccessPlannedQuery,
806) -> Result<Option<ResolvedOrder>, InternalError> {
807 if grouped_plan_strategy(plan).is_some_and(GroupedPlanStrategy::is_top_k_group) {
808 return Ok(None);
809 }
810
811 let Some(order) = plan.scalar_plan().order.as_ref() else {
812 return Ok(None);
813 };
814
815 let mut fields = Vec::with_capacity(order.fields.len());
816 for term in &order.fields {
817 fields.push(ResolvedOrderField::new(
818 resolved_order_value_source_for_term(model, schema_info, term)?,
819 term.direction(),
820 ));
821 }
822
823 Ok(Some(ResolvedOrder::new(fields)))
824}
825
826fn resolved_order_value_source_for_term(
827 model: &EntityModel,
828 schema_info: &SchemaInfo,
829 term: &crate::db::query::plan::OrderTerm,
830) -> Result<ResolvedOrderValueSource, InternalError> {
831 if term.direct_field().is_none() {
832 let rendered = term.rendered_label();
833 validate_resolved_order_expr_fields(schema_info, term.expr(), rendered.as_str())?;
834 let compiled = compile_scalar_projection_expr_with_schema(model, schema_info, term.expr())
835 .ok_or_else(|| order_expression_scalar_seam_error(rendered.as_str()))?;
836
837 return Ok(ResolvedOrderValueSource::expression(CompiledExpr::compile(
838 &compiled,
839 )));
840 }
841
842 let field = term
843 .direct_field()
844 .expect("direct-field order branch should only execute for field-backed terms");
845 let slot = resolve_required_schema_slot(schema_info, field, || {
846 InternalError::query_invalid_logical_plan(format!(
847 "order expression references unknown field '{field}'",
848 ))
849 })?;
850
851 Ok(ResolvedOrderValueSource::direct_field(slot))
852}
853
854fn validate_resolved_order_expr_fields(
855 schema_info: &SchemaInfo,
856 expr: &Expr,
857 rendered: &str,
858) -> Result<(), InternalError> {
859 expr.try_for_each_tree_expr(&mut |node| match node {
860 Expr::Field(field_id) => {
861 resolve_required_schema_slot(schema_info, field_id.as_str(), || {
862 InternalError::query_invalid_logical_plan(format!(
863 "order expression references unknown field '{rendered}'",
864 ))
865 })
866 .map(|_| ())
867 }
868 Expr::Aggregate(_) => Err(order_expression_scalar_seam_error(rendered)),
869 #[cfg(test)]
870 Expr::Alias { .. } => Err(order_expression_scalar_seam_error(rendered)),
871 Expr::Unary { .. } => Err(order_expression_scalar_seam_error(rendered)),
872 _ => Ok(()),
873 })
874}
875
876fn resolve_required_schema_slot<F>(
880 schema_info: &SchemaInfo,
881 field: &str,
882 invalid_plan_error: F,
883) -> Result<usize, InternalError>
884where
885 F: FnOnce() -> InternalError,
886{
887 schema_info
888 .field_slot_index(field)
889 .ok_or_else(invalid_plan_error)
890}
891
892fn order_expression_scalar_seam_error(rendered: &str) -> InternalError {
895 InternalError::query_invalid_logical_plan(format!(
896 "order expression '{rendered}' did not stay on the scalar expression seam",
897 ))
898}
899
900fn order_referenced_slots_for_resolved_order(
905 resolved_order: Option<&ResolvedOrder>,
906) -> Option<Vec<usize>> {
907 Some(resolved_order?.referenced_slots())
908}
909
910fn slot_map_for_schema_plan(
911 schema_info: &SchemaInfo,
912 plan: &AccessPlannedQuery,
913) -> Option<Vec<usize>> {
914 let executable = plan.access.executable_contract();
915
916 resolved_index_slots_for_access_path(schema_info, &executable)
917}
918
919fn resolved_index_slots_for_access_path(
920 schema_info: &SchemaInfo,
921 access: &ExecutableAccessPlan<'_, crate::value::Value>,
922) -> Option<Vec<usize>> {
923 let path = access.as_path()?;
924 let path_capabilities = path.capabilities();
925 let index_fields = path_capabilities.index_fields_for_slot_map()?;
926 let mut slots = Vec::with_capacity(index_fields.len());
927
928 for field_name in index_fields {
929 let slot = schema_info.field_slot_index(field_name)?;
930 slots.push(slot);
931 }
932
933 Some(slots)
934}
935
936fn index_compile_targets_for_schema_plan(
937 schema_info: &SchemaInfo,
938 plan: &AccessPlannedQuery,
939) -> Option<Vec<IndexCompileTarget>> {
940 let index = plan.access.as_path()?.selected_index_model()?;
941 let mut targets = Vec::new();
942
943 match index.key_items() {
944 IndexKeyItemsRef::Fields(fields) => {
945 for (component_index, &field_name) in fields.iter().enumerate() {
946 let field_slot = schema_info.field_slot_index(field_name)?;
947 targets.push(IndexCompileTarget {
948 component_index,
949 field_slot,
950 key_item: crate::model::index::IndexKeyItem::Field(field_name),
951 });
952 }
953 }
954 IndexKeyItemsRef::Items(items) => {
955 for (component_index, &key_item) in items.iter().enumerate() {
956 let field_slot = schema_info.field_slot_index(key_item.field())?;
957 targets.push(IndexCompileTarget {
958 component_index,
959 field_slot,
960 key_item,
961 });
962 }
963 }
964 }
965
966 Some(targets)
967}