icydb-core 0.284.2

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
//! Module: db::session::sql::surface
//! Responsibility: classify parsed SQL statements for generated/controller
//! endpoint routing.
//! Does not own: SQL execution, SQL compilation cache, or DDL publication.
//! Boundary: keeps query/mutation/DDL surface gating out of the SQL facade.

#[cfg(feature = "sql")]
use crate::db::sql::parser::SqlExplainTarget;
use crate::{
    db::{
        DbSession, QueryError,
        session::sql::SqlCompiledCommandSurface,
        sql::parser::{SqlDdlStatement, SqlStatement, parse_sql},
    },
    traits::CanisterKind,
};
use icydb_diagnostic_code::{SqlLoweringCode, SqlSurfaceMismatchCode};

/// Parsed SQL endpoint surface used by generated SQL helper dispatch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum SqlStatementSurface {
    /// SQL routed to the generated query endpoint.
    ///
    /// Row-mutation statements route here for read-only surface rejection
    /// until a generated write endpoint explicitly selects an update policy.
    Query,
    /// SQL handled by the generated DDL endpoint.
    Ddl,
}

/// Parsed SQL shell call route used by host tooling endpoint dispatch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum SqlStatementShellSurface {
    /// SQL routed to the generated query endpoint.
    Query,
    /// SQL routed to the generated DDL endpoint.
    Ddl,
    /// SQL routed to the generated primary-key-policy update endpoint.
    Update,
}

/// Immutable application-owned parsed SQL, reusable across executions.
///
/// The artifact binds its syntax tree to the exact borrowed input used by the
/// compiled-command cache. Downstream consumers cannot pair one statement
/// with another statement's cache text.
pub struct SqlStatementDispatch<'sql> {
    sql: &'sql str,
    statement: SqlStatement,
}

impl<'sql> SqlStatementDispatch<'sql> {
    #[must_use]
    const fn new(sql: &'sql str, statement: SqlStatement) -> Self {
        Self { sql, statement }
    }

    /// Return whether this statement belongs to the operational introspection family.
    #[must_use]
    pub const fn requires_introspection(&self) -> bool {
        sql_statement_requires_introspection_from_statement(&self.statement)
    }

    /// Return the entity identifier targeted by this parsed statement.
    ///
    /// `SHOW ENTITIES`, `SHOW STORES`, and `SHOW MEMORY` intentionally have no
    /// entity target; generated dispatch may route them through any accepted
    /// entity when the endpoint admits introspection.
    #[must_use]
    pub const fn entity_name(&self) -> Option<&str> {
        sql_statement_entity_name_from_statement(&self.statement)
    }

    // Return the exact text from which `statement` was parsed. This is the sole
    // raw-SQL source for the downstream compiled-command cache key.
    pub(in crate::db::session::sql) const fn sql(&self) -> &'sql str {
        self.sql
    }

    pub(in crate::db::session::sql) const fn statement(&self) -> &SqlStatement {
        &self.statement
    }
}

/// Return the generated endpoint surface required by one reduced SQL statement.
#[doc(hidden)]
pub fn sql_statement_surface(sql: &str) -> Result<SqlStatementSurface, QueryError> {
    let statement = parse_sql(sql).map_err(QueryError::from_sql_parse_error)?;

    Ok(sql_statement_surface_from_statement(&statement))
}

/// Return the available generated endpoint route for one shell SQL statement.
/// Unsupported INSERT/DELETE statements fail locally before host dispatch.
#[doc(hidden)]
pub fn sql_statement_shell_surface(sql: &str) -> Result<SqlStatementShellSurface, QueryError> {
    let statement = parse_sql(sql).map_err(QueryError::from_sql_parse_error)?;

    sql_statement_shell_surface_from_statement(&statement)
}

/// Parse one SQL statement for repeated trusted execution with typed operands.
///
/// The result borrows its source text, but owns no session, accepted authority,
/// or execution operands. Retaining it avoids parsing again on each invocation.
pub fn sql_statement_dispatch(sql: &str) -> Result<SqlStatementDispatch<'_>, QueryError> {
    let statement = parse_sql(sql).map_err(QueryError::from_sql_parse_error)?;

    Ok(SqlStatementDispatch::new(sql, statement))
}

