icydb-core 0.98.1

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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Module: db::sql::lowering
//! Responsibility: reduced SQL statement lowering into canonical query intent.
//! Does not own: SQL tokenization/parsing, planner validation policy, or executor semantics.
//! Boundary: frontend-only translation from parsed SQL statement contracts to `Query<E>`.

mod aggregate;
mod analysis;
mod expr;
mod normalize;
mod predicate;
mod prepare;
mod select;

///
/// TESTS
///

#[cfg(test)]
mod tests;

#[cfg(test)]
use crate::{
    db::{predicate::MissingRowPolicy, query::intent::Query},
    traits::EntityKind,
};
use crate::{
    db::{
        query::intent::QueryError,
        sql::parser::{SqlExplainMode, SqlStatement},
    },
    value::Value,
};
use thiserror::Error as ThisError;

pub(in crate::db::sql::lowering) use aggregate::LoweredSqlGlobalAggregateCommand;
pub(in crate::db) use aggregate::compile_sql_global_aggregate_command_core_from_prepared;
pub(in crate::db) use aggregate::is_sql_global_aggregate_statement;
#[cfg(test)]
pub(crate) use aggregate::{
    PreparedSqlScalarAggregateDescriptorShape, PreparedSqlScalarAggregateDomain,
    PreparedSqlScalarAggregateEmptySetBehavior, PreparedSqlScalarAggregateOrderingRequirement,
    PreparedSqlScalarAggregateRowSource, SqlGlobalAggregateCommand,
    compile_sql_global_aggregate_command,
};
pub(crate) use aggregate::{
    PreparedSqlScalarAggregateRuntimeDescriptor, PreparedSqlScalarAggregateStrategy,
    SqlGlobalAggregateCommandCore, bind_lowered_sql_explain_global_aggregate_structural,
};
pub(in crate::db::sql::lowering) use analysis::{LoweredExprAnalysis, analyze_lowered_expr};
pub(in crate::db) use predicate::lower_sql_where_expr;
pub(crate) use prepare::{lower_sql_command_from_prepared_statement, prepare_sql_statement};
pub(in crate::db::sql::lowering) use select::apply_lowered_base_query_shape;
#[cfg(test)]
pub(in crate::db) use select::apply_lowered_select_shape;
pub(crate) use select::{LoweredBaseQueryShape, LoweredSelectShape};
pub(in crate::db) use select::{
    bind_lowered_sql_query, bind_lowered_sql_query_structural,
    bind_lowered_sql_select_query_structural, canonicalize_sql_predicate_for_model,
    canonicalize_strict_sql_literal_for_kind,
};

///
/// LoweredSqlCommand
///
/// Generic-free SQL command shape after reduced SQL parsing and entity-route
/// normalization.
/// This keeps statement-shape lowering shared across entities before typed
/// `Query<E>` binding happens at the execution boundary.
///
#[derive(Clone, Debug)]
pub struct LoweredSqlCommand(pub(in crate::db::sql::lowering) LoweredSqlCommandInner);

#[derive(Clone, Debug)]
pub(in crate::db::sql::lowering) enum LoweredSqlCommandInner {
    Query(LoweredSqlQuery),
    Explain {
        mode: SqlExplainMode,
        query: LoweredSqlQuery,
    },
    ExplainGlobalAggregate {
        mode: SqlExplainMode,
        command: LoweredSqlGlobalAggregateCommand,
    },
    DescribeEntity,
    ShowIndexesEntity,
    ShowColumnsEntity,
    ShowEntities,
}

///
/// SqlCommand
///
/// Test-only typed SQL command shell over the shared lowered SQL surface.
/// Runtime dispatch now consumes `LoweredSqlCommand` directly, but lowering
/// tests still validate typed binding behavior on this local envelope.
///
#[cfg(test)]
#[derive(Debug)]
pub(crate) enum SqlCommand<E: EntityKind> {
    Query(Query<E>),
    GlobalAggregate(SqlGlobalAggregateCommand<E>),
    Explain {
        mode: SqlExplainMode,
        query: Query<E>,
    },
    ExplainGlobalAggregate {
        mode: SqlExplainMode,
        command: SqlGlobalAggregateCommand<E>,
    },
    DescribeEntity,
    ShowIndexesEntity,
    ShowColumnsEntity,
    ShowEntities,
}

impl LoweredSqlCommand {
    #[must_use]
    #[allow(dead_code)]
    pub(in crate::db) const fn query(&self) -> Option<&LoweredSqlQuery> {
        match &self.0 {
            LoweredSqlCommandInner::Query(query) => Some(query),
            LoweredSqlCommandInner::Explain { .. }
            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
            | LoweredSqlCommandInner::DescribeEntity
            | LoweredSqlCommandInner::ShowIndexesEntity
            | LoweredSqlCommandInner::ShowColumnsEntity
            | LoweredSqlCommandInner::ShowEntities => None,
        }
    }

