icydb-core 0.151.3

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Module: db::session::sql::execute::explain
//! Responsibility: SQL EXPLAIN execution and rendering adapters.
//! Does not own: planner/executor route policy or diagnostics DTO definitions.
//! Boundary: renders lowered SQL explain statements through session visibility and route facts.

use crate::{
    db::{
        DbSession, MissingRowPolicy, QueryError,
        executor::{
            EntityAuthority, assemble_load_execution_node_descriptor_from_route_facts,
            explain::assemble_scalar_aggregate_execution_descriptor_with_projection,
            freeze_load_execution_route_facts_for_authority,
        },
        query::{
            builder::scalar_projection::render_scalar_projection_expr_plan_label,
            explain::{ExplainAggregateTerminalPlan, FinalizedQueryDiagnostics},
            intent::StructuralQuery,
            plan::AccessPlannedQuery,
        },
        schema::{AcceptedSchemaSnapshot, SchemaInfo},
        session::{
            query::{QueryPlanCacheAttribution, query_plan_cache_reuse_event},
            sql::projection::annotate_sql_projection_debug_on_execution_descriptor,
        },
        sql::{
            lowering::{
                LoweredSqlCommand, LoweredSqlLaneKind, SqlGlobalAggregateCommandCore,
                bind_lowered_sql_explain_global_aggregate_structural_with_schema,
                bind_lowered_sql_query_structural_with_schema, lowered_sql_command_lane,
            },
            parser::SqlExplainMode,
        },
    },
    traits::CanisterKind,
};

///
/// ExplainSqlLane
///
/// ExplainSqlLane classifies lowered SQL statement families only for the
/// `EXPLAIN` surface gate. It prevents non-explain statements from slipping
/// through the explain renderer with ambiguous errors.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ExplainSqlLane {
    Query,
    Explain,
    Describe,
    ShowIndexes,
    ShowColumns,
    ShowEntities,
}

// Render one shell-facing SQL execution explain report with a phase legend and
// one indented immutable diagnostics artifact.
fn render_sql_execution_explain(diagnostics: &FinalizedQueryDiagnostics) -> String {
    let mut lines = 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(),
    ];
    lines.push("execution:".to_string());
    lines.push(diagnostics.render_text_verbose_with_tree_indent("  "));

    lines.join("\n")
}

impl<C: CanisterKind> DbSession<C> {
    // Borrow one lowered SQL query plan from the shared prepared-plan cache when
    // the explain renderer only needs immutable logical/route facts.
    fn try_map_cached_sql_query_explain_plan_for_accepted_authority<T>(
        &self,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
        structural: &StructuralQuery,
        map: impl FnOnce(&AccessPlannedQuery) -> Result<T, QueryError>,
    ) -> Result<(T, QueryPlanCacheAttribution), QueryError> {
        let (prepared_plan, cache_attribution) = self
            .cached_shared_query_plan_for_accepted_authority(
                authority,
                accepted_schema,
                structural,
            )?;
        let mapped = map(prepared_plan.logical_plan())?;

        Ok((mapped, cache_attribution))
    }

    // Resolve one lowered SQL query through the shared prepared-plan cache and
    // return an owned logical plan for explain-only descriptor mutation.
    fn cached_sql_query_explain_plan_for_accepted_authority(
        &self,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
        structural: &StructuralQuery,
    ) -> Result<(AccessPlannedQuery, QueryPlanCacheAttribution), QueryError> {
        let (prepared_plan, cache_attribution) = self
            .cached_shared_query_plan_for_accepted_authority(
                authority,
                accepted_schema,
                structural,
            )?;

        Ok((prepared_plan.logical_plan().clone(), cache_attribution))
    }

