icydb-core 0.199.31

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
//! Module: db::session::sql::write_policy::model
//! Responsibility: shared SQL write policy DTOs, proofs, and admission lanes.
//! Does not own: SQL parser expression inspection or statement-family policy.
//! Boundary: carries proven write shape and execution bounds into UPDATE/DELETE gates.

use super::bounds::{bounded_write_policy_rejection, sql_write_execution_bounds_for_staged_kind};

pub(in crate::db::session::sql) const DEFAULT_PUBLIC_BOUNDED_WRITE_LIMIT: u32 = 100;
pub(in crate::db::session::sql) const DEFAULT_PUBLIC_WRITE_RETURNING_RESPONSE_BYTES: u32 =
    1_048_576;

/// Shared `WHERE` proof classification for SQL write policy gates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum SqlWriteWhereProof {
    /// The statement has no `WHERE` clause.
    Missing,
    /// The `WHERE` clause proves complete primary-key equality under v1 rules.
    PrimaryKeyEquality,
    /// The `WHERE` clause exists but does not prove primary-key equality.
    Other,
}

impl SqlWriteWhereProof {
    /// Return whether a `WHERE` clause was present.
    #[must_use]
    pub const fn has_where(self) -> bool {
        !matches!(self, Self::Missing)
    }

    /// Return whether v1 primary-key equality proof passed.
    #[must_use]
    pub const fn is_primary_key_equality(self) -> bool {
        matches!(self, Self::PrimaryKeyEquality)
    }
}

/// Shared `ORDER BY` proof classification for SQL write policy gates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum SqlWriteOrderProof {
    /// The statement has no explicit `ORDER BY`.
    Missing,
    /// The statement explicitly orders by canonical primary-key fields ascending.
    CanonicalPrimaryKey,
    /// The statement orders by canonical primary-key fields but uses descending order.
    DescendingPrimaryKey,
    /// The statement has another explicit ordering shape.
    Other,
}

impl SqlWriteOrderProof {
    /// Return whether the statement has explicit canonical ascending primary-key order.
    #[must_use]
    pub const fn is_canonical_primary_key(self) -> bool {
        matches!(self, Self::CanonicalPrimaryKey)
    }
}

/// Shared narrow `RETURNING` classification for SQL write policy gates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum SqlWriteReturningShape {
    /// No `RETURNING` clause.
    None,
    /// Narrow `RETURNING *`.
    NarrowAll,
    /// Narrow `RETURNING field, ...`.
    NarrowFields,
}

impl SqlWriteReturningShape {
    /// Return whether the statement requests `RETURNING`.
    #[must_use]
    pub const fn is_requested(self) -> bool {
        !matches!(self, Self::None)
    }

    /// Return whether the requested `RETURNING` shape is currently narrow.
    #[must_use]
    pub const fn is_narrow(self) -> bool {
        matches!(self, Self::NarrowAll | Self::NarrowFields)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) enum SqlWriteBoundedPolicyRejection {
    MissingCanonicalPrimaryKeyOrder,
    DescendingOrder,
    MissingLimit,
    OffsetUnsupported,
    LimitTooHigh,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) enum SqlGeneratedWritePolicyKind {
    Query,
    Ddl,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) enum SqlWriteExposureClass {
    SessionWriteCurrent,
    GeneratedQuery,
    GeneratedDdl,
    PublicPrimaryKeyOnly,
    PublicBoundedDeterministic,
    AdminBulk,
}

impl SqlWriteExposureClass {
    pub(in crate::db::session::sql) const fn generated_policy_kind(
        self,
    ) -> Option<SqlGeneratedWritePolicyKind> {
        match self {
            Self::GeneratedQuery => Some(SqlGeneratedWritePolicyKind::Query),
            Self::GeneratedDdl => Some(SqlGeneratedWritePolicyKind::Ddl),
            Self::SessionWriteCurrent
            | Self::PublicPrimaryKeyOnly
            | Self::PublicBoundedDeterministic
            | Self::AdminBulk => None,
        }
    }

