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
//! Module: db::sql::parser::statement
//! Responsibility: reduced SQL statement-shell parsing and clause-order diagnostics.
//! Does not own: projection item parsing, clause helper internals, or execution semantics.
//! Boundary: keeps statement entry routing and statement-local clause sequencing out of the parser root.

mod delete;
mod insert;
mod select;
mod update;

use crate::db::sql::identifier::{identifier_last_segment, normalize_identifier_to_scope};
use crate::db::{
    sql::parser::{
        Parser, SqlAggregateCall, SqlAssignment, SqlDeleteStatement, SqlDescribeStatement,
        SqlExplainMode, SqlExplainStatement, SqlExplainTarget, SqlExpr, SqlOrderTerm,
        SqlProjection, SqlReturningProjection, SqlSelectItem, SqlSelectStatement,
        SqlShowColumnsStatement, SqlShowEntitiesStatement, SqlShowIndexesStatement, SqlStatement,
        SqlUpdateStatement,
    },
    sql_shared::{Keyword, SqlParseError, TokenKind},
};

impl Parser {
    pub(super) fn parse_statement(&mut self) -> Result<SqlStatement, SqlParseError> {
        if self.eat_keyword(Keyword::Select) {
            return Ok(SqlStatement::Select(self.parse_select_statement()?));
        }
        if self.eat_keyword(Keyword::Delete) {
            return Ok(SqlStatement::Delete(self.parse_delete_statement()?));
        }
        if self.eat_keyword(Keyword::Insert) {
            return Ok(SqlStatement::Insert(self.parse_insert_statement()?));
        }
        if self.eat_keyword(Keyword::Update) {
            return Ok(SqlStatement::Update(self.parse_update_statement()?));
        }
        if self.eat_keyword(Keyword::Explain) {
            return Ok(SqlStatement::Explain(self.parse_explain_statement()?));
        }
        if self.eat_keyword(Keyword::Describe) {
            return Ok(SqlStatement::Describe(self.parse_describe_statement()?));
        }
        if self.eat_keyword(Keyword::Show) {
            return self.parse_show_statement();
        }

        if let Some(feature) = self.peek_unsupported_feature() {
            return Err(SqlParseError::unsupported_feature(feature));
        }

        Err(SqlParseError::expected(
            "one of SELECT, DELETE, INSERT, UPDATE, EXPLAIN, DESCRIBE, SHOW",
            self.peek_kind(),
        ))
    }

    // Classify one trailing token as a likely out-of-order clause mistake so
    // callers get an actionable parser diagnostic instead of generic EOI.
    pub(super) fn trailing_clause_order_error(
        &self,
        statement: &SqlStatement,
    ) -> Option<SqlParseError> {
        match statement {
            SqlStatement::Select(select) => self.select_clause_order_error(select),
            SqlStatement::Delete(delete) => self.delete_clause_order_error(delete),
            SqlStatement::Insert(_) => None,
            SqlStatement::Update(update) => self.update_clause_order_error(update),
            SqlStatement::Explain(explain) => match &explain.statement {
                SqlExplainTarget::Select(select) => self.select_clause_order_error(select),
                SqlExplainTarget::Delete(delete) => self.delete_clause_order_error(delete),
            },
            SqlStatement::Describe(_) => {
                Some(SqlParseError::unsupported_feature("DESCRIBE modifiers"))
            }
            SqlStatement::ShowIndexes(_) => {
                Some(SqlParseError::unsupported_feature("SHOW INDEXES modifiers"))
            }
            SqlStatement::ShowColumns(_) => {
                Some(SqlParseError::unsupported_feature("SHOW COLUMNS modifiers"))
            }
            SqlStatement::ShowEntities(_) => Some(SqlParseError::unsupported_feature(
                "SHOW ENTITIES modifiers",
            )),
        }
    }

