icydb-core 0.213.38

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
423
424
425
426
427
428
429
430
431
//! Module: db::dynamic_write
//! Responsibility: entity-name-driven structural write requests and results.
//! Does not own: accepted policy resolution, row encoding, or commit execution.
//! Boundary: public dynamic intent is lowered once by the session write owner.

use crate::{
    error::InternalError,
    value::{InputValue, OutputValue},
};
use candid::CandidType;
use icydb_schema::ScalarType;
use serde::Deserialize;
use std::collections::BTreeSet;

///
/// DynamicWriteCell
///
/// One structural field-write intent crossing the facade-to-core boundary.
/// Omission remains distinct from an explicit default request, `NULL`, and an
/// authored value until accepted write policy resolves the final after-image.
///

#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DynamicWriteCell {
    /// Supply no authored value for this field.
    Omitted,
    /// Explicitly request the accepted database default.
    Default,
    /// Explicitly author a nullable value.
    Null,
    /// Author one concrete public input value.
    Value(InputValue),
}

///
/// DynamicStructuralPatch
///
/// Field-name-driven structural patch consumed by the accepted write lane.
/// Field names are resolved against the selected accepted snapshot; this type
/// carries no physical slots or generated-model ordering.
///

#[doc(hidden)]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DynamicStructuralPatch {
    fields: Vec<(String, DynamicWriteCell)>,
}

impl DynamicStructuralPatch {
    /// Build one field-name-driven structural patch.
    #[must_use]
    pub const fn new(fields: Vec<(String, DynamicWriteCell)>) -> Self {
        Self { fields }
    }

    /// Borrow the authored field intents in caller order.
    #[must_use]
    pub const fn fields(&self) -> &[(String, DynamicWriteCell)] {
        self.fields.as_slice()
    }
}

///
/// DynamicMutation
///
/// One entity-name-driven structural mutation request.
/// Variant shape owns row-existence and key requirements so callers cannot
/// combine an insert-only identity mode with update/delete semantics.
///

#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DynamicMutation {
    /// Insert one row, resolving its identity from the accepted after-image.
    Insert {
        /// Accepted entity display name.
        entity: String,
        /// Authored insert intent.
        patch: DynamicStructuralPatch,
    },
    /// Patch one existing row selected by its public primary-key value.
    Update {
        /// Accepted entity display name.
        entity: String,
        /// Scalar or composite primary-key value.
        key: InputValue,
        /// Authored patch intent.
        patch: DynamicStructuralPatch,
    },
    /// Replace one row, inserting when the selected key does not yet exist.
    Replace {
        /// Accepted entity display name.
        entity: String,
        /// Scalar or composite primary-key value.
        key: InputValue,
        /// Authored replacement intent.
        patch: DynamicStructuralPatch,
    },
    /// Delete one existing row selected by its public primary-key value.
    Delete {
        /// Accepted entity display name.
        entity: String,
        /// Scalar or composite primary-key value.
        key: InputValue,
    },
}

impl DynamicMutation {
    /// Borrow the accepted entity display name selected by this request.
    #[must_use]
    pub const fn entity(&self) -> &str {
        match self {
            Self::Insert { entity, .. }
            | Self::Update { entity, .. }
            | Self::Replace { entity, .. }
            | Self::Delete { entity, .. } => entity.as_str(),
        }
    }
}

///
/// DynamicMutationResult
///
/// Row-oriented result from one accepted-schema-driven structural mutation.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct DynamicMutationResult {
    /// Accepted entity name used for the mutation.
    pub entity: String,
    /// Complete accepted output-column names in row order.
    pub columns: Vec<String>,
    /// Canonical row values produced or removed by the mutation.
    pub rows: Vec<Vec<OutputValue>>,
    /// Number of rows whose logical or physical state changed.
    pub affected_rows: u32,
}

///
/// DynamicTypedFieldBindingRequest
///
/// Generated logical field contract supplied only while issuing an opaque
/// accepted adapter binding.
///

#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DynamicTypedFieldBindingRequest {
    pub(crate) field_type: DynamicTypedFieldType,
    pub(crate) nullable: bool,
    pub(crate) source_key: String,
}

