1use crate::{
7 db::{
8 access::{AccessPlan, ExecutableAccessPlan},
9 predicate::IndexCompileTarget,
10 predicate::{PredicateExecutionModel, PredicateProgram},
11 query::plan::{
12 AccessPlannedQuery, ContinuationPolicy, DistinctExecutionStrategy,
13 ExecutionShapeSignature, ExpressionOrderTerm, GroupPlan, GroupedAggregateExecutionSpec,
14 GroupedDistinctExecutionStrategy, LogicalPlan, PlannerRouteProfile, QueryMode,
15 ResolvedOrder, ResolvedOrderField, ResolvedOrderValueSource, ScalarPlan,
16 StaticPlanningShape, derive_logical_pushdown_eligibility,
17 expr::{
18 Expr, ProjectionField, ProjectionSpec, ScalarProjectionExpr,
19 compile_scalar_projection_plan,
20 },
21 grouped_aggregate_execution_specs_with_model,
22 grouped_aggregate_projection_specs_from_projection_spec,
23 grouped_cursor_policy_violation, lower_direct_projection_slots,
24 lower_projection_identity, lower_projection_intent,
25 residual_query_predicate_after_access_path_bounds,
26 residual_query_predicate_after_filtered_access,
27 resolved_grouped_distinct_execution_strategy_for_model,
28 },
29 },
30 error::InternalError,
31 model::{
32 entity::{EntityModel, resolve_field_slot},
33 index::IndexKeyItemsRef,
34 },
35};
36
37impl QueryMode {
38 #[must_use]
40 pub const fn is_load(&self) -> bool {
41 match self {
42 Self::Load(_) => true,
43 Self::Delete(_) => false,
44 }
45 }
46
47 #[must_use]
49 pub const fn is_delete(&self) -> bool {
50 match self {
51 Self::Delete(_) => true,
52 Self::Load(_) => false,
53 }
54 }
55}
56
57impl LogicalPlan {
58 #[must_use]
60 pub(in crate::db) const fn scalar_semantics(&self) -> &ScalarPlan {
61 match self {
62 Self::Scalar(plan) => plan,
63 Self::Grouped(plan) => &plan.scalar,
64 }
65 }
66
67 #[must_use]
69 #[cfg(test)]
70 pub(in crate::db) const fn scalar_semantics_mut(&mut self) -> &mut ScalarPlan {
71 match self {
72 Self::Scalar(plan) => plan,
73 Self::Grouped(plan) => &mut plan.scalar,
74 }
75 }
76
77 #[must_use]
79 #[cfg(test)]
80 pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
81 self.scalar_semantics()
82 }
83
84 #[must_use]
86 #[cfg(test)]
87 pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
88 self.scalar_semantics_mut()
89 }
90}
91
92impl AccessPlannedQuery {
93 #[must_use]
95 pub(in crate::db) const fn scalar_plan(&self) -> &ScalarPlan {
96 self.logical.scalar_semantics()
97 }
98
99 #[must_use]
101 #[cfg(test)]
102 pub(in crate::db) const fn scalar_plan_mut(&mut self) -> &mut ScalarPlan {
103 self.logical.scalar_semantics_mut()
104 }
105
106 #[must_use]
108 #[cfg(test)]
109 pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
110 self.scalar_plan()
111 }
112
113 #[must_use]
115 #[cfg(test)]
116 pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
117 self.scalar_plan_mut()
118 }
119
120 #[must_use]
122 pub(in crate::db) const fn grouped_plan(&self) -> Option<&GroupPlan> {
123 match &self.logical {
124 LogicalPlan::Scalar(_) => None,
125 LogicalPlan::Grouped(plan) => Some(plan),
126 }
127 }
128
129 #[must_use]
131 pub(in crate::db) fn projection_spec(&self, model: &EntityModel) -> ProjectionSpec {
132 if let Some(static_shape) = &self.static_planning_shape {
133 return static_shape.projection_spec.clone();
134 }
135
136 lower_projection_intent(model, &self.logical, &self.projection_selection)
137 }
138
139 #[must_use]
141 pub(in crate::db::query) fn projection_spec_for_identity(&self) -> ProjectionSpec {
142 lower_projection_identity(&self.logical)
143 }
144
145 #[must_use]
151 pub(in crate::db) fn execution_preparation_predicate(&self) -> Option<PredicateExecutionModel> {
152 let query_predicate = self.scalar_plan().predicate.as_ref()?;
153
154 match self.access.selected_index_model() {
155 Some(index) => residual_query_predicate_after_filtered_access(index, query_predicate),
156 None => Some(query_predicate.clone()),
157 }
158 }
159
160 #[must_use]
164 pub(in crate::db) fn effective_execution_predicate(&self) -> Option<PredicateExecutionModel> {
165 let filtered_residual = self.execution_preparation_predicate();
168 let filtered_residual = filtered_residual.as_ref()?;
169
170 residual_query_predicate_after_access_path_bounds(self.access.as_path(), filtered_residual)
174 }
175
176 #[must_use]
178 pub(in crate::db) const fn execution_preparation_compiled_predicate(
179 &self,
180 ) -> Option<&PredicateProgram> {
181 self.static_planning_shape()
182 .execution_preparation_compiled_predicate
183 .as_ref()
184 }
185
186 #[must_use]
188 pub(in crate::db) const fn effective_runtime_compiled_predicate(
189 &self,
190 ) -> Option<&PredicateProgram> {
191 self.static_planning_shape()
192 .effective_runtime_compiled_predicate
193 .as_ref()
194 }
195
196 #[must_use]
198 pub(in crate::db) fn distinct_execution_strategy(&self) -> DistinctExecutionStrategy {
199 if !self.scalar_plan().distinct {
200 return DistinctExecutionStrategy::None;
201 }
202
203 match distinct_runtime_dedup_strategy(&self.access) {
207 Some(strategy) => strategy,
208 None => DistinctExecutionStrategy::None,
209 }
210 }
211
212 pub(in crate::db) fn finalize_planner_route_profile_for_model(&mut self, model: &EntityModel) {
214 self.set_planner_route_profile(project_planner_route_profile_for_model(model, self));
215 }
216
217 pub(in crate::db) fn finalize_static_planning_shape_for_model(
219 &mut self,
220 model: &EntityModel,
221 ) -> Result<(), InternalError> {
222 self.static_planning_shape = Some(project_static_planning_shape_for_model(model, self)?);
223
224 Ok(())
225 }
226
227 #[must_use]
229 pub(in crate::db) fn execution_shape_signature(
230 &self,
231 entity_path: &'static str,
232 ) -> ExecutionShapeSignature {
233 ExecutionShapeSignature::new(self.continuation_signature(entity_path))
234 }
235
236 #[must_use]
239 pub(in crate::db) fn predicate_fully_satisfied_by_access_contract(&self) -> bool {
240 self.scalar_plan().predicate.is_some() && self.effective_execution_predicate().is_none()
241 }
242
243 #[must_use]
247 pub(in crate::db) fn has_residual_predicate(&self) -> bool {
248 self.scalar_plan().predicate.is_some()
249 && !self.predicate_fully_satisfied_by_access_contract()
250 }
251
252 #[must_use]
254 pub(in crate::db) fn scalar_projection_plan(&self) -> Option<&[ScalarProjectionExpr]> {
255 self.static_planning_shape()
256 .scalar_projection_plan
257 .as_deref()
258 }
259
260 #[must_use]
262 pub(in crate::db) const fn primary_key_name(&self) -> &'static str {
263 self.static_planning_shape().primary_key_name
264 }
265
266 #[must_use]
268 pub(in crate::db) const fn projection_referenced_slots(&self) -> &[usize] {
269 self.static_planning_shape()
270 .projection_referenced_slots
271 .as_slice()
272 }
273
274 #[must_use]
276 pub(in crate::db) const fn projected_slot_mask(&self) -> &[bool] {
277 self.static_planning_shape().projected_slot_mask.as_slice()
278 }
279
280 #[must_use]
282 pub(in crate::db) const fn projection_is_model_identity(&self) -> bool {
283 self.static_planning_shape().projection_is_model_identity
284 }
285
286 #[must_use]
288 pub(in crate::db) fn order_referenced_slots(&self) -> Option<&[usize]> {
289 self.static_planning_shape()
290 .order_referenced_slots
291 .as_deref()
292 }
293
294 #[must_use]
296 pub(in crate::db) const fn resolved_order(&self) -> Option<&ResolvedOrder> {
297 self.static_planning_shape().resolved_order.as_ref()
298 }
299
300 #[must_use]
302 pub(in crate::db) fn slot_map(&self) -> Option<&[usize]> {
303 self.static_planning_shape().slot_map.as_deref()
304 }
305
306 #[must_use]
308 pub(in crate::db) fn grouped_aggregate_execution_specs(
309 &self,
310 ) -> Option<&[GroupedAggregateExecutionSpec]> {
311 self.static_planning_shape()
312 .grouped_aggregate_execution_specs
313 .as_deref()
314 }
315
316 #[must_use]
318 pub(in crate::db) const fn grouped_distinct_execution_strategy(
319 &self,
320 ) -> Option<&GroupedDistinctExecutionStrategy> {
321 self.static_planning_shape()
322 .grouped_distinct_execution_strategy
323 .as_ref()
324 }
325
326 #[must_use]
328 pub(in crate::db) const fn frozen_projection_spec(&self) -> &ProjectionSpec {
329 &self.static_planning_shape().projection_spec
330 }
331
332 #[must_use]
334 pub(in crate::db) fn frozen_direct_projection_slots(&self) -> Option<&[usize]> {
335 self.static_planning_shape()
336 .projection_direct_slots
337 .as_deref()
338 }
339
340 #[must_use]
342 pub(in crate::db) fn index_compile_targets(&self) -> Option<&[IndexCompileTarget]> {
343 self.static_planning_shape()
344 .index_compile_targets
345 .as_deref()
346 }
347
348 const fn static_planning_shape(&self) -> &StaticPlanningShape {
349 self.static_planning_shape
350 .as_ref()
351 .expect("access-planned queries must freeze static planning shape before execution")
352 }
353}
354
355fn distinct_runtime_dedup_strategy<K>(access: &AccessPlan<K>) -> Option<DistinctExecutionStrategy> {
356 match access {
357 AccessPlan::Union(_) | AccessPlan::Intersection(_) => {
358 Some(DistinctExecutionStrategy::PreOrdered)
359 }
360 AccessPlan::Path(path) if path.as_ref().is_index_multi_lookup() => {
361 Some(DistinctExecutionStrategy::HashMaterialize)
362 }
363 AccessPlan::Path(_) => None,
364 }
365}
366
367fn derive_continuation_policy_validated(plan: &AccessPlannedQuery) -> ContinuationPolicy {
368 let is_grouped_safe = plan
369 .grouped_plan()
370 .is_none_or(|grouped| grouped_cursor_policy_violation(grouped, true).is_none());
371
372 ContinuationPolicy::new(
373 true, true, is_grouped_safe,
376 )
377}
378
379#[must_use]
381pub(in crate::db) fn project_planner_route_profile_for_model(
382 model: &EntityModel,
383 plan: &AccessPlannedQuery,
384) -> PlannerRouteProfile {
385 let secondary_order_contract = plan
386 .scalar_plan()
387 .order
388 .as_ref()
389 .and_then(|order| order.deterministic_secondary_order_contract(model.primary_key.name));
390
391 PlannerRouteProfile::new(
392 derive_continuation_policy_validated(plan),
393 derive_logical_pushdown_eligibility(plan, secondary_order_contract.as_ref()),
394 secondary_order_contract,
395 )
396}
397
398fn project_static_planning_shape_for_model(
399 model: &EntityModel,
400 plan: &AccessPlannedQuery,
401) -> Result<StaticPlanningShape, InternalError> {
402 let projection_spec = lower_projection_intent(model, &plan.logical, &plan.projection_selection);
403 let execution_preparation_compiled_predicate = plan
404 .execution_preparation_predicate()
405 .as_ref()
406 .map(|predicate| PredicateProgram::compile_with_model(model, predicate));
407 let effective_runtime_compiled_predicate = plan
408 .effective_execution_predicate()
409 .as_ref()
410 .map(|predicate| PredicateProgram::compile_with_model(model, predicate));
411 let scalar_projection_plan =
412 if plan.grouped_plan().is_none() {
413 Some(compile_scalar_projection_plan(model, &projection_spec).ok_or_else(|| {
414 InternalError::query_executor_invariant(
415 "scalar projection program must compile during static planning finalization",
416 )
417 })?)
418 } else {
419 None
420 };
421 let grouped_aggregate_execution_specs = if let Some(grouped) = plan.grouped_plan() {
422 let aggregate_projection_specs = grouped_aggregate_projection_specs_from_projection_spec(
423 &projection_spec,
424 grouped.group.group_fields.as_slice(),
425 grouped.group.aggregates.as_slice(),
426 )?;
427
428 Some(grouped_aggregate_execution_specs_with_model(
429 model,
430 aggregate_projection_specs.as_slice(),
431 )?)
432 } else {
433 None
434 };
435 let grouped_distinct_execution_strategy = if let Some(grouped) = plan.grouped_plan() {
436 Some(resolved_grouped_distinct_execution_strategy_for_model(
437 model,
438 grouped.group.group_fields.as_slice(),
439 grouped.group.aggregates.as_slice(),
440 grouped.having.as_ref(),
441 )?)
442 } else {
443 None
444 };
445 let projection_direct_slots =
446 lower_direct_projection_slots(model, &plan.logical, &plan.projection_selection);
447 let projection_referenced_slots =
448 projection_referenced_slots_for_spec(model, &projection_spec)?;
449 let projected_slot_mask =
450 projected_slot_mask_for_spec(model, &projection_spec, projection_direct_slots.as_deref());
451 let projection_is_model_identity =
452 projection_is_model_identity_for_spec(model, &projection_spec);
453 let resolved_order = resolved_order_for_plan(model, plan)?;
454 let order_referenced_slots = order_referenced_slots_for_resolved_order(resolved_order.as_ref());
455 let slot_map = slot_map_for_model_plan(model, plan);
456 let index_compile_targets = index_compile_targets_for_model_plan(model, plan);
457
458 Ok(StaticPlanningShape {
459 primary_key_name: model.primary_key.name,
460 projection_spec,
461 execution_preparation_compiled_predicate,
462 effective_runtime_compiled_predicate,
463 scalar_projection_plan,
464 grouped_aggregate_execution_specs,
465 grouped_distinct_execution_strategy,
466 projection_direct_slots,
467 projection_referenced_slots,
468 projected_slot_mask,
469 projection_is_model_identity,
470 resolved_order,
471 order_referenced_slots,
472 slot_map,
473 index_compile_targets,
474 })
475}
476
477fn projection_referenced_slots_for_spec(
478 model: &EntityModel,
479 projection: &ProjectionSpec,
480) -> Result<Vec<usize>, InternalError> {
481 let mut referenced = vec![false; model.fields().len()];
482
483 for field in projection.fields() {
484 match field {
485 ProjectionField::Scalar { expr, .. } => {
486 mark_projection_expr_slots(model, expr, referenced.as_mut_slice())?;
487 }
488 }
489 }
490
491 Ok(referenced
492 .into_iter()
493 .enumerate()
494 .filter_map(|(slot, required)| required.then_some(slot))
495 .collect())
496}
497
498fn mark_projection_expr_slots(
499 model: &EntityModel,
500 expr: &Expr,
501 referenced: &mut [bool],
502) -> Result<(), InternalError> {
503 match expr {
504 Expr::Field(field_id) => {
505 let field_name = field_id.as_str();
506 let slot = resolve_field_slot(model, field_name).ok_or_else(|| {
507 InternalError::query_invalid_logical_plan(format!(
508 "projection expression references unknown field '{field_name}'",
509 ))
510 })?;
511 referenced[slot] = true;
512 }
513 Expr::Literal(_) | Expr::Aggregate(_) => {}
514 Expr::Unary { expr, .. } | Expr::Alias { expr, .. } => {
515 mark_projection_expr_slots(model, expr.as_ref(), referenced)?;
516 }
517 Expr::Binary { left, right, .. } => {
518 mark_projection_expr_slots(model, left.as_ref(), referenced)?;
519 mark_projection_expr_slots(model, right.as_ref(), referenced)?;
520 }
521 }
522
523 Ok(())
524}
525
526fn projected_slot_mask_for_spec(
527 model: &EntityModel,
528 projection: &ProjectionSpec,
529 direct_projection_slots: Option<&[usize]>,
530) -> Vec<bool> {
531 let mut projected_slots = vec![false; model.fields().len()];
532
533 let Some(direct_projection_slots) = direct_projection_slots else {
534 return projected_slots;
535 };
536
537 for (field, slot) in projection
538 .fields()
539 .zip(direct_projection_slots.iter().copied())
540 {
541 if matches!(field, ProjectionField::Scalar { .. })
542 && let Some(projected) = projected_slots.get_mut(slot)
543 {
544 *projected = true;
545 }
546 }
547
548 projected_slots
549}
550
551fn projection_is_model_identity_for_spec(model: &EntityModel, projection: &ProjectionSpec) -> bool {
552 if projection.len() != model.fields().len() {
553 return false;
554 }
555
556 for (field_model, projected_field) in model.fields().iter().zip(projection.fields()) {
557 match projected_field {
558 ProjectionField::Scalar {
559 expr: Expr::Field(field_id),
560 alias: None,
561 } if field_id.as_str() == field_model.name() => {}
562 ProjectionField::Scalar { .. } => return false,
563 }
564 }
565
566 true
567}
568
569fn resolved_order_for_plan(
570 model: &EntityModel,
571 plan: &AccessPlannedQuery,
572) -> Result<Option<ResolvedOrder>, InternalError> {
573 let Some(order) = plan.scalar_plan().order.as_ref() else {
574 return Ok(None);
575 };
576
577 let mut fields = Vec::with_capacity(order.fields.len());
578 for (field, direction) in &order.fields {
579 fields.push(ResolvedOrderField::new(
580 resolved_order_value_source_for_field(model, field)?,
581 *direction,
582 ));
583 }
584
585 Ok(Some(ResolvedOrder::new(fields)))
586}
587
588fn resolved_order_value_source_for_field(
589 model: &EntityModel,
590 field: &str,
591) -> Result<ResolvedOrderValueSource, InternalError> {
592 if let Some(expression) = ExpressionOrderTerm::parse(field) {
593 let slot = resolve_field_slot(model, expression.field()).ok_or_else(|| {
594 InternalError::query_invalid_logical_plan(format!(
595 "order expression references unknown field '{field}'",
596 ))
597 })?;
598
599 return Ok(match expression {
600 ExpressionOrderTerm::Lower(_) => ResolvedOrderValueSource::expression_lower(slot),
601 ExpressionOrderTerm::Upper(_) => ResolvedOrderValueSource::expression_upper(slot),
602 });
603 }
604
605 let slot = resolve_field_slot(model, field).ok_or_else(|| {
606 InternalError::query_invalid_logical_plan(format!(
607 "order expression references unknown field '{field}'",
608 ))
609 })?;
610
611 Ok(ResolvedOrderValueSource::direct_field(slot))
612}
613
614fn order_referenced_slots_for_resolved_order(
615 resolved_order: Option<&ResolvedOrder>,
616) -> Option<Vec<usize>> {
617 let resolved_order = resolved_order?;
618 let mut referenced = Vec::new();
619
620 for field in resolved_order.fields() {
623 let slot = field.source().slot();
624 if !referenced.contains(&slot) {
625 referenced.push(slot);
626 }
627 }
628
629 Some(referenced)
630}
631
632fn slot_map_for_model_plan(model: &EntityModel, plan: &AccessPlannedQuery) -> Option<Vec<usize>> {
633 let access_strategy = plan.access.resolve_strategy();
634 let executable = access_strategy.executable();
635
636 resolved_index_slots_for_access_path(model, executable)
637}
638
639fn resolved_index_slots_for_access_path(
640 model: &EntityModel,
641 access: &ExecutableAccessPlan<'_, crate::value::Value>,
642) -> Option<Vec<usize>> {
643 let path = access.as_path()?;
644 let path_capabilities = path.capabilities();
645 let index_fields = path_capabilities.index_fields_for_slot_map()?;
646 let mut slots = Vec::with_capacity(index_fields.len());
647
648 for field_name in index_fields {
649 let slot = resolve_field_slot(model, field_name)?;
650 slots.push(slot);
651 }
652
653 Some(slots)
654}
655
656fn index_compile_targets_for_model_plan(
657 model: &EntityModel,
658 plan: &AccessPlannedQuery,
659) -> Option<Vec<IndexCompileTarget>> {
660 let index = plan.access.as_path()?.selected_index_model()?;
661 let mut targets = Vec::new();
662
663 match index.key_items() {
664 IndexKeyItemsRef::Fields(fields) => {
665 for (component_index, &field_name) in fields.iter().enumerate() {
666 let field_slot = resolve_field_slot(model, field_name)?;
667 targets.push(IndexCompileTarget {
668 component_index,
669 field_slot,
670 key_item: crate::model::index::IndexKeyItem::Field(field_name),
671 });
672 }
673 }
674 IndexKeyItemsRef::Items(items) => {
675 for (component_index, &key_item) in items.iter().enumerate() {
676 let field_slot = resolve_field_slot(model, key_item.field())?;
677 targets.push(IndexCompileTarget {
678 component_index,
679 field_slot,
680 key_item,
681 });
682 }
683 }
684 }
685
686 Some(targets)
687}