icydb-core 0.80.3

IcyDB — A type-safe, embedded ORM and schema system for the Internet Computer
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Module: db::session::sql::execute
//! Responsibility: session-owned SQL execution entrypoints that bind lowered SQL
//! commands onto structural planning, execution, and outward result shaping.
//! Does not own: SQL parsing or executor runtime internals.
//! Boundary: centralizes authority-aware SQL execution routing while owner-local
//! submodules keep aggregate, write, and explain details out of the root.

mod aggregate;
mod lowered;
mod route;
mod write;

#[cfg(feature = "perf-attribution")]
use crate::db::executor::pipeline::execute_initial_grouped_rows_for_canister;
#[cfg(feature = "perf-attribution")]
use crate::db::session::sql::SqlExecutePhaseAttribution;
use crate::{
    db::{
        DbSession, PersistedRow, QueryError,
        executor::EntityAuthority,
        query::{intent::StructuralQuery, plan::AccessPlannedQuery},
        session::sql::{
            CompiledSqlCommand, SqlCacheAttribution, SqlCompiledCommandCacheKey,
            SqlStatementResult,
            projection::{SqlProjectionPayload, execute_sql_projection_rows_for_canister},
        },
    },
    traits::{CanisterKind, EntityValue},
};

type PreparedStructuralSqlProjectionExecution = (
    Vec<String>,
    Vec<Option<u32>>,
    AccessPlannedQuery,
    SqlCacheAttribution,
);

#[cfg(feature = "perf-attribution")]
#[expect(
    clippy::missing_const_for_fn,
    reason = "the wasm32 branch reads the runtime performance counter and cannot be const"
)]
fn read_local_instruction_counter() -> u64 {
    #[cfg(target_arch = "wasm32")]
    {
        canic_cdk::api::performance_counter(1)
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        0
    }
}

#[cfg(feature = "perf-attribution")]
fn measure_execute_phase<T, E>(run: impl FnOnce() -> Result<T, E>) -> (u64, Result<T, E>) {
    let start = read_local_instruction_counter();
    let result = run();
    let delta = read_local_instruction_counter().saturating_sub(start);

    (delta, result)
}

impl<C: CanisterKind> DbSession<C> {
    // Build the shared structural SQL projection execution inputs once so
    // value-row and rendered-row statement surfaces only differ in final packaging.
    fn prepare_structural_sql_projection_execution(
        &self,
        query: StructuralQuery,
        authority: EntityAuthority,
        compiled_cache_key: Option<&SqlCompiledCommandCacheKey>,
    ) -> Result<PreparedStructuralSqlProjectionExecution, QueryError> {
        // Phase 1: build the structural access plan once and freeze its outward
        // column contract for all projection materialization surfaces.
        let (entry, cache_attribution) =
            self.planned_sql_select_with_visibility(&query, authority, compiled_cache_key)?;
        let (plan, columns, fixed_scales) = entry.into_parts();

        Ok((columns, fixed_scales, plan, cache_attribution))
    }

    // Execute one structural SQL load query and return only row-oriented SQL
    // projection values, keeping typed projection rows out of the shared SQL
    // query-lane path.
    pub(in crate::db::session::sql) fn execute_structural_sql_projection(
        &self,
        query: StructuralQuery,
        authority: EntityAuthority,
        compiled_cache_key: Option<&SqlCompiledCommandCacheKey>,
    ) -> Result<(SqlProjectionPayload, SqlCacheAttribution), QueryError> {
        // Phase 1: build the shared structural plan and outward column contract once.
        let (columns, fixed_scales, plan, cache_attribution) =
            self.prepare_structural_sql_projection_execution(query, authority, compiled_cache_key)?;

        // Phase 2: execute the shared structural load path with the already
        // derived projection semantics.
        let projected =
            execute_sql_projection_rows_for_canister(&self.db, self.debug, authority, plan)
                .map_err(QueryError::execute)?;
        let (rows, row_count) = projected.into_parts();

        Ok((
            SqlProjectionPayload::new(columns, fixed_scales, rows, row_count),
            cache_attribution,
        ))
    }

    /// Execute one compiled reduced SQL statement into one unified SQL payload.
    pub(in crate::db) fn execute_compiled_sql<E>(
        &self,
        compiled: &CompiledSqlCommand,
    ) -> Result<SqlStatementResult, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let (result, _) = self.execute_compiled_sql_with_cache_attribution::<E>(compiled)?;