    pub(in crate::db::session::sql::execute) fn explain_lowered_sql_for_authority(
        &self,
        lowered: &LoweredSqlCommand,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
    ) -> Result<String, QueryError> {
        let lane = match lowered_sql_command_lane(lowered) {
            LoweredSqlLaneKind::Query => ExplainSqlLane::Query,
            LoweredSqlLaneKind::Explain => ExplainSqlLane::Explain,
            LoweredSqlLaneKind::Describe => ExplainSqlLane::Describe,
            LoweredSqlLaneKind::ShowIndexes => ExplainSqlLane::ShowIndexes,
            LoweredSqlLaneKind::ShowColumns => ExplainSqlLane::ShowColumns,
            LoweredSqlLaneKind::ShowEntities => ExplainSqlLane::ShowEntities,
        };
        if lane != ExplainSqlLane::Explain {
            let message = 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",
            };

            return Err(QueryError::unsupported_query(message));
        }

        let schema_info = SchemaInfo::from_accepted_snapshot_for_model_with_expression_indexes(
            authority.model(),
            accepted_schema,
            true,
        );

        if let Some(rendered) = self.render_lowered_sql_explain_plan_or_json_for_authority(
            lowered,
            authority.clone(),
            accepted_schema,
            &schema_info,
        )? {
            return Ok(rendered);
        }

        if let Some((mode, verbose, command)) =
            bind_lowered_sql_explain_global_aggregate_structural_with_schema(
                lowered,
                authority.model(),
                MissingRowPolicy::Ignore,
                &schema_info,
            )
            .map_err(QueryError::from_sql_lowering_error)?
        {
            return self.explain_sql_global_aggregate_structural_for_authority(
                mode,
                verbose,
                command,
                authority,
                accepted_schema,
            );
        }

