icydb-core 0.94.0

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
//! Module: query::intent::errors
//! Responsibility: query-intent-facing typed error taxonomy and domain conversions.
//! Does not own: planner rule evaluation or runtime execution policy decisions.
//! Boundary: unifies intent/planner/cursor/resource errors into query API error classes.

///
/// TESTS
///

#[cfg(test)]
mod tests;

#[cfg(feature = "sql")]
use crate::db::sql::{lowering::SqlLoweringError, parser::SqlParseError};
use crate::{
    db::{
        cursor::CursorPlanError,
        executor::ExecutorPlanError,
        query::{
            expr::SortLowerError,
            plan::{
                CursorPagingPolicyError, FluentLoadPolicyViolation, IntentKeyAccessPolicyViolation,
                PlanError, PlannerError, PolicyPlanError,
            },
        },
        response::ResponseError,
        schema::ValidateError,
    },
    error::{ErrorClass, InternalError},
};
use thiserror::Error as ThisError;

///
/// QueryError
///

#[derive(Debug, ThisError)]
pub enum QueryError {
    #[error("{0}")]
    Validate(Box<ValidateError>),

    #[error("{0}")]
    Plan(Box<PlanError>),

    #[error("{0}")]
    Intent(#[from] IntentError),

    #[error("{0}")]
    Response(#[from] ResponseError),

    #[error("{0}")]
    Execute(#[from] QueryExecutionError),
}

impl QueryError {
    /// Construct one validation-domain query error.
    pub(crate) fn validate(err: ValidateError) -> Self {
        Self::Validate(Box::new(err))
    }

    /// Construct an execution-domain query error from one classified runtime error.
    pub(crate) fn execute(err: InternalError) -> Self {
        Self::Execute(QueryExecutionError::from(err))
    }

    /// Construct one query-origin invariant-violation execution error.
    pub(crate) fn invariant(message: impl Into<String>) -> Self {
        Self::execute(InternalError::query_executor_invariant(message))
    }

    /// Construct one intent-domain query error.
    pub(crate) const fn intent(err: IntentError) -> Self {
        Self::Intent(err)
    }

    /// Construct one query-origin unsupported execution error.
    pub(crate) fn unsupported_query(message: impl Into<String>) -> Self {
        Self::execute(InternalError::query_unsupported(message))
    }

    /// Construct one serialize-origin internal execution error.
    pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
        Self::execute(InternalError::serialize_internal(message))
    }

    /// Construct one query error from one executor plan-surface failure.
    pub(in crate::db) fn from_executor_plan_error(err: ExecutorPlanError) -> Self {
        match err {
            ExecutorPlanError::Cursor(err) => Self::from_cursor_plan_error(*err),
        }
    }

    /// Construct one query error from one cursor plan-surface failure.
    pub(in crate::db) fn from_cursor_plan_error(err: CursorPlanError) -> Self {
        Self::from(PlanError::from(err))
    }

    /// Construct one query-origin unsupported SQL-feature execution error.
    #[cfg(feature = "sql")]
    pub(crate) fn unsupported_sql_feature(feature: &'static str) -> Self {
        Self::execute(InternalError::query_unsupported_sql_feature(feature))
    }

    /// Construct one query error from one SQL lowering failure.
    #[cfg(feature = "sql")]
    pub(in crate::db) fn from_sql_lowering_error(err: SqlLoweringError) -> Self {
        match err {
            SqlLoweringError::Query(err) => *err,
            SqlLoweringError::Parse(SqlParseError::UnsupportedFeature { feature }) => {
                Self::unsupported_sql_feature(feature)
            }
            SqlLoweringError::UnexpectedQueryLaneStatement => {
                Self::unsupported_query_lane_sql_statement()
            }
            other => Self::unsupported_query(format!(
                "SQL query is not executable in this release: {other}"
            )),
        }
    }

    /// Construct one query error from one reduced SQL parse failure.
    #[cfg(feature = "sql")]
    pub(in crate::db) fn from_sql_parse_error(err: SqlParseError) -> Self {
        Self::from_sql_lowering_error(SqlLoweringError::Parse(err))
    }

    /// Construct one unsupported query-lane SQL statement error.
    #[cfg(feature = "sql")]
    pub(crate) fn unsupported_query_lane_sql_statement() -> Self {
        Self::unsupported_query(
            "query-lane SQL execution only accepts SELECT, DELETE, and EXPLAIN statements",
        )
    }

    /// Construct one unsupported aggregate target-field query error.
    pub(crate) fn unknown_aggregate_target_field(field: &str) -> Self {
        Self::unsupported_query(format!("unknown aggregate target field: {field}"))
    }

    /// Construct one invariant violation for scalar pagination emitting the wrong cursor kind.
    pub(crate) fn scalar_paged_emitted_grouped_continuation() -> Self {
        Self::invariant("scalar load pagination emitted grouped continuation token")
    }

    /// Construct one invariant violation for grouped pagination emitting the wrong cursor kind.
    pub(crate) fn grouped_paged_emitted_scalar_continuation() -> Self {
        Self::invariant("grouped pagination emitted scalar continuation token")
    }
}

impl From<ValidateError> for QueryError {
    fn from(err: ValidateError) -> Self {
        Self::validate(err)
    }
}

///
/// QueryExecutionError
///

#[derive(Debug, ThisError)]
pub enum QueryExecutionError {
    #[error("{0}")]
    Corruption(InternalError),

    #[error("{0}")]
    IncompatiblePersistedFormat(InternalError),

    #[error("{0}")]
    InvariantViolation(InternalError),

    #[error("{0}")]
    Conflict(InternalError),

    #[error("{0}")]
    NotFound(InternalError),

    #[error("{0}")]
    Unsupported(InternalError),

    #[error("{0}")]
    Internal(InternalError),
}

impl QueryExecutionError {
    /// Borrow the wrapped classified runtime error.
    #[must_use]
    pub const fn as_internal(&self) -> &InternalError {
        match self {
            Self::Corruption(err)
            | Self::IncompatiblePersistedFormat(err)
            | Self::InvariantViolation(err)
            | Self::Conflict(err)
            | Self::NotFound(err)
            | Self::Unsupported(err)
            | Self::Internal(err) => err,
        }
    }
}

impl From<InternalError> for QueryExecutionError {
    fn from(err: InternalError) -> Self {
        match err.class {
            ErrorClass::Corruption => Self::Corruption(err),
            ErrorClass::IncompatiblePersistedFormat => Self::IncompatiblePersistedFormat(err),
            ErrorClass::InvariantViolation => Self::InvariantViolation(err),
            ErrorClass::Conflict => Self::Conflict(err),
            ErrorClass::NotFound => Self::NotFound(err),
            ErrorClass::Unsupported => Self::Unsupported(err),
            ErrorClass::Internal => Self::Internal(err),
        }
    }
}

impl From<PlannerError> for QueryError {
    fn from(err: PlannerError) -> Self {
        match err {
            PlannerError::Plan(err) => Self::from(*err),
            PlannerError::Internal(err) => Self::execute(*err),
        }
    }
}

impl From<PlanError> for QueryError {
    fn from(err: PlanError) -> Self {
        Self::Plan(Box::new(err))
    }
}

impl From<SortLowerError> for QueryError {
    fn from(err: SortLowerError) -> Self {
        match err {
            SortLowerError::Validate(err) => Self::validate(*err),
            SortLowerError::Plan(err) => Self::from(*err),
        }
    }
}

///
/// IntentError
///

#[derive(Clone, Copy, Debug, ThisError)]
pub enum IntentError {
    #[error("{0}")]
    PlanShape(#[from] PolicyPlanError),

    #[error("by_ids() cannot be combined with predicates")]
    ByIdsWithPredicate,

    #[error("only() cannot be combined with predicates")]
    OnlyWithPredicate,

    #[error("multiple key access methods were used on the same query")]
    KeyAccessConflict,

    #[error("{0}")]
    InvalidPagingShape(#[from] PagingIntentError),

    #[error("grouped queries execute via execute()")]
    GroupedRequiresDirectExecute,

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

    #[error("HAVING references an unknown grouped aggregate output")]
    HavingReferencesUnknownAggregate,
}

impl IntentError {
    /// Construct one by-ids-with-predicate intent error.
    pub(crate) const fn by_ids_with_predicate() -> Self {
        Self::ByIdsWithPredicate
    }

    /// Construct one only-with-predicate intent error.
    pub(crate) const fn only_with_predicate() -> Self {
        Self::OnlyWithPredicate
    }

    /// Construct one key-access-conflict intent error.
    pub(crate) const fn key_access_conflict() -> Self {
        Self::KeyAccessConflict
    }

    /// Construct one invalid-paging-shape intent error.
    pub(crate) const fn invalid_paging_shape(err: PagingIntentError) -> Self {
        Self::InvalidPagingShape(err)
    }

    /// Construct one cursor-requires-order intent error.
    pub(crate) const fn cursor_requires_order() -> Self {
        Self::invalid_paging_shape(PagingIntentError::cursor_requires_order())
    }

    /// Construct one cursor-requires-limit intent error.
    pub(crate) const fn cursor_requires_limit() -> Self {
        Self::invalid_paging_shape(PagingIntentError::cursor_requires_limit())
    }

    /// Construct one cursor-requires-paged-execution intent error.
    pub(crate) const fn cursor_requires_paged_execution() -> Self {
        Self::invalid_paging_shape(PagingIntentError::cursor_requires_paged_execution())
    }

    /// Construct one grouped-requires-direct-execute intent error.
    pub(crate) const fn grouped_requires_direct_execute() -> Self {
        Self::GroupedRequiresDirectExecute
    }

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

    /// Construct one unknown-grouped-aggregate HAVING intent error.
    pub(crate) const fn having_references_unknown_aggregate() -> Self {
        Self::HavingReferencesUnknownAggregate
    }
}

///
/// PagingIntentError
///
/// Canonical intent-level paging contract failures shared by planner and
/// fluent/execution boundary gates.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq, ThisError)]
#[expect(clippy::enum_variant_names)]
pub enum PagingIntentError {
    #[error(
        "{message}",
        message = CursorPlanError::cursor_requires_order_message()
    )]
    CursorRequiresOrder,

    #[error(
        "{message}",
        message = CursorPlanError::cursor_requires_limit_message()
    )]
    CursorRequiresLimit,

