icydb-core 0.264.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::db::query::preparation::PreparationWork;
use crate::db::{
    query::plan::{
        GroupField,
        expr::{Alias, Expr, FieldId, ProjectionField, ProjectionSelection},
    },
    schema::SchemaInfo,
    sql::{
        identifier::split_qualified_identifier,
        lowering::{
            AnalyzedLoweredExpr, LoweredExprAnalysis, SqlLoweringError,
            aggregate::SqlAggregateCallInterner,
            expr::{SqlExprPhase, lower_sql_expr},
            select::order::LoweredSqlOrderTerm,
        },
        parser::{SqlAggregateCall, SqlProjection, SqlSelectItem},
    },
};
use icydb_diagnostic_code::{DiagnosticExecutionBudgetResource as Resource, QueryFieldRole};

///
/// LoweredSqlProjectionSelection
///
/// SQL-local projection wrapper that keeps expression analyses beside lowered
/// projection fields until schema-bound SQL capability validation consumes
/// them.
///

#[derive(Clone, Debug)]
pub(super) struct LoweredSqlProjectionSelection {
    selection: ProjectionSelection,
    expr_analyses: Vec<LoweredExprAnalysis>,
}

impl LoweredSqlProjectionSelection {
    #[must_use]
    pub(super) const fn all() -> Self {
        Self {
            selection: ProjectionSelection::All,
            expr_analyses: Vec::new(),
        }
    }

    #[must_use]
    pub(super) const fn fields(fields: Vec<FieldId>) -> Self {
        Self {
            selection: ProjectionSelection::Fields(fields),
            expr_analyses: Vec::new(),
        }
    }

    #[must_use]
    pub(super) fn exprs(fields: Vec<ProjectionField>, analyses: Vec<LoweredExprAnalysis>) -> Self {
        debug_assert_eq!(
            fields.len(),
            analyses.len(),
            "lowered SQL projection analysis must stay aligned with projection fields",
        );
        Self {
            selection: ProjectionSelection::Exprs(fields),
            expr_analyses: analyses,
        }
    }

    #[must_use]
    pub(super) const fn selection(&self) -> &ProjectionSelection {
        &self.selection
    }

    #[must_use]
    pub(super) const fn expr_analyses(&self) -> &[LoweredExprAnalysis] {
        self.expr_analyses.as_slice()
    }

    #[must_use]
    pub(super) fn into_selection(self) -> ProjectionSelection {
        self.selection
    }

    fn is_grouped_canonical_identity(&self, group_by: &[String]) -> bool {
        matches!(
            &self.selection,
            ProjectionSelection::Exprs(fields)
                if grouped_projection_is_canonical_identity(fields.as_slice(), group_by)
        )
    }
}

///
/// LoweredGroupedProjection
///
/// SQL-local grouped projection artifact that keeps the projection and the
/// first-seen unique aggregate calls from the same analyzed expression pass.
///

#[derive(Clone, Debug)]
pub(super) struct LoweredGroupedProjection {
    selection: LoweredSqlProjectionSelection,
    aggregate_calls: Vec<SqlAggregateCall>,
}

impl LoweredGroupedProjection {
    #[must_use]
    pub(super) const fn aggregate_calls(&self) -> &[SqlAggregateCall] {
        self.aggregate_calls.as_slice()
    }

    #[must_use]
    pub(super) fn into_projection_selection(
        self,
        allow_identity_fast_path: bool,
        group_by: &[String],
    ) -> LoweredSqlProjectionSelection {
        if allow_identity_fast_path && self.selection.is_grouped_canonical_identity(group_by) {
            LoweredSqlProjectionSelection::all()
        } else {
            self.selection
        }
    }
}

pub(super) fn lower_scalar_projection_selection(
    projection: SqlProjection,
    projection_aliases: &[Option<String>],
    work: &PreparationWork<'_>,
) -> Result<LoweredSqlProjectionSelection, SqlLoweringError> {
    let SqlProjection::Items(items) = projection else {
        return Ok(LoweredSqlProjectionSelection::all());
    };

    if let Some(field_ids) = direct_scalar_field_selection(items.as_slice(), projection_aliases) {
        return Ok(LoweredSqlProjectionSelection::fields(field_ids));
    }

    let mut fields = Vec::with_capacity(items.len());
    let mut projection_facts = Vec::with_capacity(items.len());
    for (index, item) in items.into_iter().enumerate() {
        let analyzed = lower_analyzed_select_item_expr(&item, SqlExprPhase::Scalar, work)?;
        let (expr, expr_facts) = analyzed.into_parts();
        fields.push(ProjectionField::Scalar {
            expr,
            alias: projection_aliases
                .get(index)
                .and_then(Option::as_deref)
                .map(Alias::new),
        });
        projection_facts.push(expr_facts);
    }

    Ok(LoweredSqlProjectionSelection::exprs(
        fields,
        projection_facts,
    ))
}

