use crate::{
db::{
DbSession, MissingRowPolicy, QueryError,
executor::{
EntityAuthority, assemble_load_execution_node_descriptor,
explain::assemble_scalar_aggregate_execution_descriptor_with_projection,
planning::route::AggregateRouteShape,
},
query::explain::ExplainAggregateTerminalPlan,
session::sql::projection::annotate_sql_projection_debug_on_execution_descriptor,
sql::lowering::{
LoweredSqlCommand, LoweredSqlLaneKind, SqlGlobalAggregateCommandCore,
bind_lowered_sql_explain_global_aggregate_structural,
bind_lowered_sql_query_structural, lowered_sql_command_lane,
},
sql::parser::SqlExplainMode,
},
traits::CanisterKind,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ExplainSqlLane {
Query,
Explain,
Describe,
ShowIndexes,
ShowColumns,
ShowEntities,
}
const fn explain_sql_lane(command: &LoweredSqlCommand) -> ExplainSqlLane {
match lowered_sql_command_lane(command) {
LoweredSqlLaneKind::Query => ExplainSqlLane::Query,
LoweredSqlLaneKind::Explain => ExplainSqlLane::Explain,
LoweredSqlLaneKind::Describe => ExplainSqlLane::Describe,
LoweredSqlLaneKind::ShowIndexes => ExplainSqlLane::ShowIndexes,
LoweredSqlLaneKind::ShowColumns => ExplainSqlLane::ShowColumns,
LoweredSqlLaneKind::ShowEntities => ExplainSqlLane::ShowEntities,
}
}
const fn unsupported_explain_sql_lane_message(lane: ExplainSqlLane) -> &'static str {
match lane {
ExplainSqlLane::Describe => "explain_sql rejects DESCRIBE",
ExplainSqlLane::ShowIndexes => "explain_sql rejects SHOW INDEXES",
ExplainSqlLane::ShowColumns => "explain_sql rejects SHOW COLUMNS",
ExplainSqlLane::ShowEntities => "explain_sql rejects SHOW ENTITIES",
ExplainSqlLane::Query | ExplainSqlLane::Explain => "explain_sql requires EXPLAIN",
}
}
fn sql_execution_phase_breakdown_lines() -> Vec<String> {
vec![
"phases:".to_string(),
" c=compile: parse, lower, and compile the SQL surface".to_string(),
" p=planner: resolve visible indexes and build the structural access plan".to_string(),
" s=store: traverse physical index/data storage and decode physical access payloads"
.to_string(),
" e=executor: run residual filter, order, group, aggregate, and projection logic"
.to_string(),
" d=decode: package the public SQL result payload for the shell".to_string(),
]
}
fn render_sql_execution_explain(descriptor: &crate::db::ExplainExecutionNodeDescriptor) -> String {
let mut lines = sql_execution_phase_breakdown_lines();
lines.push("execution:".to_string());
lines.push(descriptor.render_text_tree_verbose_with_indent(" "));
lines.join("\n")
}
impl<C: CanisterKind> DbSession<C> {
pub(in crate::db) fn explain_lowered_sql_for_authority(
&self,
lowered: &LoweredSqlCommand,
authority: EntityAuthority,
) -> Result<String, QueryError> {
let lane = explain_sql_lane(lowered);
if lane != ExplainSqlLane::Explain {
return Err(QueryError::unsupported_query(
unsupported_explain_sql_lane_message(lane),
));
}
if let Some(rendered) =
self.render_lowered_sql_explain_plan_or_json_for_authority(lowered, authority)?
{
return Ok(rendered);
}
if let Some((mode, command)) = bind_lowered_sql_explain_global_aggregate_structural(
lowered,
authority.model(),
MissingRowPolicy::Ignore,
)
.map_err(QueryError::from_sql_lowering_error)?
{
return self
.explain_sql_global_aggregate_structural_for_authority(mode, command, authority);
}
Err(QueryError::unsupported_query(
"shared EXPLAIN execution could not classify lowered SQL shape",
))
}
fn render_lowered_sql_explain_plan_or_json_for_authority(
&self,
lowered: &LoweredSqlCommand,
authority: EntityAuthority,
) -> Result<Option<String>, QueryError> {
let Some((mode, query)) = lowered.explain_query() else {
return Ok(None);
};
if matches!(mode, SqlExplainMode::Execution) {
return Ok(None);
}
let structural = bind_lowered_sql_query_structural(
authority.model(),
query.clone(),
MissingRowPolicy::Ignore,
)
.map_err(QueryError::from_sql_lowering_error)?;
let (_, mut plan) =
self.build_structural_plan_with_visible_indexes_for_authority(structural, authority)?;
authority.finalize_static_planning_shape(&mut plan);
let explain = plan.explain();
let rendered = match mode {
SqlExplainMode::Plan => explain.render_text_canonical(),
SqlExplainMode::Json => explain.render_json_canonical(),
SqlExplainMode::Execution => unreachable!("execution explain is handled separately"),
};
Ok(Some(rendered))
}
pub(in crate::db::session::sql) fn explain_lowered_sql_execution_for_authority(
&self,
lowered: &LoweredSqlCommand,
authority: EntityAuthority,
) -> Result<Option<String>, QueryError> {
let Some((SqlExplainMode::Execution, query)) = lowered.explain_query() else {
return Ok(None);
};
let structural = bind_lowered_sql_query_structural(
authority.model(),
query.clone(),
MissingRowPolicy::Ignore,
)
.map_err(QueryError::from_sql_lowering_error)?;
let (_, mut plan) =
self.build_structural_plan_with_visible_indexes_for_authority(structural, authority)?;
authority.finalize_static_planning_shape(&mut plan);
let mut descriptor = assemble_load_execution_node_descriptor(
authority.fields(),
authority.primary_key_name(),
&plan,
)
.map_err(QueryError::execute)?;
annotate_sql_projection_debug_on_execution_descriptor(
&mut descriptor,
authority.model(),
&plan,
plan.frozen_projection_spec(),
);
Ok(Some(render_sql_execution_explain(&descriptor)))
}
#[inline(never)]
fn explain_sql_global_aggregate_structural_for_authority(
&self,
mode: SqlExplainMode,
command: SqlGlobalAggregateCommandCore,
authority: EntityAuthority,
) -> Result<String, QueryError> {
let model = command.query().model();
let visible_indexes =
self.visible_indexes_for_store_model(authority.store_path(), authority.model())?;
let strategies = command.strategies();
match mode {
SqlExplainMode::Plan => Ok(command
.query()
.build_plan_with_visible_indexes(&visible_indexes)
.map(|mut plan| {
authority.finalize_static_planning_shape(&mut plan);
plan
})?
.explain()
.render_text_canonical()),
SqlExplainMode::Execution => {
let mut plan = command
.query()
.build_plan_with_visible_indexes(&visible_indexes)?;
authority.finalize_static_planning_shape(&mut plan);
let mut rendered = Vec::with_capacity(strategies.len());
for strategy in strategies {
let query_explain = plan.explain();
let execution = assemble_scalar_aggregate_execution_descriptor_with_projection(
&plan,
AggregateRouteShape::new_from_fields(
strategy.aggregate_kind(),
strategy.projected_field(),
model.fields(),
model.primary_key().name(),
),
strategy.aggregate_kind(),
strategy.projected_field(),
);
let terminal_plan = ExplainAggregateTerminalPlan::new(
query_explain,
strategy.aggregate_kind(),
execution,
);
rendered.push(render_sql_execution_explain(
&terminal_plan.execution_node_descriptor(),
));
}
Ok(rendered.join("\n\n"))
}
SqlExplainMode::Json => Ok(command
.query()
.build_plan_with_visible_indexes(&visible_indexes)
.map(|mut plan| {
authority.finalize_static_planning_shape(&mut plan);
plan
})?
.explain()
.render_json_canonical()),
}
}
}