    #[must_use]
    pub(in crate::db) fn into_query(self) -> Option<LoweredSqlQuery> {
        match self.0 {
            LoweredSqlCommandInner::Query(query) => Some(query),
            LoweredSqlCommandInner::Explain { .. }
            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
            | LoweredSqlCommandInner::DescribeEntity
            | LoweredSqlCommandInner::ShowIndexesEntity
            | LoweredSqlCommandInner::ShowColumnsEntity
            | LoweredSqlCommandInner::ShowEntities => None,
        }
    }

    #[must_use]
    pub(in crate::db) const fn explain_query(&self) -> Option<(SqlExplainMode, &LoweredSqlQuery)> {
        match &self.0 {
            LoweredSqlCommandInner::Explain { mode, query } => Some((*mode, query)),
            LoweredSqlCommandInner::Query(_)
            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
            | LoweredSqlCommandInner::DescribeEntity
            | LoweredSqlCommandInner::ShowIndexesEntity
            | LoweredSqlCommandInner::ShowColumnsEntity
            | LoweredSqlCommandInner::ShowEntities => None,
        }
    }
}

///
/// LoweredSqlQuery
///
/// Generic-free executable SQL query shape prepared before typed query binding.
/// Select and delete lowering stay shared until the final `Query<E>` build.
///
#[derive(Clone, Debug)]
pub(crate) enum LoweredSqlQuery {
    Select(LoweredSelectShape),
    Delete(LoweredBaseQueryShape),
}

///
/// SqlLoweringError
///
/// SQL frontend lowering failures before planner validation/execution.
///
#[derive(Debug, ThisError)]
pub(crate) enum SqlLoweringError {
    #[error("{0}")]
    Parse(#[from] crate::db::sql::parser::SqlParseError),

    #[error("{0}")]
    Query(Box<QueryError>),

    #[error("SQL entity '{sql_entity}' does not match requested entity type '{expected_entity}'")]
    EntityMismatch {
        sql_entity: String,
        expected_entity: &'static str,
    },

    #[error(
        "unsupported SQL SELECT projection; supported forms are SELECT *, field lists, global aggregate terminal lists, or grouped aggregate shapes"
    )]
    UnsupportedSelectProjection,

    #[error("unsupported SQL SELECT DISTINCT")]
    UnsupportedSelectDistinct,

    #[error("SELECT DISTINCT ORDER BY terms must be derivable from the projected distinct tuple")]
    DistinctOrderByRequiresProjectedTuple,

    #[error(
        "unsupported global aggregate SQL projection; supported forms are aggregate projections such as COUNT(*), SUM(field), AVG(expr), or scalar wrappers over aggregate results"
    )]
    UnsupportedGlobalAggregateProjection,

    #[error("global aggregate SQL does not support GROUP BY")]
    GlobalAggregateDoesNotSupportGroupBy,

    #[error("unsupported SQL GROUP BY projection shape")]
    UnsupportedSelectGroupBy,

    #[error("grouped SELECT requires an explicit projection list")]
    GroupedProjectionRequiresExplicitList,

    #[error("grouped SELECT projection must include at least one aggregate expression")]
    GroupedProjectionRequiresAggregate,

    #[error(
        "grouped projection expression at index={index} references fields outside GROUP BY keys"
    )]
    GroupedProjectionReferencesNonGroupField { index: usize },

    #[error(
        "grouped projection expression at index={index} appears after aggregate expressions started"
    )]
    GroupedProjectionScalarAfterAggregate { index: usize },

    #[error("HAVING requires GROUP BY")]
    HavingRequiresGroupBy,

    #[error("unsupported SQL HAVING shape")]
    UnsupportedSelectHaving,

    #[error("aggregate input expressions are not executable in this release")]
    UnsupportedAggregateInputExpressions,

    #[error("unsupported SQL WHERE expression shape")]
    UnsupportedWhereExpression,

    #[error("unknown field '{field}'")]
    UnknownField { field: String },

    #[error("{message}")]
    UnsupportedParameterPlacement { message: String },

    #[error("query-lane lowering reached a non query-compatible statement")]
    UnexpectedQueryLaneStatement,
}

impl SqlLoweringError {
    /// Construct one entity-mismatch SQL lowering error.
    fn entity_mismatch(sql_entity: impl Into<String>, expected_entity: &'static str) -> Self {
        Self::EntityMismatch {
            sql_entity: sql_entity.into(),
            expected_entity,
        }
    }

    /// Construct one unsupported SELECT projection SQL lowering error.
    const fn unsupported_select_projection() -> Self {
        Self::UnsupportedSelectProjection
    }