impl DynamicTypedFieldBindingRequest {
    /// Construct one generated field binding request.
    #[must_use]
    pub const fn new(
        source_key: String,
        field_type: DynamicTypedFieldType,
        nullable: bool,
    ) -> Self {
        Self {
            field_type,
            nullable,
            source_key,
        }
    }
}

/// Logical generated field shape used only for accepted compatibility checks.
#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DynamicTypedFieldType {
    /// Exact schema-owned scalar contract.
    Scalar(ScalarType),
    /// Ordered repeated values with one exact item contract.
    List(Box<Self>),
    /// Named contract selected by immutable source key.
    Named(String),
}

/// Typed binding issuance failure before an opaque binding exists.
#[doc(hidden)]
#[derive(Debug)]
pub enum DynamicTypedBindingError {
    /// A requested immutable source identity is unavailable.
    FieldUnavailable,
    /// The requested logical field contract disagrees with accepted authority.
    IncompatibleField,
    /// Accepted database inspection failed.
    Internal(InternalError),
}

impl From<InternalError> for DynamicTypedBindingError {
    fn from(error: InternalError) -> Self {
        Self::Internal(error)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct DynamicTypedFieldBinding {
    source_key: String,
    field_id: u32,
    slot: u16,
    label: String,
}

///
/// DynamicTypedStructuralPatch
///
/// Opaque accepted-ID/slot patch produced by a current typed binding.
///

#[doc(hidden)]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DynamicTypedStructuralPatch {
    entity_source: String,
    entity_tag: u64,
    accepted_fingerprint: [u8; 16],
    fields: Vec<(u32, u16, DynamicWriteCell)>,
}

impl DynamicTypedStructuralPatch {
    /// Borrow accepted field ID/slot intents for core mutation lowering.
    #[must_use]
    pub(crate) const fn fields(&self) -> &[(u32, u16, DynamicWriteCell)] {
        self.fields.as_slice()
    }

    pub(crate) fn is_bound_to(&self, binding: &DynamicTypedEntityBinding) -> bool {
        self.entity_source == binding.entity_source
            && self.entity_tag == binding.entity_tag
            && self.accepted_fingerprint == binding.accepted_fingerprint
    }
}

///
/// DynamicTypedMutation
///
/// One source-bound generated mutation whose fields already carry accepted
/// field IDs and slots. Entity and field names are not routing authority.
///

#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DynamicTypedMutation {
    /// Insert one accepted row.
    Insert {
        /// Bound authored field intents.
        patch: DynamicTypedStructuralPatch,
    },
    /// Patch one accepted row.
    Update {
        /// Scalar or composite public primary key.
        key: InputValue,
        /// Bound authored field intents.
        patch: DynamicTypedStructuralPatch,
    },
    /// Replace one accepted row, inserting it when absent.
    Replace {
        /// Scalar or composite public primary key.
        key: InputValue,
        /// Bound authored field intents.
        patch: DynamicTypedStructuralPatch,
    },
}

/// Opaque accepted-schema identity issued for one generated typed adapter.
///
/// Public facade code may retain and return this value, but its accepted field
/// mapping remains private to IcyDB.
#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DynamicTypedEntityBinding {
    pub(crate) database_incarnation: [u8; 16],
    pub(crate) entity_source: String,
    pub(crate) entity_label: String,
    pub(crate) entity_tag: u64,
    pub(crate) accepted_revision: u64,
    pub(crate) accepted_fingerprint: [u8; 16],
    pub(crate) entity_generation: u32,
    fields: Vec<DynamicTypedFieldBinding>,
    pub(crate) named_types: Vec<(String, String)>,
    pub(crate) enum_variants: Vec<(String, String, String)>,
    pub(crate) composite_fields: Vec<(String, String, String)>,
}