    const fn admission_lane(self) -> Option<SqlWriteAdmissionLane> {
        Some(match self {
            Self::PublicPrimaryKeyOnly => SqlWriteAdmissionLane::PrimaryKeyOnly,
            Self::PublicBoundedDeterministic => SqlWriteAdmissionLane::BoundedDeterministic,
            Self::SessionWriteCurrent | Self::AdminBulk => SqlWriteAdmissionLane::Bulk,
            Self::GeneratedQuery | Self::GeneratedDdl => return None,
        })
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) enum SqlWriteShapePolicyRejection {
    MissingWhere,
    PrimaryKeyProofFailed,
    Bounded(SqlWriteBoundedPolicyRejection),
}

/// Shared `RETURNING` bounds carried by policy-validated SQL write plans.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct SqlWriteReturningBounds {
    /// Maximum rows the plan may return, when statically bounded by policy.
    pub max_rows: Option<u32>,
    /// Maximum encoded response bytes, when supplied by the caller surface.
    pub max_response_bytes: Option<u32>,
}

/// Shared execution bounds carried by policy-validated SQL write plans.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct SqlWriteExecutionBounds {
    /// Maximum candidate rows the validated plan may stage before mutation.
    pub max_staged_rows: Option<u32>,
    /// Optional `RETURNING` row and response-size bounds.
    pub returning: SqlWriteReturningBounds,
}

/// Shared parsed write shape used by UPDATE and DELETE exposure policies.
#[derive(Clone, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct SqlWriteStatementShape {
    /// `WHERE` proof classification.
    pub where_proof: SqlWriteWhereProof,
    /// Explicit `ORDER BY` proof classification.
    pub order_proof: SqlWriteOrderProof,
    /// Parsed `LIMIT`, if supplied.
    pub limit: Option<u32>,
    /// Parsed `OFFSET`, if supplied.
    pub offset: Option<u32>,
    /// Narrow write `RETURNING` classification.
    pub returning_shape: SqlWriteReturningShape,
}

impl SqlWriteStatementShape {
    /// Return whether the statement has an explicit positive `LIMIT`.
    #[must_use]
    pub const fn is_bounded(&self) -> bool {
        matches!(self.limit, Some(limit) if limit > 0)
    }

    /// Return whether the statement has explicit canonical ascending primary-key order.
    #[must_use]
    pub const fn has_explicit_canonical_primary_key_order(&self) -> bool {
        self.order_proof.is_canonical_primary_key()
    }

    const fn bounded_policy_rejection(
        &self,
        max_limit: u32,
    ) -> Option<SqlWriteBoundedPolicyRejection> {
        bounded_write_policy_rejection(self.offset, self.limit, max_limit, self.order_proof)
    }

    pub(in crate::db::session::sql) const fn bounded_policy_rejection_for_bounds(
        &self,
        bounds: SqlWritePolicyBounds,
    ) -> Option<SqlWriteBoundedPolicyRejection> {
        self.bounded_policy_rejection(bounds.public_bounded_limit)
    }

    pub(in crate::db::session::sql) const fn required_where_rejection(
        &self,
    ) -> Option<SqlWriteShapePolicyRejection> {
        if self.where_proof.has_where() {
            None
        } else {
            Some(SqlWriteShapePolicyRejection::MissingWhere)
        }
    }

    pub(in crate::db::session::sql) const fn primary_key_policy_rejection(
        &self,
    ) -> Option<SqlWriteShapePolicyRejection> {
        if let Some(rejection) = self.required_where_rejection() {
            return Some(rejection);
        }
        if self.where_proof.is_primary_key_equality() {
            None
        } else {
            Some(SqlWriteShapePolicyRejection::PrimaryKeyProofFailed)
        }
    }

    pub(in crate::db::session::sql) const fn bounded_deterministic_policy_rejection(
        &self,
        bounds: SqlWritePolicyBounds,
    ) -> Option<SqlWriteShapePolicyRejection> {
        if let Some(rejection) = self.required_where_rejection() {
            return Some(rejection);
        }
        match self.bounded_policy_rejection_for_bounds(bounds) {
            Some(rejection) => Some(SqlWriteShapePolicyRejection::Bounded(rejection)),
            None => None,
        }
    }

    pub(in crate::db::session::sql) const fn execution_bounds_for_admission_lane(
        &self,
        admission_lane: SqlWriteAdmissionLane,
        bounds: SqlWritePolicyBounds,
    ) -> SqlWriteExecutionBounds {
        sql_write_execution_bounds_for_staged_kind(
            admission_lane.staged_row_bound_kind(),
            self.limit,
            self.returning_shape.is_requested(),
            bounds.returning_rows,
            bounds.returning_response_bytes,
        )
    }

