Skip to main content

icydb_core/db/session/
write.rs

1//! Module: db::session::write
2//! Responsibility: session-owned typed write APIs for insert, replace, update,
3//! and structural mutation entrypoints over the shared save pipeline.
4//! Does not own: commit staging, mutation execution, or persistence encoding.
5//! Boundary: keeps public session write semantics above the executor save surface.
6
7use crate::{
8    db::{
9        DbSession, PersistedRow, WriteBatchResponse,
10        data::{FieldSlot, StructuralPatch},
11        executor::MutationMode,
12        schema::{
13            AcceptedFieldAbsencePolicy, AcceptedRowLayoutRuntimeDescriptor, SchemaInfo,
14            accepted_commit_schema_fingerprint,
15        },
16    },
17    error::InternalError,
18    traits::{CanisterKind, EntityCreateInput, EntityValue},
19    value::Value,
20};
21
22// Append one session-resolved structural field update. The caller passes the
23// accepted runtime descriptor that already crossed schema reconciliation, so
24// field-name lookup follows persisted row-layout metadata rather than generated
25// declaration order.
26fn append_accepted_structural_patch_field(
27    entity_path: &'static str,
28    descriptor: &AcceptedRowLayoutRuntimeDescriptor<'_>,
29    patch: StructuralPatch,
30    field_name: &str,
31    value: Value,
32) -> Result<StructuralPatch, InternalError> {
33    let slot = descriptor
34        .field_slot_index_by_name(field_name)
35        .ok_or_else(|| InternalError::mutation_structural_field_unknown(entity_path, field_name))?;
36
37    Ok(patch.set(FieldSlot::from_validated_index(slot), value))
38}
39
40// Enforce public structural patch policy before the executor materializes an
41// entity through generated derive code. This keeps database write ownership and
42// absence/default policy owned by accepted schema metadata instead of
43// accidentally relying on executor-local generated field metadata, Rust
44// construction defaults, or derive-local missing slot behavior.
45fn validate_structural_patch_schema_policy<E>(
46    descriptor: &AcceptedRowLayoutRuntimeDescriptor<'_>,
47    patch: &StructuralPatch,
48    mode: MutationMode,
49) -> Result<(), InternalError>
50where
51    E: PersistedRow + EntityValue,
52{
53    reject_explicit_generated_fields_from_accepted_patch::<E>(descriptor, patch)?;
54
55    if matches!(mode, MutationMode::Update) {
56        return Ok(());
57    }
58
59    let mut provided_slots = vec![false; descriptor.required_slot_count()];
60    for entry in patch.entries() {
61        let slot = entry.slot().index();
62        if slot < provided_slots.len() {
63            provided_slots[slot] = true;
64        }
65    }
66
67    // Every omitted field must be allowed by accepted schema absence policy.
68    // Future database defaults should extend `AcceptedFieldAbsencePolicy`; this
69    // check must not inspect `Default` impls or generated construction values.
70    for field in descriptor.fields() {
71        let slot = usize::from(field.slot().get());
72        if provided_slots.get(slot).copied().unwrap_or(false) {
73            continue;
74        }
75
76        if matches!(field.absence_policy(), AcceptedFieldAbsencePolicy::Required) {
77            return Err(
78                InternalError::mutation_structural_patch_required_field_missing(
79                    E::PATH,
80                    field.name(),
81                ),
82            );
83        }
84    }
85
86    Ok(())
87}
88
89// Preserve generated-field ownership diagnostics ahead of sparse-patch
90// required-field diagnostics. Public structural writes must not author fields
91// whose values are owned by accepted schema write policy, except for the
92// redundant primary-key slot because the structural API already carries the
93// authoritative key separately.
94fn reject_explicit_generated_fields_from_accepted_patch<E>(
95    descriptor: &AcceptedRowLayoutRuntimeDescriptor<'_>,
96    patch: &StructuralPatch,
97) -> Result<(), InternalError>
98where
99    E: PersistedRow + EntityValue,
100{
101    for entry in patch.entries() {
102        let slot = entry.slot().index();
103        let Some(accepted_field) = descriptor.field_for_slot_index(slot) else {
104            continue;
105        };
106        let write_policy = accepted_field.write_policy();
107
108        if write_policy.insert_generation().is_some()
109            && accepted_field.name() != descriptor.primary_key_name()
110        {
111            return Err(InternalError::mutation_generated_field_explicit(
112                E::PATH,
113                accepted_field.name(),
114            ));
115        }
116    }
117
118    Ok(())
119}
120
121impl<C: CanisterKind> DbSession<C> {
122    /// Insert one entity row.
123    pub fn insert<E>(&self, entity: E) -> Result<E, InternalError>
124    where
125        E: PersistedRow<Canister = C> + EntityValue,
126    {
127        self.execute_save_entity(|save| save.insert(entity))
128    }
129
130    /// Insert one authored typed input.
131    pub fn create<I>(&self, input: I) -> Result<I::Entity, InternalError>
132    where
133        I: EntityCreateInput,
134        I::Entity: PersistedRow<Canister = C> + EntityValue,
135    {
136        self.execute_save_entity(|save| save.create(input))
137    }
138
139    /// Insert a single-entity-type batch atomically in one commit window.
140    ///
141    /// If any item fails pre-commit validation, no row in the batch is persisted.
142    ///
143    /// This API is not a multi-entity transaction surface.
144    pub fn insert_many_atomic<E>(
145        &self,
146        entities: impl IntoIterator<Item = E>,
147    ) -> Result<WriteBatchResponse<E>, InternalError>
148    where
149        E: PersistedRow<Canister = C> + EntityValue,
150    {
151        self.execute_save_batch(|save| save.insert_many_atomic(entities))
152    }
153
154    /// Insert a batch with explicitly non-atomic semantics.
155    ///
156    /// WARNING: fail-fast and non-atomic. Earlier inserts may commit before an error.
157    pub fn insert_many_non_atomic<E>(
158        &self,
159        entities: impl IntoIterator<Item = E>,
160    ) -> Result<WriteBatchResponse<E>, InternalError>
161    where
162        E: PersistedRow<Canister = C> + EntityValue,
163    {
164        self.execute_save_batch(|save| save.insert_many_non_atomic(entities))
165    }
166
167    /// Replace one existing entity row.
168    pub fn replace<E>(&self, entity: E) -> Result<E, InternalError>
169    where
170        E: PersistedRow<Canister = C> + EntityValue,
171    {
172        self.execute_save_entity(|save| save.replace(entity))
173    }
174
175    /// Apply one structural mutation under one explicit write-mode contract.
176    ///
177    /// This is the public core session boundary for structural writes:
178    /// callers provide the key, field patch, and intended mutation mode, and
179    /// the session routes that through the shared structural mutation pipeline.
180    pub fn mutate_structural<E>(
181        &self,
182        key: E::Key,
183        patch: StructuralPatch,
184        mode: MutationMode,
185    ) -> Result<E, InternalError>
186    where
187        E: PersistedRow<Canister = C> + EntityValue,
188    {
189        let accepted_schema = self.ensure_accepted_schema_snapshot::<E>()?;
190        let (descriptor, _) = AcceptedRowLayoutRuntimeDescriptor::from_generated_compatible_schema(
191            &accepted_schema,
192            E::MODEL,
193        )?;
194        validate_structural_patch_schema_policy::<E>(&descriptor, &patch, mode)?;
195        let accepted_schema_info =
196            SchemaInfo::from_accepted_snapshot_for_model(E::MODEL, &accepted_schema);
197        let accepted_schema_fingerprint = accepted_commit_schema_fingerprint(&accepted_schema)?;
198
199        let row_decode_contract = descriptor.row_decode_contract();
200        let mutation_row_decode_contract = row_decode_contract.clone();
201
202        self.execute_save_with_checked_accepted_row_contract(
203            row_decode_contract,
204            accepted_schema_info,
205            accepted_schema_fingerprint,
206            |save| save.apply_structural_mutation(mode, key, patch, mutation_row_decode_contract),
207            std::convert::identity,
208        )
209    }
210
211    /// Build one structural patch through the accepted schema row layout.
212    ///
213    /// This is the session-owned patch construction boundary for callers that
214    /// can provide all dynamic field updates at once. It resolves field names
215    /// through the accepted row-layout descriptor before the patch reaches the
216    /// generated-compatible write codec bridge.
217    pub fn structural_patch<E, I, S>(&self, fields: I) -> Result<StructuralPatch, InternalError>
218    where
219        E: PersistedRow<Canister = C> + EntityValue,
220        I: IntoIterator<Item = (S, Value)>,
221        S: AsRef<str>,
222    {
223        let accepted_schema = self.ensure_accepted_schema_snapshot::<E>()?;
224        let (descriptor, _) = AcceptedRowLayoutRuntimeDescriptor::from_generated_compatible_schema(
225            &accepted_schema,
226            E::MODEL,
227        )?;
228        let mut patch = StructuralPatch::new();
229
230        // Phase 1: resolve every caller-provided field name against the
231        // accepted descriptor so public structural patch construction no
232        // longer has to choose slots from generated model field order.
233        for (field_name, value) in fields {
234            let field_name = field_name.as_ref();
235            patch = append_accepted_structural_patch_field(
236                E::PATH,
237                &descriptor,
238                patch,
239                field_name,
240                value,
241            )?;
242        }
243
244        Ok(patch)
245    }
246
247    /// Apply one structural replacement, inserting if missing.
248    ///
249    /// Replace semantics still do not inherit omitted fields from the old row.
250    /// Missing fields must materialize through explicit defaults or managed
251    /// field preflight, or the write fails closed.
252    #[cfg(test)]
253    pub(in crate::db) fn replace_structural<E>(
254        &self,
255        key: E::Key,
256        patch: StructuralPatch,
257    ) -> Result<E, InternalError>
258    where
259        E: PersistedRow<Canister = C> + EntityValue,
260    {
261        self.mutate_structural(key, patch, MutationMode::Replace)
262    }
263
264    /// Replace a single-entity-type batch atomically in one commit window.
265    ///
266    /// If any item fails pre-commit validation, no row in the batch is persisted.
267    ///
268    /// This API is not a multi-entity transaction surface.
269    pub fn replace_many_atomic<E>(
270        &self,
271        entities: impl IntoIterator<Item = E>,
272    ) -> Result<WriteBatchResponse<E>, InternalError>
273    where
274        E: PersistedRow<Canister = C> + EntityValue,
275    {
276        self.execute_save_batch(|save| save.replace_many_atomic(entities))
277    }
278
279    /// Replace a batch with explicitly non-atomic semantics.
280    ///
281    /// WARNING: fail-fast and non-atomic. Earlier replaces may commit before an error.
282    pub fn replace_many_non_atomic<E>(
283        &self,
284        entities: impl IntoIterator<Item = E>,
285    ) -> Result<WriteBatchResponse<E>, InternalError>
286    where
287        E: PersistedRow<Canister = C> + EntityValue,
288    {
289        self.execute_save_batch(|save| save.replace_many_non_atomic(entities))
290    }
291
292    /// Update one existing entity row.
293    pub fn update<E>(&self, entity: E) -> Result<E, InternalError>
294    where
295        E: PersistedRow<Canister = C> + EntityValue,
296    {
297        self.execute_save_entity(|save| save.update(entity))
298    }
299
300    /// Apply one structural insert from a patch-defined after-image.
301    ///
302    /// Insert semantics no longer require a pre-built full row image.
303    /// Missing fields still fail closed unless derive-owned materialization can
304    /// supply them through explicit defaults or managed-field preflight.
305    #[cfg(test)]
306    pub(in crate::db) fn insert_structural<E>(
307        &self,
308        key: E::Key,
309        patch: StructuralPatch,
310    ) -> Result<E, InternalError>
311    where
312        E: PersistedRow<Canister = C> + EntityValue,
313    {
314        self.mutate_structural(key, patch, MutationMode::Insert)
315    }
316
317    /// Apply one structural field patch to an existing entity row.
318    ///
319    /// This session-owned boundary keeps structural mutation out of the raw
320    /// executor surface while still routing through the same typed save
321    /// preflight before commit staging.
322    #[cfg(test)]
323    pub(in crate::db) fn update_structural<E>(
324        &self,
325        key: E::Key,
326        patch: StructuralPatch,
327    ) -> Result<E, InternalError>
328    where
329        E: PersistedRow<Canister = C> + EntityValue,
330    {
331        self.mutate_structural(key, patch, MutationMode::Update)
332    }
333
334    /// Update a single-entity-type batch atomically in one commit window.
335    ///
336    /// If any item fails pre-commit validation, no row in the batch is persisted.
337    ///
338    /// This API is not a multi-entity transaction surface.
339    pub fn update_many_atomic<E>(
340        &self,
341        entities: impl IntoIterator<Item = E>,
342    ) -> Result<WriteBatchResponse<E>, InternalError>
343    where
344        E: PersistedRow<Canister = C> + EntityValue,
345    {
346        self.execute_save_batch(|save| save.update_many_atomic(entities))
347    }
348
349    /// Update a batch with explicitly non-atomic semantics.
350    ///
351    /// WARNING: fail-fast and non-atomic. Earlier updates may commit before an error.
352    pub fn update_many_non_atomic<E>(
353        &self,
354        entities: impl IntoIterator<Item = E>,
355    ) -> Result<WriteBatchResponse<E>, InternalError>
356    where
357        E: PersistedRow<Canister = C> + EntityValue,
358    {
359        self.execute_save_batch(|save| save.update_many_non_atomic(entities))
360    }
361}