pub(super) fn lower_grouped_projection(
    projection: SqlProjection,
    projection_aliases: &[Option<String>],
    group_by: &[String],
    schema: &SchemaInfo,
    work: &PreparationWork<'_>,
) -> Result<LoweredGroupedProjection, SqlLoweringError> {
    if group_by.is_empty() {
        return Err(SqlLoweringError::unsupported_select_group_by());
    }

    let SqlProjection::Items(items) = projection else {
        return Err(SqlLoweringError::grouped_projection_requires_explicit_list());
    };
    // Validate every declared key, even if no projected expression references
    // it. Retained execution keys belong to structural planning, not this proof.
    for field in group_by {
        work.charge(Resource::PredicateExpressionSteps, 1 + field.len() as u64)?;
        if GroupField::accepted_kind_for_label(schema, field).is_none() {
            return Err(SqlLoweringError::unknown_field(
                QueryFieldRole::GroupBy,
                field,
            ));
        }
    }

    let mut seen_aggregate = false;
    let mut fields = Vec::with_capacity(items.len());
    let mut projection_facts = Vec::with_capacity(items.len());
    let mut aggregate_calls = Vec::new();
    let mut aggregate_call_interner = SqlAggregateCallInterner::new();

    for (index, item) in items.into_iter().enumerate() {
        let analyzed = lower_analyzed_select_item_expr(&item, SqlExprPhase::PostAggregate, work)?;
        let expr_facts = analyzed.analysis();
        let contains_aggregate = expr_facts.contains_aggregate();
        if seen_aggregate && !contains_aggregate {
            return Err(SqlLoweringError::grouped_projection_scalar_after_aggregate(
                index,
            ));
        }
        validate_grouped_projection_expr(index, group_by, schema, expr_facts, work)?;
        seen_aggregate |= contains_aggregate;
        if contains_aggregate {
            aggregate_call_interner.extend_select_item(&mut aggregate_calls, &item)?;
        }

        let (expr, expr_facts) = analyzed.into_parts();
        fields.push(ProjectionField::Scalar {
            expr,
            alias: projection_aliases
                .get(index)
                .and_then(Option::as_deref)
                .map(Alias::new),
        });
        projection_facts.push(expr_facts);
    }

    if !seen_aggregate {
        return Err(SqlLoweringError::grouped_projection_requires_aggregate());
    }

    Ok(LoweredGroupedProjection {
        selection: LoweredSqlProjectionSelection::exprs(fields, projection_facts),
        aggregate_calls,
    })
}

// Validate one grouped projection expression against grouped-key authority
// while preserving specific unknown-field diagnostics.
fn validate_grouped_projection_expr(
    index: usize,
    group_fields: &[String],
    schema: &SchemaInfo,
    analysis: &LoweredExprAnalysis,
    work: &PreparationWork<'_>,
) -> Result<(), SqlLoweringError> {
    if let Some(field) = analysis.first_unknown_field_for_schema(schema) {
        return Err(SqlLoweringError::unknown_field(
            QueryFieldRole::Projection,
            field,
        ));
    }
    if !analysis.references_only_group_fields(group_fields, work)? {
        return Err(SqlLoweringError::grouped_projection_references_non_group_field(index));
    }

    Ok(())
}

// Preserve the older grouped `ProjectionSelection::All` fast path only for
// the canonical identity shape where projected grouped fields match `GROUP BY`
// exactly and aggregate terminals follow in declaration order.
fn grouped_projection_is_canonical_identity(
    fields: &[ProjectionField],
    group_by: &[String],
) -> bool {
    if fields.len() < group_by.len() {
        return false;
    }

    let Some((group_fields, aggregate_fields)) = fields.split_at_checked(group_by.len()) else {
        return false;
    };

    group_fields
        .iter()
        .zip(group_by.iter())
        .all(|(field, group_by)| match field {
            ProjectionField::Scalar {
                expr: Expr::Field(field_id),
                alias: None,
            } => field_id.as_str() == group_by,
            ProjectionField::Scalar {
                expr: Expr::FieldPath(path),
                alias: None,
            } => path.path_spec().matches_dotted_label(group_by),
            ProjectionField::Scalar { .. } => false,
        })
        && aggregate_fields.iter().all(|field| {
            matches!(
                field,
                ProjectionField::Scalar {
                    expr: Expr::Aggregate(_),
                    alias: None,
                }
            )
        })
}