const fn sql_statement_surface_from_statement(statement: &SqlStatement) -> SqlStatementSurface {
    match statement {
        SqlStatement::Ddl(_) => SqlStatementSurface::Ddl,
        SqlStatement::Select(_)
        | SqlStatement::Delete(_)
        | SqlStatement::Insert(_)
        | SqlStatement::Update(_)
        | SqlStatement::Describe(_)
        | SqlStatement::ShowConstraints(_)
        | SqlStatement::ShowIndexes(_)
        | SqlStatement::ShowColumns(_)
        | SqlStatement::ShowRelations(_)
        | SqlStatement::ShowEntities(_)
        | SqlStatement::ShowStores(_)
        | SqlStatement::ShowMemory(_) => SqlStatementSurface::Query,
        #[cfg(feature = "sql")]
        SqlStatement::Explain(_) => SqlStatementSurface::Query,
    }
}

fn sql_statement_shell_surface_from_statement(
    statement: &SqlStatement,
) -> Result<SqlStatementShellSurface, QueryError> {
    match statement {
        SqlStatement::Ddl(_) => Ok(SqlStatementShellSurface::Ddl),
        SqlStatement::Update(_) => Ok(SqlStatementShellSurface::Update),
        SqlStatement::Insert(_) => Err(QueryError::sql_surface_mismatch(
            SqlSurfaceMismatchCode::QueryRejectsInsert,
        )),
        SqlStatement::Delete(_) => Err(QueryError::sql_surface_mismatch(
            SqlSurfaceMismatchCode::QueryRejectsDelete,
        )),
        SqlStatement::Select(_)
        | SqlStatement::Describe(_)
        | SqlStatement::ShowConstraints(_)
        | SqlStatement::ShowIndexes(_)
        | SqlStatement::ShowColumns(_)
        | SqlStatement::ShowRelations(_)
        | SqlStatement::ShowEntities(_)
        | SqlStatement::ShowStores(_)
        | SqlStatement::ShowMemory(_) => Ok(SqlStatementShellSurface::Query),
        #[cfg(feature = "sql")]
        SqlStatement::Explain(_) => Ok(SqlStatementShellSurface::Query),
    }
}

const fn sql_statement_requires_introspection_from_statement(statement: &SqlStatement) -> bool {
    match statement {
        #[cfg(feature = "sql")]
        SqlStatement::Explain(_) => true,
        SqlStatement::Describe(_)
        | SqlStatement::ShowConstraints(_)
        | SqlStatement::ShowIndexes(_)
        | SqlStatement::ShowColumns(_)
        | SqlStatement::ShowRelations(_)
        | SqlStatement::ShowEntities(_)
        | SqlStatement::ShowStores(_)
        | SqlStatement::ShowMemory(_) => true,
        SqlStatement::Select(_)
        | SqlStatement::Delete(_)
        | SqlStatement::Insert(_)
        | SqlStatement::Update(_)
        | SqlStatement::Ddl(_) => false,
    }
}