    /// Construct one query-lane lowering misuse error.
    pub(crate) const fn unexpected_query_lane_statement() -> Self {
        Self::UnexpectedQueryLaneStatement
    }

    /// Construct one unsupported SELECT DISTINCT SQL lowering error.
    const fn unsupported_select_distinct() -> Self {
        Self::UnsupportedSelectDistinct
    }

    /// Construct one DISTINCT ORDER BY projection-derivability SQL lowering error.
    const fn distinct_order_by_requires_projected_tuple() -> Self {
        Self::DistinctOrderByRequiresProjectedTuple
    }

    /// Construct one unsupported global aggregate projection SQL lowering error.
    const fn unsupported_global_aggregate_projection() -> Self {
        Self::UnsupportedGlobalAggregateProjection
    }

    /// Construct one unsupported SQL WHERE expression lowering error.
    pub(crate) const fn unsupported_where_expression() -> Self {
        Self::UnsupportedWhereExpression
    }

    /// Construct one global-aggregate-GROUP-BY SQL lowering error.
    const fn global_aggregate_does_not_support_group_by() -> Self {
        Self::GlobalAggregateDoesNotSupportGroupBy
    }

    /// Construct one unsupported SELECT GROUP BY shape SQL lowering error.
    const fn unsupported_select_group_by() -> Self {
        Self::UnsupportedSelectGroupBy
    }

    /// Construct one grouped-projection-explicit-list SQL lowering error.
    const fn grouped_projection_requires_explicit_list() -> Self {
        Self::GroupedProjectionRequiresExplicitList
    }

    /// Construct one grouped-projection-missing-aggregate SQL lowering error.
    const fn grouped_projection_requires_aggregate() -> Self {
        Self::GroupedProjectionRequiresAggregate
    }

    /// Construct one grouped projection non-group-field SQL lowering error.
    const fn grouped_projection_references_non_group_field(index: usize) -> Self {
        Self::GroupedProjectionReferencesNonGroupField { index }
    }

    /// Construct one grouped projection scalar-after-aggregate SQL lowering error.
    const fn grouped_projection_scalar_after_aggregate(index: usize) -> Self {
        Self::GroupedProjectionScalarAfterAggregate { index }
    }

    /// Construct one HAVING-requires-GROUP-BY SQL lowering error.
    const fn having_requires_group_by() -> Self {
        Self::HavingRequiresGroupBy
    }

    /// Construct one unsupported SELECT HAVING shape SQL lowering error.
    const fn unsupported_select_having() -> Self {
        Self::UnsupportedSelectHaving
    }

    /// Construct one aggregate-input execution seam SQL lowering error.
    const fn unsupported_aggregate_input_expressions() -> Self {
        Self::UnsupportedAggregateInputExpressions
    }

    /// Construct one unknown-field SQL lowering error.
    pub(crate) fn unknown_field(field: impl Into<String>) -> Self {
        Self::UnknownField {
            field: field.into(),
        }
    }

    /// Construct one unsupported parameter placement SQL lowering error.
    pub(crate) fn unsupported_parameter_placement(
        index: Option<usize>,
        message: impl Into<String>,
    ) -> Self {
        let message = match index {
            Some(index) => format!("parameter slot ${index}: {}", message.into()),
            None => message.into(),
        };

        Self::UnsupportedParameterPlacement { message }
    }
}

impl From<QueryError> for SqlLoweringError {
    fn from(value: QueryError) -> Self {
        Self::Query(Box::new(value))
    }
}

///
/// PreparedSqlStatement
///
/// SQL statement envelope after entity-scope normalization and
/// entity-match validation for one target entity descriptor.
///
/// This pre-lowering contract is entity-agnostic and reusable across
/// dynamic SQL route branches before typed `Query<E>` binding.
///
#[derive(Clone, Debug)]
pub(crate) struct PreparedSqlStatement {
    pub(in crate::db::sql::lowering) statement: SqlStatement,
}

///
/// PreparedSqlParameterTypeFamily
///
/// Stable bind-time type family for one prepared SQL parameter slot.
/// This keeps v1 validation coarse and deterministic while the prepared SQL
/// surface remains restricted to compare-family value-insensitive positions.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum PreparedSqlParameterTypeFamily {
    Numeric,
    Text,
    Bool,
}

///
/// PreparedSqlParameterContract
///
/// Frozen bind contract for one prepared SQL parameter slot.
/// The contract is inferred once during prepare and reused unchanged for every
/// execution of the prepared SQL query shape.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct PreparedSqlParameterContract {
    index: usize,
    type_family: PreparedSqlParameterTypeFamily,
    null_allowed: bool,
    template_binding: Option<Value>,
}