    fn parse_show_statement(&mut self) -> Result<SqlStatement, SqlParseError> {
        if self.eat_keyword(Keyword::Indexes) {
            return Ok(SqlStatement::ShowIndexes(
                self.parse_show_indexes_statement()?,
            ));
        }
        if self.eat_keyword(Keyword::Columns) {
            return Ok(SqlStatement::ShowColumns(
                self.parse_show_columns_statement()?,
            ));
        }
        if self.eat_keyword(Keyword::Entities) {
            return Ok(SqlStatement::ShowEntities(SqlShowEntitiesStatement));
        }
        if self.eat_keyword(Keyword::Tables) {
            return Ok(SqlStatement::ShowEntities(SqlShowEntitiesStatement));
        }

        Err(SqlParseError::unsupported_feature(
            "SHOW commands beyond SHOW INDEXES/SHOW COLUMNS/SHOW ENTITIES/SHOW TABLES",
        ))
    }

    fn parse_explain_statement(&mut self) -> Result<SqlExplainStatement, SqlParseError> {
        let mode = if self.eat_keyword(Keyword::Execution) {
            SqlExplainMode::Execution
        } else if self.eat_keyword(Keyword::Json) {
            SqlExplainMode::Json
        } else {
            SqlExplainMode::Plan
        };

        let statement = if self.eat_keyword(Keyword::Select) {
            SqlExplainTarget::Select(self.parse_select_statement()?)
        } else if self.eat_keyword(Keyword::Delete) {
            SqlExplainTarget::Delete(self.parse_delete_statement()?)
        } else if let Some(feature) = self.peek_unsupported_feature() {
            return Err(SqlParseError::unsupported_feature(feature));
        } else {
            return Err(SqlParseError::expected(
                "one of SELECT, DELETE",
                self.peek_kind(),
            ));
        };

        Ok(SqlExplainStatement { mode, statement })
    }

    fn select_clause_order_error(&self, statement: &SqlSelectStatement) -> Option<SqlParseError> {
        if self.peek_keyword(Keyword::Order)
            && (statement.limit.is_some() || statement.offset.is_some())
        {
            return Some(SqlParseError::invalid_syntax(
                "ORDER BY must appear before LIMIT/OFFSET",
            ));
        }

        None
    }

    fn delete_clause_order_error(&self, statement: &SqlDeleteStatement) -> Option<SqlParseError> {
        if self.peek_keyword(Keyword::Order) && statement.limit.is_some() {
            return Some(SqlParseError::invalid_syntax(
                "ORDER BY must appear before LIMIT in DELETE",
            ));
        }

        None
    }

    fn update_clause_order_error(&self, statement: &SqlUpdateStatement) -> Option<SqlParseError> {
        if self.peek_keyword(Keyword::Order)
            && (statement.limit.is_some() || statement.offset.is_some())
        {
            return Some(SqlParseError::invalid_syntax(
                "ORDER BY must appear before LIMIT/OFFSET in UPDATE",
            ));
        }
        if self.peek_keyword(Keyword::Limit) && statement.offset.is_some() {
            return Some(SqlParseError::invalid_syntax(
                "LIMIT must appear before OFFSET in UPDATE",
            ));
        }

        None
    }

    pub(super) fn parse_optional_table_alias(&mut self) -> Result<Option<String>, SqlParseError> {
        if self.eat_keyword(Keyword::As) {
            return self.expect_identifier().map(Some);
        }

        if matches!(self.peek_kind(), Some(TokenKind::Identifier(_))) {
            let Some(TokenKind::Identifier(value)) = self.peek_kind() else {
                unreachable!();
            };
            if matches!(
                value.as_str().to_ascii_uppercase().as_str(),
                "SET" | "VALUES"
            ) {
                return Ok(None);
            }

            return self.expect_identifier().map(Some);
        }

        Ok(None)
    }

    fn parse_describe_statement(&mut self) -> Result<SqlDescribeStatement, SqlParseError> {
        let entity = self.expect_identifier()?;

        Ok(SqlDescribeStatement { entity })
    }