impl DynamicTypedEntityBinding {
    #[expect(
        clippy::too_many_arguments,
        reason = "the opaque binding keeps every accepted authority component explicit"
    )]
    pub(crate) fn new(
        database_incarnation: [u8; 16],
        entity_source: String,
        entity_label: String,
        entity_tag: u64,
        accepted_revision: u64,
        accepted_fingerprint: [u8; 16],
        entity_generation: u32,
        fields: Vec<(String, u32, u16, String)>,
        named_types: Vec<(String, String)>,
        enum_variants: Vec<(String, String, String)>,
        composite_fields: Vec<(String, String, String)>,
    ) -> Result<Self, InternalError> {
        let mut sources = BTreeSet::new();
        let mut ids = BTreeSet::new();
        let mut slots = BTreeSet::new();
        let fields = fields
            .into_iter()
            .map(|(source_key, field_id, slot, label)| {
                if !sources.insert(source_key.clone())
                    || !ids.insert(field_id)
                    || !slots.insert(slot)
                {
                    return Err(InternalError::store_invariant());
                }
                Ok(DynamicTypedFieldBinding {
                    source_key,
                    field_id,
                    slot,
                    label,
                })
            })
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self {
            database_incarnation,
            entity_source,
            entity_label,
            entity_tag,
            accepted_revision,
            accepted_fingerprint,
            entity_generation,
            fields,
            named_types,
            enum_variants,
            composite_fields,
        })
    }

    /// Borrow the accepted entity display label.
    #[must_use]
    pub const fn entity(&self) -> &str {
        self.entity_label.as_str()
    }

    /// Borrow the immutable entity source identity.
    #[must_use]
    pub const fn entity_source(&self) -> &str {
        self.entity_source.as_str()
    }

    /// Resolve one immutable field source key directly to its accepted slot.
    #[must_use]
    pub fn field_slot(&self, source_key: &str) -> Option<u16> {
        self.fields
            .iter()
            .find_map(|field| (field.source_key == source_key).then_some(field.slot))
    }

    /// Resolve one accepted output label to its binding-owned accepted slot.
    #[must_use]
    pub fn output_field_slot(&self, label: &str) -> Option<u16> {
        self.fields
            .iter()
            .find_map(|field| (field.label == label).then_some(field.slot))
    }

    pub(crate) fn field_identity_bindings(&self) -> impl Iterator<Item = (&str, u32, u16)> {
        self.fields
            .iter()
            .map(|field| (field.source_key.as_str(), field.field_id, field.slot))
    }

    /// Bind generated source-key write intent to accepted field IDs and slots.
    #[must_use]
    pub fn bind_write_fields(
        &self,
        fields: Vec<(String, DynamicWriteCell)>,
    ) -> Option<DynamicTypedStructuralPatch> {
        let mut seen_ids = BTreeSet::new();
        let mut seen_slots = BTreeSet::new();
        let mut bound = Vec::with_capacity(fields.len());
        for (source_key, cell) in fields {
            let field = self
                .fields
                .iter()
                .find(|field| field.source_key == source_key)?;
            if !seen_ids.insert(field.field_id) || !seen_slots.insert(field.slot) {
                return None;
            }
            bound.push((field.field_id, field.slot, cell));
        }
        Some(DynamicTypedStructuralPatch {
            entity_source: self.entity_source.clone(),
            entity_tag: self.entity_tag,
            accepted_fingerprint: self.accepted_fingerprint,
            fields: bound,
        })
    }

    /// Resolve one immutable named-type source key to its accepted display path.
    #[must_use]
    pub fn named_type_name(&self, source_key: &str) -> Option<&str> {
        self.named_types
            .iter()
            .find_map(|(source, name)| (source == source_key).then_some(name.as_str()))
    }

    /// Resolve one immutable enum-variant source key to its accepted display name.
    #[must_use]
    pub fn enum_variant_name(&self, type_source_key: &str, source_key: &str) -> Option<&str> {
        self.enum_variants
            .iter()
            .find_map(|(bound_type, source, name)| {
                (bound_type == type_source_key && source == source_key).then_some(name.as_str())
            })
    }

    /// Resolve one immutable record-member source key to its accepted display name.
    #[must_use]
    pub fn composite_field_name(&self, type_source_key: &str, source_key: &str) -> Option<&str> {
        self.composite_fields
            .iter()
            .find_map(|(bound_type, source, name)| {
                (bound_type == type_source_key && source == source_key).then_some(name.as_str())
            })
    }
}