impl PreparedSqlParameterContract {
    #[must_use]
    pub(in crate::db) const fn new(
        index: usize,
        type_family: PreparedSqlParameterTypeFamily,
        null_allowed: bool,
        template_binding: Option<Value>,
    ) -> Self {
        Self {
            index,
            type_family,
            null_allowed,
            template_binding,
        }
    }

    #[must_use]
    pub(in crate::db) const fn index(&self) -> usize {
        self.index
    }

    #[must_use]
    pub(in crate::db) const fn type_family(&self) -> PreparedSqlParameterTypeFamily {
        self.type_family
    }

    #[must_use]
    pub(in crate::db) const fn null_allowed(&self) -> bool {
        self.null_allowed
    }

    #[must_use]
    pub(in crate::db) const fn template_binding(&self) -> Option<&Value> {
        self.template_binding.as_ref()
    }
}

impl PreparedSqlStatement {
    /// Borrow one prepared SQL statement in its normalized parsed form.
    #[must_use]
    pub(in crate::db) const fn statement(&self) -> &SqlStatement {
        &self.statement
    }

    /// Consume one prepared SQL statement back into its normalized parsed form.
    #[must_use]
    pub(in crate::db) fn into_statement(self) -> SqlStatement {
        self.statement
    }

    /// Collect frozen parameter contracts from one prepared SQL statement.
    pub(in crate::db) fn parameter_contracts(
        &self,
        model: &'static crate::model::entity::EntityModel,
    ) -> Result<Vec<PreparedSqlParameterContract>, SqlLoweringError> {
        prepare::collect_prepared_statement_parameter_contracts(&self.statement, model)
    }

    /// Rebind one prepared SQL statement back to a literal-backed SQL shape.
    pub(in crate::db) fn bind_literals(
        &self,
        bindings: &[Value],
    ) -> Result<SqlStatement, QueryError> {
        prepare::bind_prepared_statement_literals(&self.statement, bindings)
    }
}

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

/// Parse and lower one SQL statement into canonical query intent for `E`.
#[cfg(test)]
pub(crate) fn compile_sql_command<E: EntityKind>(
    sql: &str,
    consistency: MissingRowPolicy,
) -> Result<SqlCommand<E>, SqlLoweringError> {
    let statement = crate::db::sql::parser::parse_sql(sql)?;
    let prepared = prepare_sql_statement(statement, E::MODEL.name())?;

    if aggregate::is_sql_global_aggregate_statement(prepared.statement()) {
        return Ok(SqlCommand::GlobalAggregate(
            aggregate::compile_sql_global_aggregate_command_from_prepared::<E>(
                prepared,
                consistency,
            )?,
        ));
    }

    let lowered = lower_sql_command_from_prepared_statement(prepared, E::MODEL)?;

    // Keep the test-only typed envelope local to the single public test entry
    // point instead of preserving a private forwarding chain.
    match lowered.0 {
        LoweredSqlCommandInner::Query(query) => Ok(SqlCommand::Query(bind_lowered_sql_query::<E>(
            query,
            consistency,
        )?)),
        LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command } => {
            Ok(SqlCommand::ExplainGlobalAggregate {
                mode,
                command: aggregate::bind_lowered_sql_global_aggregate_command::<E>(
                    command,
                    consistency,
                )?,
            })
        }
        LoweredSqlCommandInner::Explain { mode, query } => Ok(SqlCommand::Explain {
            mode,
            query: bind_lowered_sql_query::<E>(query, consistency)?,
        }),
        LoweredSqlCommandInner::DescribeEntity => Ok(SqlCommand::DescribeEntity),
        LoweredSqlCommandInner::ShowIndexesEntity => Ok(SqlCommand::ShowIndexesEntity),
        LoweredSqlCommandInner::ShowColumnsEntity => Ok(SqlCommand::ShowColumnsEntity),
        LoweredSqlCommandInner::ShowEntities => Ok(SqlCommand::ShowEntities),
    }
}

pub(crate) const fn lowered_sql_command_lane(command: &LoweredSqlCommand) -> LoweredSqlLaneKind {
    match command.0 {
        LoweredSqlCommandInner::Query(_) => LoweredSqlLaneKind::Query,
        LoweredSqlCommandInner::Explain { .. }
        | LoweredSqlCommandInner::ExplainGlobalAggregate { .. } => LoweredSqlLaneKind::Explain,
        LoweredSqlCommandInner::DescribeEntity => LoweredSqlLaneKind::Describe,
        LoweredSqlCommandInner::ShowIndexesEntity => LoweredSqlLaneKind::ShowIndexes,
        LoweredSqlCommandInner::ShowColumnsEntity => LoweredSqlLaneKind::ShowColumns,
        LoweredSqlCommandInner::ShowEntities => LoweredSqlLaneKind::ShowEntities,
    }
}