    pub(in crate::db::session::sql) const fn execution_bounds_for_exposure_class(
        &self,
        exposure_class: SqlWriteExposureClass,
        bounds: SqlWritePolicyBounds,
    ) -> Option<SqlWriteExecutionBounds> {
        match exposure_class.admission_lane() {
            Some(admission_lane) => {
                Some(self.execution_bounds_for_admission_lane(admission_lane, bounds))
            }
            None => None,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) struct SqlWritePolicyBounds {
    pub(in crate::db::session::sql) public_bounded_limit: u32,
    pub(in crate::db::session::sql) returning_rows: Option<u32>,
    pub(in crate::db::session::sql) returning_response_bytes: Option<u32>,
}

impl SqlWritePolicyBounds {
    pub(in crate::db::session::sql) const fn new(
        public_bounded_limit: u32,
        returning_rows: Option<u32>,
        returning_response_bytes: Option<u32>,
    ) -> Self {
        Self {
            public_bounded_limit,
            returning_rows,
            returning_response_bytes,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) struct SqlWritePlanCore<S, C> {
    statement: S,
    classification: C,
    execution_bounds: SqlWriteExecutionBounds,
}

impl<S, C> SqlWritePlanCore<S, C> {
    pub(in crate::db::session::sql) const fn new(
        statement: S,
        classification: C,
        execution_bounds: SqlWriteExecutionBounds,
    ) -> Self {
        Self {
            statement,
            classification,
            execution_bounds,
        }
    }

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

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

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

    #[cfg(test)]
    pub(in crate::db) const fn set_execution_bounds_for_tests(
        &mut self,
        execution_bounds: SqlWriteExecutionBounds,
    ) {
        self.execution_bounds = execution_bounds;
    }
}

impl<S: Clone, C: Clone> SqlWritePlanCore<S, C> {
    pub(in crate::db::session::sql) fn from_borrowed(
        statement: &S,
        classification: &C,
        execution_bounds: SqlWriteExecutionBounds,
    ) -> Self {
        Self::new(statement.clone(), classification.clone(), execution_bounds)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) struct SqlWritePrimaryKeyPlanProof {
    primary_key_fields: Vec<String>,
}

impl SqlWritePrimaryKeyPlanProof {
    pub(in crate::db::session::sql) const fn new(primary_key_fields: Vec<String>) -> Self {
        Self { primary_key_fields }
    }

    pub(in crate::db::session::sql) fn from_field_names(primary_key_fields: &[&str]) -> Self {
        Self::new(owned_write_field_names(primary_key_fields))
    }

    pub(in crate::db::session::sql) const fn primary_key_fields(&self) -> &[String] {
        self.primary_key_fields.as_slice()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) struct SqlWriteBoundedPlanProof {
    limit: u32,
    ordered_primary_key_fields: Vec<String>,
}

impl SqlWriteBoundedPlanProof {
    pub(in crate::db::session::sql) const fn new(
        limit: u32,
        ordered_primary_key_fields: Vec<String>,
    ) -> Self {
        Self {
            limit,
            ordered_primary_key_fields,
        }
    }

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

    pub(in crate::db::session::sql) const fn ordered_primary_key_fields(&self) -> &[String] {
        self.ordered_primary_key_fields.as_slice()
    }

    pub(in crate::db::session::sql) fn from_admitted_shape(
        shape: &SqlWriteStatementShape,
        ordered_primary_key_fields: &[&str],
    ) -> Option<Self> {
        Some(Self::new(
            shape.limit?,
            owned_write_field_names(ordered_primary_key_fields),
        ))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::session::sql) enum SqlWriteAdmissionLane {
    PrimaryKeyOnly,
    BoundedDeterministic,
    Bulk,
}

impl SqlWriteAdmissionLane {
    pub(super) const fn staged_row_bound_kind(self) -> SqlWriteStagedRowBoundKind {
        match self {
            Self::PrimaryKeyOnly => SqlWriteStagedRowBoundKind::One,
            Self::BoundedDeterministic => SqlWriteStagedRowBoundKind::Limit,
            Self::Bulk => SqlWriteStagedRowBoundKind::Unbounded,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum SqlWriteStagedRowBoundKind {
    One,
    Limit,
    Unbounded,
}

fn owned_write_field_names(fields: &[&str]) -> Vec<String> {
    fields.iter().map(|field| (*field).to_owned()).collect()
}