    #[error("cursor tokens can only be used with .page().execute()")]
    CursorRequiresPagedExecution,
}

impl PagingIntentError {
    /// Construct one cursor-requires-order paging intent error.
    pub(crate) const fn cursor_requires_order() -> Self {
        Self::CursorRequiresOrder
    }

    /// Construct one cursor-requires-limit paging intent error.
    pub(crate) const fn cursor_requires_limit() -> Self {
        Self::CursorRequiresLimit
    }

    /// Construct one cursor-requires-paged-execution paging intent error.
    pub(crate) const fn cursor_requires_paged_execution() -> Self {
        Self::CursorRequiresPagedExecution
    }
}

impl From<CursorPagingPolicyError> for PagingIntentError {
    fn from(err: CursorPagingPolicyError) -> Self {
        match err {
            CursorPagingPolicyError::CursorRequiresOrder => Self::cursor_requires_order(),
            CursorPagingPolicyError::CursorRequiresLimit => Self::cursor_requires_limit(),
        }
    }
}

impl From<CursorPagingPolicyError> for IntentError {
    fn from(err: CursorPagingPolicyError) -> Self {
        match err {
            CursorPagingPolicyError::CursorRequiresOrder => Self::cursor_requires_order(),
            CursorPagingPolicyError::CursorRequiresLimit => Self::cursor_requires_limit(),
        }
    }
}

impl From<IntentKeyAccessPolicyViolation> for IntentError {
    fn from(err: IntentKeyAccessPolicyViolation) -> Self {
        match err {
            IntentKeyAccessPolicyViolation::KeyAccessConflict => Self::key_access_conflict(),
            IntentKeyAccessPolicyViolation::ByIdsWithPredicate => Self::by_ids_with_predicate(),
            IntentKeyAccessPolicyViolation::OnlyWithPredicate => Self::only_with_predicate(),
        }
    }
}

impl From<FluentLoadPolicyViolation> for IntentError {
    fn from(err: FluentLoadPolicyViolation) -> Self {
        match err {
            FluentLoadPolicyViolation::CursorRequiresPagedExecution => {
                Self::cursor_requires_paged_execution()
            }
            FluentLoadPolicyViolation::GroupedRequiresDirectExecute => {
                Self::grouped_requires_direct_execute()
            }
            FluentLoadPolicyViolation::CursorRequiresOrder => Self::cursor_requires_order(),
            FluentLoadPolicyViolation::CursorRequiresLimit => Self::cursor_requires_limit(),
        }
    }
}