        Ok(result)
    }

    // Split scalar SELECT execution into plan construction and runtime work so
    // perf tooling can show the planner cost separately from row execution.
    #[cfg(feature = "perf-attribution")]
    fn execute_structural_sql_projection_with_phase_attribution(
        &self,
        query: StructuralQuery,
        authority: EntityAuthority,
        compiled_cache_key: Option<&SqlCompiledCommandCacheKey>,
    ) -> Result<
        (
            SqlProjectionPayload,
            SqlCacheAttribution,
            SqlExecutePhaseAttribution,
        ),
        QueryError,
    > {
        let (planner_local_instructions, prepared) = measure_execute_phase(|| {
            self.prepare_structural_sql_projection_execution(query, authority, compiled_cache_key)
        });
        let (columns, fixed_scales, plan, cache_attribution) = prepared?;

        let (executor_local_instructions, payload) = measure_execute_phase(move || {
            let projected =
                execute_sql_projection_rows_for_canister(&self.db, self.debug, authority, plan)
                    .map_err(QueryError::execute)?;
            let (rows, row_count) = projected.into_parts();

            Ok::<SqlProjectionPayload, QueryError>(SqlProjectionPayload::new(
                columns,
                fixed_scales,
                rows,
                row_count,
            ))
        });
        let payload = payload?;

        Ok((
            payload,
            cache_attribution,
            SqlExecutePhaseAttribution {
                planner_local_instructions,
                executor_local_instructions,
            },
        ))
    }

    // Split grouped SELECT execution at the same session boundary: first plan
    // selection/cache resolution, then grouped runtime plus result packaging.
    #[cfg(feature = "perf-attribution")]
    fn execute_structural_sql_grouped_statement_select_with_phase_attribution(
        &self,
        query: StructuralQuery,
        authority: EntityAuthority,
        compiled_cache_key: Option<&SqlCompiledCommandCacheKey>,
    ) -> Result<
        (
            SqlStatementResult,
            SqlCacheAttribution,
            SqlExecutePhaseAttribution,
        ),
        QueryError,
    > {
        let (planner_local_instructions, prepared) = measure_execute_phase(|| {
            self.planned_sql_select_with_visibility(&query, authority, compiled_cache_key)
        });
        let (entry, cache_attribution) = prepared?;
        let (plan, columns, _) = entry.into_parts();

        let (executor_local_instructions, statement_result) = measure_execute_phase(move || {
            let page =
                execute_initial_grouped_rows_for_canister(&self.db, self.debug, authority, plan)
                    .map_err(QueryError::execute)?;
            let next_cursor = page
                .next_cursor
                .map(|cursor| {
                    let Some(token) = cursor.as_grouped() else {
                        return Err(QueryError::grouped_paged_emitted_scalar_continuation());
                    };

                    token.encode_hex().map_err(|err| {
                        QueryError::serialize_internal(format!(
                            "failed to serialize grouped continuation cursor: {err}"
                        ))
                    })
                })
                .transpose()?;

            Ok::<SqlStatementResult, QueryError>(
                crate::db::session::sql::projection::grouped_sql_statement_result(
                    columns,
                    page.rows,
                    next_cursor,
                ),
            )
        });
        let statement_result = statement_result?;

        Ok((
            statement_result,
            cache_attribution,
            SqlExecutePhaseAttribution {
                planner_local_instructions,
                executor_local_instructions,
            },
        ))
    }

    // Keep one perf-only execution entrypoint that returns cache attribution
    // together with planner/runtime instruction splits for shell-facing tools.
    #[cfg(feature = "perf-attribution")]
    #[expect(
        clippy::too_many_lines,
        reason = "the compiled SQL execution matrix keeps every statement family on one explicit perf-attributed seam"
    )]
    pub(in crate::db) fn execute_compiled_sql_with_phase_attribution<E>(
        &self,
        compiled: &CompiledSqlCommand,
    ) -> Result<
        (
            SqlStatementResult,
            SqlCacheAttribution,
            SqlExecutePhaseAttribution,
        ),
        QueryError,
    >
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let authority = EntityAuthority::for_type::<E>();

        match compiled {
            CompiledSqlCommand::Select {
                query,
                compiled_cache_key,
            } => {
                if query.has_grouping() {
                    return self
                        .execute_structural_sql_grouped_statement_select_with_phase_attribution(
                            query.clone(),
                            authority,
                            compiled_cache_key.as_ref(),
                        );
                }

                let (payload, cache_attribution, phase_attribution) = self
                    .execute_structural_sql_projection_with_phase_attribution(
                        query.clone(),
                        authority,
                        compiled_cache_key.as_ref(),
                    )?;

                Ok((
                    payload.into_statement_result(),
                    cache_attribution,
                    phase_attribution,
                ))
            }
            CompiledSqlCommand::Delete { query, statement } => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    self.execute_sql_delete_statement::<E>(query.clone(), statement)
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::GlobalAggregate {
                command,
                label_override,
            } => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    self.execute_global_aggregate_statement_for_authority(
                        command.clone(),
                        authority,
                        label_override.clone(),
                    )
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::Explain(lowered) => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    if let Some(explain) =
                        self.explain_lowered_sql_execution_for_authority(lowered, authority)?
                    {
                        return Ok::<SqlStatementResult, QueryError>(SqlStatementResult::Explain(
                            explain,
                        ));
                    }

                    self.explain_lowered_sql_for_authority(lowered, authority)
                        .map(SqlStatementResult::Explain)
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::Insert(statement) => {
                let (execute_local_instructions, result) =
                    measure_execute_phase(|| self.execute_sql_insert_statement::<E>(statement));
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::Update(statement) => {
                let (execute_local_instructions, result) =
                    measure_execute_phase(|| self.execute_sql_update_statement::<E>(statement));
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::DescribeEntity => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    Ok::<SqlStatementResult, QueryError>(SqlStatementResult::Describe(
                        self.describe_entity::<E>(),
                    ))
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::ShowIndexesEntity => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    Ok::<SqlStatementResult, QueryError>(SqlStatementResult::ShowIndexes(
                        self.show_indexes::<E>(),
                    ))
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::ShowColumnsEntity => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    Ok::<SqlStatementResult, QueryError>(SqlStatementResult::ShowColumns(
                        self.show_columns::<E>(),
                    ))
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
            CompiledSqlCommand::ShowEntities => {
                let (execute_local_instructions, result) = measure_execute_phase(|| {
                    Ok::<SqlStatementResult, QueryError>(SqlStatementResult::ShowEntities(
                        self.show_entities(),
                    ))
                });
                let result = result?;

                Ok((
                    result,
                    SqlCacheAttribution::default(),
                    SqlExecutePhaseAttribution::from_execute_total(execute_local_instructions),
                ))
            }
        }
    }

    pub(in crate::db) fn execute_compiled_sql_with_cache_attribution<E>(
        &self,
        compiled: &CompiledSqlCommand,
    ) -> Result<(SqlStatementResult, SqlCacheAttribution), QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let authority = EntityAuthority::for_type::<E>();

        match compiled {
            CompiledSqlCommand::Select {
                query,
                compiled_cache_key,
            } => {
                if query.has_grouping() {
                    return self.execute_structural_sql_grouped_statement_select_core(
                        query.clone(),
                        authority,
                        compiled_cache_key.as_ref(),
                    );
                }

                let (payload, cache_attribution) = self.execute_structural_sql_projection(
                    query.clone(),
                    authority,
                    compiled_cache_key.as_ref(),
                )?;

                Ok((payload.into_statement_result(), cache_attribution))
            }
            CompiledSqlCommand::Delete { query, statement } => self
                .execute_sql_delete_statement::<E>(query.clone(), statement)
                .map(|result| (result, SqlCacheAttribution::default())),
            CompiledSqlCommand::GlobalAggregate {
                command,
                label_override,
            } => self
                .execute_global_aggregate_statement_for_authority(
                    command.clone(),
                    authority,
                    label_override.clone(),
                )
                .map(|result| (result, SqlCacheAttribution::default())),
            CompiledSqlCommand::Explain(lowered) => {
                if let Some(explain) =
                    self.explain_lowered_sql_execution_for_authority(lowered, authority)?
                {
                    return Ok((
                        SqlStatementResult::Explain(explain),
                        SqlCacheAttribution::default(),
                    ));
                }

                self.explain_lowered_sql_for_authority(lowered, authority)
                    .map(SqlStatementResult::Explain)
                    .map(|result| (result, SqlCacheAttribution::default()))
            }
            CompiledSqlCommand::Insert(statement) => self
                .execute_sql_insert_statement::<E>(statement)
                .map(|result| (result, SqlCacheAttribution::default())),
            CompiledSqlCommand::Update(statement) => self
                .execute_sql_update_statement::<E>(statement)
                .map(|result| (result, SqlCacheAttribution::default())),
            CompiledSqlCommand::DescribeEntity => Ok((
                SqlStatementResult::Describe(self.describe_entity::<E>()),
                SqlCacheAttribution::default(),
            )),
            CompiledSqlCommand::ShowIndexesEntity => Ok((
                SqlStatementResult::ShowIndexes(self.show_indexes::<E>()),
                SqlCacheAttribution::default(),
            )),
            CompiledSqlCommand::ShowColumnsEntity => Ok((
                SqlStatementResult::ShowColumns(self.show_columns::<E>()),
                SqlCacheAttribution::default(),
            )),
            CompiledSqlCommand::ShowEntities => Ok((
                SqlStatementResult::ShowEntities(self.show_entities()),
                SqlCacheAttribution::default(),
            )),
        }
    }

    /// Compile and then execute one parsed reduced SQL statement into one
    /// unified SQL payload for session-owned tests.
    #[cfg(test)]
    pub(in crate::db) fn execute_sql_statement_inner<E>(
        &self,
        sql_statement: &crate::db::sql::parser::SqlStatement,
    ) -> Result<SqlStatementResult, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let compiled = Self::compile_sql_statement_inner::<E>(sql_statement)?;

        self.execute_compiled_sql::<E>(&compiled)
    }
}