pub(in crate::db::session::sql) const fn sql_statement_entity_name_from_statement(
    statement: &SqlStatement,
) -> Option<&str> {
    match statement {
        SqlStatement::Select(statement) => Some(statement.entity.as_str()),
        SqlStatement::Delete(statement) => Some(statement.entity.as_str()),
        SqlStatement::Insert(statement) => Some(statement.entity.as_str()),
        SqlStatement::Update(statement) => Some(statement.entity.as_str()),
        SqlStatement::Ddl(SqlDdlStatement::CreateIndex(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::DropIndex(statement)) => match &statement.entity {
            Some(entity) => Some(entity.as_str()),
            None => None,
        },
        SqlStatement::Ddl(SqlDdlStatement::AlterTableAddColumn(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::AlterTableAddCheckConstraint(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::AlterTableAlterColumn(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::AlterTableDropColumn(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::AlterTableDropConstraint(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::AlterTableRenameColumn(statement)) => {
            Some(statement.entity.as_str())
        }
        SqlStatement::Ddl(SqlDdlStatement::AlterTableValidateConstraint(statement)) => {
            Some(statement.entity.as_str())
        }
        #[cfg(feature = "sql")]
        SqlStatement::Explain(statement) => match &statement.statement {
            SqlExplainTarget::Select(statement) => Some(statement.entity.as_str()),
            SqlExplainTarget::Delete(statement) => Some(statement.entity.as_str()),
        },
        SqlStatement::Describe(statement) => Some(statement.entity.as_str()),
        SqlStatement::ShowConstraints(statement) => Some(statement.entity.as_str()),
        SqlStatement::ShowIndexes(statement) => Some(statement.entity.as_str()),
        SqlStatement::ShowColumns(statement) => Some(statement.entity.as_str()),
        SqlStatement::ShowRelations(statement) => Some(statement.entity.as_str()),
        SqlStatement::ShowEntities(_)
        | SqlStatement::ShowStores(_)
        | SqlStatement::ShowMemory(_) => None,
    }
}

impl<C: CanisterKind> DbSession<C> {
    // Keep query/mutation surface gating owned by one helper so the SQL
    // compiled-command lane does not duplicate the same statement-family split
    // just to change the outward error wording.
    pub(in crate::db::session::sql) fn ensure_sql_statement_supported_for_surface(
        statement: &SqlStatement,
        surface: SqlCompiledCommandSurface,
    ) -> Result<(), QueryError> {
        match (surface, statement) {
            (
                SqlCompiledCommandSurface::Query,
                SqlStatement::Select(_)
                | SqlStatement::Describe(_)
                | SqlStatement::ShowConstraints(_)
                | SqlStatement::ShowIndexes(_)
                | SqlStatement::ShowColumns(_)
                | SqlStatement::ShowRelations(_)
                | SqlStatement::ShowEntities(_)
                | SqlStatement::ShowStores(_)
                | SqlStatement::ShowMemory(_),
            ) => Ok(()),
            #[cfg(feature = "sql")]
            (SqlCompiledCommandSurface::Query, SqlStatement::Explain(_)) => Ok(()),
            (
                SqlCompiledCommandSurface::Mutation,
                SqlStatement::Insert(_) | SqlStatement::Update(_) | SqlStatement::Delete(_),
            ) => Ok(()),
            (_, SqlStatement::Ddl(_)) => Err(QueryError::sql_lowering(
                SqlLoweringCode::SqlDdlExecutionUnsupported,
            )),
            (SqlCompiledCommandSurface::Query, SqlStatement::Insert(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::QueryRejectsInsert),
            ),
            (SqlCompiledCommandSurface::Query, SqlStatement::Update(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::QueryRejectsUpdate),
            ),
            (SqlCompiledCommandSurface::Query, SqlStatement::Delete(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::QueryRejectsDelete),
            ),
            (SqlCompiledCommandSurface::Mutation, SqlStatement::Select(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::MutationRejectsSelect),
            ),
            #[cfg(feature = "sql")]
            (SqlCompiledCommandSurface::Mutation, SqlStatement::Explain(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::MutationRejectsExplain),
            ),
            (SqlCompiledCommandSurface::Mutation, SqlStatement::Describe(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::MutationRejectsDescribe),
            ),
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowConstraints(_)) => {
                Err(QueryError::sql_surface_mismatch(
                    SqlSurfaceMismatchCode::MutationRejectsShowConstraints,
                ))
            }
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowIndexes(_)) => {
                Err(QueryError::sql_surface_mismatch(
                    SqlSurfaceMismatchCode::MutationRejectsShowIndexes,
                ))
            }
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowColumns(_)) => {
                Err(QueryError::sql_surface_mismatch(
                    SqlSurfaceMismatchCode::MutationRejectsShowColumns,
                ))
            }
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowRelations(_)) => {
                Err(QueryError::sql_surface_mismatch(
                    SqlSurfaceMismatchCode::MutationRejectsShowRelations,
                ))
            }
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowEntities(_)) => {
                Err(QueryError::sql_surface_mismatch(
                    SqlSurfaceMismatchCode::MutationRejectsShowEntities,
                ))
            }
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowStores(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::MutationRejectsShowStores),
            ),
            (SqlCompiledCommandSurface::Mutation, SqlStatement::ShowMemory(_)) => Err(
                QueryError::sql_surface_mismatch(SqlSurfaceMismatchCode::MutationRejectsShowMemory),
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use icydb_diagnostic_code::{DiagnosticCode, DiagnosticDetail};

    #[test]
    fn frozen_operational_sql_families_require_introspection() {
        for sql in [
            "DESCRIBE Example",
            "SHOW CONSTRAINTS FROM Example",
            "SHOW INDEXES FROM Example",
            "SHOW COLUMNS Example",
            "SHOW RELATIONS FROM Example",
            "SHOW ENTITIES",
            "SHOW STORES",
            "SHOW MEMORY",
        ] {
            let dispatch = sql_statement_dispatch(sql)
                .unwrap_or_else(|error| panic!("{sql} should classify: {error}"));
            assert!(dispatch.requires_introspection(), "{sql}");
        }

        let select_sql = "SELECT id FROM Example";
        let select = sql_statement_dispatch(select_sql).expect("ordinary SELECT should classify");
        assert!(!select.requires_introspection());
        assert_eq!(select.sql(), select_sql);
    }

    #[cfg(feature = "sql")]
    #[test]
    fn explain_requires_introspection() {
        let dispatch = sql_statement_dispatch("EXPLAIN SELECT id FROM Example")
            .expect("EXPLAIN should classify");

        assert!(dispatch.requires_introspection());
    }

    #[test]
    fn shell_routes_only_available_endpoints_and_preserves_mutation_refusals() {
        for (sql, expected) in [
            ("SELECT * FROM Character", SqlStatementShellSurface::Query),
            ("SHOW ENTITIES", SqlStatementShellSurface::Query),
            (
                "CREATE INDEX name_idx ON Character (name)",
                SqlStatementShellSurface::Ddl,
            ),
            (
                "UPDATE Character SET name = 'Ada' WHERE id = 1",
                SqlStatementShellSurface::Update,
            ),
        ] {
            assert_eq!(sql_statement_shell_surface(sql).unwrap(), expected);
        }
        for (sql, mismatch) in [
            (
                "INSERT INTO Character (id) VALUES (1)",
                SqlSurfaceMismatchCode::QueryRejectsInsert,
            ),
            (
                " \t insert into Character (id) SELECT id FROM Other;",
                SqlSurfaceMismatchCode::QueryRejectsInsert,
            ),
            (
                "DELETE FROM Character",
                SqlSurfaceMismatchCode::QueryRejectsDelete,
            ),
            (
                " \n delete from Character WHERE id = 1;",
                SqlSurfaceMismatchCode::QueryRejectsDelete,
            ),
            (
                "DELETE FROM Character RETURNING name",
                SqlSurfaceMismatchCode::QueryRejectsDelete,
            ),
            (
                "INSERT INTO Character (id, name) VALUES (1, 'Ada') RETURNING name",
                SqlSurfaceMismatchCode::QueryRejectsInsert,
            ),
        ] {
            let error = sql_statement_shell_surface(sql).unwrap_err();
            assert_eq!(
                error.diagnostic_code(),
                DiagnosticCode::QuerySqlSurfaceMismatch
            );
            assert_eq!(
                error.diagnostic().detail(),
                Some(&DiagnosticDetail::SqlSurfaceMismatch { mismatch })
            );
            // Generated query ingress still owns the same typed refusal; trusted
            // application mutation dispatch remains independently available.
            assert_eq!(
                sql_statement_surface(sql).unwrap(),
                SqlStatementSurface::Query
            );
            assert!(sql_statement_dispatch(sql).is_ok());
        }
    }
}