        Err(QueryError::unsupported_query(
            "shared EXPLAIN execution could not classify lowered SQL shape",
        ))
    }

    // Render one lowered SQL EXPLAIN PLAN / JSON payload through the session-
    // owned planner visibility boundary for one resolved authority.
    fn render_lowered_sql_explain_plan_or_json_for_authority(
        &self,
        lowered: &LoweredSqlCommand,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
        schema_info: &SchemaInfo,
    ) -> 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_with_schema(
            authority.model(),
            query.clone(),
            MissingRowPolicy::Ignore,
            schema_info,
        )
        .map_err(QueryError::from_sql_lowering_error)?;
        let (rendered, _) = self.try_map_cached_sql_query_explain_plan_for_accepted_authority(
            authority,
            accepted_schema,
            &structural,
            |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(rendered)
            },
        )?;

        Ok(Some(rendered))
    }

    // Render one SQL EXPLAIN EXECUTION payload through the shared planner-owned
    // covering contract. Covering visibility is now part of route planning, so
    // SQL EXPLAIN does not need a separate store-backed authority pass.
    pub(in crate::db::session::sql::execute) fn explain_lowered_sql_execution_for_authority(
        &self,
        lowered: &LoweredSqlCommand,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
    ) -> Result<Option<String>, QueryError> {
        let Some((SqlExplainMode::Execution, verbose, query)) = lowered.explain_query() else {
            return Ok(None);
        };

        let schema_info = SchemaInfo::from_accepted_snapshot_for_model_with_expression_indexes(
            authority.model(),
            accepted_schema,
            true,
        );
        let structural = bind_lowered_sql_query_structural_with_schema(
            authority.model(),
            query.clone(),
            MissingRowPolicy::Ignore,
            &schema_info,
        )
        .map_err(QueryError::from_sql_lowering_error)?;
        if verbose {
            let (mut plan, cache_attribution) = self
                .cached_sql_query_explain_plan_for_accepted_authority(
                    authority.clone(),
                    accepted_schema,
                    &structural,
                )?;
            let visible_indexes = self.visible_indexes_for_store_accepted_schema(
                authority.store_path(),
                authority.model(),
                &schema_info,
            )?;
            plan.finalize_access_choice_for_model_with_accepted_indexes_and_schema(
                authority.model(),
                visible_indexes.generated_expression_candidate_indexes(),
                visible_indexes.accepted_field_path_indexes(),
                visible_indexes.accepted_expression_indexes(),
                &schema_info,
            );
            let diagnostics = structural
                .finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
                    &plan,
                    &authority,
                    Some(query_plan_cache_reuse_event(cache_attribution)),
                    |descriptor| {
                        annotate_sql_projection_debug_on_execution_descriptor(
                            descriptor,
                            &plan,
                            plan.frozen_projection_spec(),
                        );
                    },
                )?;

            return Ok(Some(render_sql_execution_explain(&diagnostics)));
        }

        let (rendered, _) = self.try_map_cached_sql_query_explain_plan_for_accepted_authority(
            authority.clone(),
            accepted_schema,
            &structural,
            |plan| {
                let route_facts = freeze_load_execution_route_facts_for_authority(&authority, plan)
                    .map_err(QueryError::execute)?;
                let mut descriptor =
                    assemble_load_execution_node_descriptor_from_route_facts(plan, &route_facts);
                annotate_sql_projection_debug_on_execution_descriptor(
                    &mut descriptor,
                    plan,
                    plan.frozen_projection_spec(),
                );

                Ok(render_sql_execution_explain(
                    &FinalizedQueryDiagnostics::new(descriptor, Vec::new(), Vec::new(), None),
                ))
            },
        )?;

        Ok(Some(rendered))
    }

    // Resolve one global aggregate base query through the same shared
    // prepared-plan cache as runtime aggregate execution, then borrow immutable
    // logical facts for aggregate descriptor assembly.
    fn try_map_cached_sql_global_aggregate_explain_plan_for_accepted_authority<T>(
        &self,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
        command: &SqlGlobalAggregateCommandCore,
        map: impl FnOnce(&AccessPlannedQuery) -> Result<T, QueryError>,
    ) -> Result<T, QueryError> {
        let (mapped, _) = self.try_map_cached_sql_query_explain_plan_for_accepted_authority(
            authority,
            accepted_schema,
            command.query(),
            map,
        )?;

        Ok(mapped)
    }

    // Render one EXPLAIN payload for constrained global aggregate SQL command
    // through the same shared prepared-plan cache used by runtime execution.
    #[inline(never)]
    fn explain_sql_global_aggregate_structural_for_authority(
        &self,
        mode: SqlExplainMode,
        verbose: bool,
        command: SqlGlobalAggregateCommandCore,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
    ) -> Result<String, QueryError> {
        let strategies = command.strategies();

        match mode {
            SqlExplainMode::Plan => self
                .try_map_cached_sql_global_aggregate_explain_plan_for_accepted_authority(
                    authority,
                    accepted_schema,
                    &command,
                    |plan| Ok(plan.explain().render_text_canonical()),
                ),
            SqlExplainMode::Execution => {
                let _ = verbose;

                self.try_map_cached_sql_global_aggregate_explain_plan_for_accepted_authority(
                    authority.clone(),
                    accepted_schema,
                    &command,
                    |plan| {
                        let mut rendered = Vec::with_capacity(strategies.len());

                        for strategy in strategies {
                            let query_explain = plan.explain();
                            let mut execution =
                                assemble_scalar_aggregate_execution_descriptor_with_projection(
                                    plan,
                                    authority
                                        .aggregate_route_shape(
                                            strategy.aggregate_kind(),
                                            strategy.projected_field(),
                                        )
                                        .map_err(QueryError::execute)?,
                                    strategy.aggregate_kind(),
                                    strategy.projected_field(),
                                );
                            if let Some(filter_expr) = strategy.filter_expr() {
                                execution.node_properties.insert(
                                    "filter_expr",
                                    render_scalar_projection_expr_plan_label(filter_expr).into(),
                                );
                            }
                            let terminal_plan = ExplainAggregateTerminalPlan::new(
                                query_explain,
                                strategy.aggregate_kind(),
                                execution,
                            );

                            rendered.push(render_sql_execution_explain(
                                &FinalizedQueryDiagnostics::new(
                                    terminal_plan.execution_node_descriptor(),
                                    Vec::new(),
                                    Vec::new(),
                                    None,
                                ),
                            ));
                        }

                        Ok(rendered.join("\n\n"))
                    },
                )
            }
            SqlExplainMode::Json => self
                .try_map_cached_sql_global_aggregate_explain_plan_for_accepted_authority(
                    authority,
                    accepted_schema,
                    &command,
                    |plan| Ok(plan.explain().render_json_canonical()),
                ),
        }
    }
}