    fn parse_show_indexes_statement(&mut self) -> Result<SqlShowIndexesStatement, SqlParseError> {
        let entity = self.expect_identifier()?;

        Ok(SqlShowIndexesStatement { entity })
    }

    fn parse_show_columns_statement(&mut self) -> Result<SqlShowColumnsStatement, SqlParseError> {
        let entity = self.expect_identifier()?;

        Ok(SqlShowColumnsStatement { entity })
    }
}

// Normalize one admitted write-lane `RETURNING` field list back onto the
// canonical entity namespace after one single-table alias is admitted.
pub(super) fn normalize_returning_projection_for_table_alias(
    projection: SqlReturningProjection,
    entity: &str,
    alias: &str,
) -> SqlReturningProjection {
    match projection {
        SqlReturningProjection::All => SqlReturningProjection::All,
        SqlReturningProjection::Fields(fields) => SqlReturningProjection::Fields(
            normalize_identifier_list_for_table_alias(fields, entity, alias),
        ),
    }
}

// Build the identifier scope admitted for one single-table alias surface.
fn table_alias_scope(entity: &str, alias: &str) -> Vec<String> {
    let mut scope = vec![entity.to_string(), alias.to_string()];

    if let Some(last) = identifier_last_segment(entity) {
        scope.push(last.to_string());
    }

    scope
}

// Reduce one parsed field/projection tree back onto canonical entity-local
// field identifiers when the statement admitted one table alias.
pub(super) fn normalize_projection_for_table_alias(
    projection: SqlProjection,
    entity: &str,
    alias: &str,
) -> SqlProjection {
    let scope = table_alias_scope(entity, alias);

    match projection {
        SqlProjection::All => SqlProjection::All,
        SqlProjection::Items(items) => SqlProjection::Items(
            items
                .into_iter()
                .map(|item| match item {
                    SqlSelectItem::Field(field) => {
                        SqlSelectItem::Field(normalize_identifier_to_scope(field, scope.as_slice()))
                    }
                    SqlSelectItem::Aggregate(aggregate) => SqlSelectItem::Aggregate(
                        normalize_aggregate_call_for_table_alias(aggregate, scope.as_slice()),
                    ),
                    SqlSelectItem::Expr(expr) => SqlSelectItem::Expr(
                        normalize_sql_expr_for_table_alias(expr, scope.as_slice()),
                    ),
                })
                .collect(),
        ),
    }
}

// Reduce one parsed SQL expression tree onto canonical entity-local
// identifiers so alias-qualified clause expressions stay planner-neutral.
pub(super) fn normalize_sql_expr_for_entity_alias(
    expr: SqlExpr,
    entity: &str,
    alias: &str,
) -> SqlExpr {
    let scope = table_alias_scope(entity, alias);

    normalize_sql_expr_for_table_alias(expr, scope.as_slice())
}

// Reduce one parsed SQL expression list onto canonical entity-local
// identifiers so shared clause expression batches stay alias-neutral.
pub(super) fn normalize_sql_exprs_for_entity_alias(
    exprs: Vec<SqlExpr>,
    entity: &str,
    alias: &str,
) -> Vec<SqlExpr> {
    let scope = table_alias_scope(entity, alias);

    exprs
        .into_iter()
        .map(|expr| normalize_sql_expr_for_table_alias(expr, scope.as_slice()))
        .collect()
}

// Reduce one identifier list such as GROUP BY onto canonical entity-local
// field names for the admitted alias scope.
pub(super) fn normalize_identifier_list_for_table_alias(
    fields: Vec<String>,
    entity: &str,
    alias: &str,
) -> Vec<String> {
    let scope = table_alias_scope(entity, alias);

    fields
        .into_iter()
        .map(|field| normalize_identifier_to_scope(field, scope.as_slice()))
        .collect()
}