// Enforce the SQL DISTINCT rule at lowering time: every ORDER BY term must be
// fully expressible as a function of the outward projected distinct tuple
// rather than from hidden base-row fields.
pub(super) fn validate_distinct_order_terms_against_projection(
    projection: &ProjectionSelection,
    order_by: &[LoweredSqlOrderTerm],
    schema: &SchemaInfo,
) -> Result<(), SqlLoweringError> {
    if order_by
        .iter()
        .all(|term| distinct_order_term_is_derivable_from_projection(projection, term, schema))
    {
        return Ok(());
    }

    Err(SqlLoweringError::distinct_order_by_requires_projected_tuple())
}

// Keep DISTINCT ORDER BY derivation intentionally narrow:
// - exact projected expressions are always admissible
// - otherwise the term may reference only direct projected fields
// - `SELECT DISTINCT *` exposes the full entity field set
// This is a field-level proof only; it does not admit hidden payloads or a
// broader symbolic derivation model.
fn distinct_order_term_is_derivable_from_projection(
    projection: &ProjectionSelection,
    order_term: &LoweredSqlOrderTerm,
    schema: &SchemaInfo,
) -> bool {
    match projection {
        ProjectionSelection::All => {
            let projected_fields = schema.field_names_in_slot_order();

            order_term
                .analysis
                .references_only_direct_fields(projected_fields.as_slice())
        }
        ProjectionSelection::Fields(field_ids) => {
            let projected_fields = field_ids.iter().map(FieldId::as_str).collect::<Vec<_>>();

            order_term
                .analysis
                .references_only_direct_fields(projected_fields.as_slice())
        }
        ProjectionSelection::Exprs(fields) => {
            if fields.iter().any(|field| match field {
                ProjectionField::Scalar { expr, .. } => expr == &order_term.expr,
            }) {
                return true;
            }

            let projected_fields = fields
                .iter()
                .filter_map(ProjectionField::direct_field_name)
                .collect::<Vec<_>>();

            order_term
                .analysis
                .references_only_direct_fields(projected_fields.as_slice())
        }
    }
}

pub(super) fn direct_scalar_field_selection(
    items: &[SqlSelectItem],
    projection_aliases: &[Option<String>],
) -> Option<Vec<FieldId>> {
    if !projection_aliases.iter().all(Option::is_none) {
        return None;
    }

    items
        .iter()
        .map(|item| match item {
            SqlSelectItem::Field(field) if split_qualified_identifier(field).is_none() => {
                Some(FieldId::new(field.clone()))
            }
            SqlSelectItem::Field(_) | SqlSelectItem::Aggregate(_) | SqlSelectItem::Expr(_) => None,
        })
        .collect()
}

pub(in crate::db::sql::lowering) fn lower_select_item_expr(
    item: &SqlSelectItem,
    phase: SqlExprPhase,
    work: &PreparationWork<'_>,
) -> Result<Expr, SqlLoweringError> {
    lower_sql_expr(
        &crate::db::sql::parser::SqlExpr::from_select_item(item),
        phase,
        work,
    )
}

pub(in crate::db::sql::lowering) fn lower_analyzed_select_item_expr(
    item: &SqlSelectItem,
    phase: SqlExprPhase,
    work: &PreparationWork<'_>,
) -> Result<AnalyzedLoweredExpr, SqlLoweringError> {
    Ok(AnalyzedLoweredExpr::new(lower_select_item_expr(
        item, phase, work,
    )?))
}

#[cfg(test)]
mod tests {
    use crate::db::{
        query::plan::expr::{Alias, Expr, FieldPath, ProjectionField},
        sql::lowering::select::projection::grouped_projection_is_canonical_identity,
    };

    #[test]
    fn grouped_path_identity_preserves_exact_labels_and_alias_policy() {
        let mut fields = [ProjectionField::Scalar {
            expr: Expr::FieldPath(FieldPath::new("profile", vec!["city".into()])),
            alias: None,
        }];
        assert!(grouped_projection_is_canonical_identity(
            &fields,
            &["profile.city".into()],
        ));
        for label in ["profile", "profile.city.code", "profile.city."] {
            assert!(!grouped_projection_is_canonical_identity(
                &fields,
                &[label.into()],
            ));
        }
        let ProjectionField::Scalar { alias, .. } = &mut fields[0];
        *alias = Some(Alias::new("city"));
        assert!(!grouped_projection_is_canonical_identity(
            &fields,
            &["profile.city".into()],
        ));
    }
}