// Reduce one UPDATE assignment list onto canonical entity-local field names so
// single-table alias use stays parser-local before dispatch.
pub(super) fn normalize_assignments_for_table_alias(
    assignments: Vec<SqlAssignment>,
    entity: &str,
    alias: &str,
) -> Vec<SqlAssignment> {
    let scope = table_alias_scope(entity, alias);

    assignments
        .into_iter()
        .map(|assignment| SqlAssignment {
            field: normalize_identifier_to_scope(assignment.field, scope.as_slice()),
            value: assignment.value,
        })
        .collect()
}

// Reduce ORDER BY fields and the admitted LOWER/UPPER(field) forms onto
// canonical entity-local targets before lowering sees the statement.
pub(super) fn normalize_order_terms_for_table_alias(
    terms: Vec<SqlOrderTerm>,
    entity: &str,
    alias: &str,
) -> Vec<SqlOrderTerm> {
    let scope = table_alias_scope(entity, alias);

    terms
        .into_iter()
        .map(|term| SqlOrderTerm {
            field: normalize_sql_expr_for_table_alias(term.field, scope.as_slice()),
            direction: term.direction,
        })
        .collect()
}

fn normalize_aggregate_call_for_table_alias(
    aggregate: SqlAggregateCall,
    scope: &[String],
) -> SqlAggregateCall {
    SqlAggregateCall {
        kind: aggregate.kind,
        input: aggregate
            .input
            .map(|input| Box::new(normalize_sql_expr_for_table_alias(*input, scope))),
        filter_expr: aggregate
            .filter_expr
            .map(|expr| Box::new(normalize_sql_expr_for_table_alias(*expr, scope))),
        distinct: aggregate.distinct,
    }
}

pub(super) fn normalize_sql_expr_for_table_alias(expr: SqlExpr, scope: &[String]) -> SqlExpr {
    match expr {
        SqlExpr::Field(field) => SqlExpr::Field(normalize_identifier_to_scope(field, scope)),
        SqlExpr::Aggregate(aggregate) => {
            SqlExpr::Aggregate(normalize_aggregate_call_for_table_alias(aggregate, scope))
        }
        SqlExpr::Literal(value) => SqlExpr::Literal(value),
        SqlExpr::Param { index } => SqlExpr::Param { index },
        SqlExpr::Membership {
            expr,
            values,
            negated,
        } => SqlExpr::Membership {
            expr: Box::new(normalize_sql_expr_for_table_alias(*expr, scope)),
            values,
            negated,
        },
        SqlExpr::NullTest { expr, negated } => SqlExpr::NullTest {
            expr: Box::new(normalize_sql_expr_for_table_alias(*expr, scope)),
            negated,
        },
        SqlExpr::FunctionCall { function, args } => SqlExpr::FunctionCall {
            function,
            args: args
                .into_iter()
                .map(|arg| normalize_sql_expr_for_table_alias(arg, scope))
                .collect(),
        },
        SqlExpr::Unary { op, expr } => SqlExpr::Unary {
            op,
            expr: Box::new(normalize_sql_expr_for_table_alias(*expr, scope)),
        },
        SqlExpr::Binary { op, left, right } => SqlExpr::Binary {
            op,
            left: Box::new(normalize_sql_expr_for_table_alias(*left, scope)),
            right: Box::new(normalize_sql_expr_for_table_alias(*right, scope)),
        },
        SqlExpr::Case { arms, else_expr } => SqlExpr::Case {
            arms: arms
                .into_iter()
                .map(|arm| crate::db::sql::parser::SqlCaseArm {
                    condition: normalize_sql_expr_for_table_alias(arm.condition, scope),
                    result: normalize_sql_expr_for_table_alias(arm.result, scope),
                })
                .collect(),
            else_expr: else_expr
                .map(|else_expr| Box::new(normalize_sql_expr_for_table_alias(*else_expr, scope))),
        },
    }
}