Skip to main content

type_bridge/
transaction.rs

1#![deny(missing_docs)]
2//! Client-owned write transactions and their borrowing exact managers.
3
4use std::marker::PhantomData;
5use std::sync::Arc;
6
7use type_bridge_contract::id::{TypeId, is_canonical_thing_iid};
8use type_bridge_orm::_descriptor::{EntityDescriptor, RelationDescriptor};
9use type_bridge_orm::_manager::{DynamicEntityManager, DynamicRelationManager};
10use type_bridge_orm::_registry::DescriptorRegistry;
11use type_bridge_orm::session::backend::TxType;
12use type_bridge_orm::session::context::TransactionContext;
13use type_bridge_orm::{
14    AnswerCancellation, DynamicAttributeMap, DynamicRolePlayerInput, InstalledRuntimeProjection,
15    ProjectedBatchOperation, ProjectedCrudExecutor, QueryExecutionResourceLimits,
16};
17
18use crate::__codegen::{CompleteModel, EntityModel, HydrationCapability, RelationModel};
19use crate::entity_codec::{
20    hydrate_entity, lower_entity_create, map_validation_error, resolve_entity_authority,
21};
22use crate::entity_manager::rehydrate_written_entity;
23use crate::error::{Error, ModelValidationPhase};
24use crate::hooks::{CrudOperation, ModelKind};
25use crate::projected_batch::{
26    create_rows, delete_rows, execute_borrowed_delete, execute_borrowed_things, prepare_batch,
27    update_rows, uses_successor_batch_runtime, validate_binding_row_count,
28};
29use crate::projected_codec::{materialize_projected, project_create};
30use crate::relation_codec::{hydrate_relation, lower_relation_create, resolve_relation_authority};
31use crate::relation_manager::rehydrate_written_relation;
32use crate::schema::Schema;
33use crate::{Database, Result};
34
35#[cfg(test)]
36mod tests;
37
38fn invalid_iid() -> Error {
39    Error::model_validation(
40        ModelValidationPhase::Input,
41        "invalid_iid",
42        vec!["iid".into()],
43        "IID is not canonical",
44        None,
45    )
46}
47
48fn schema_not_bound() -> Error {
49    Error::model_validation(
50        ModelValidationPhase::Input,
51        "schema_not_bound",
52        vec![],
53        "database is not schema-bound",
54        None,
55    )
56}
57
58/// One client-owned reusable read transaction over a schema-bound database.
59///
60/// Query sessions borrow this wrapper and execute every terminal on its one
61/// retained read context. Closing consumes the wrapper without commit
62/// semantics; dropping an open wrapper likewise cannot commit.
63pub struct ReadTransaction<'db, S: Schema> {
64    tx: TransactionContext,
65    db: &'db Database<S>,
66    installed: Arc<InstalledRuntimeProjection>,
67    registry: Arc<DescriptorRegistry>,
68}
69
70impl<S: Schema> std::fmt::Debug for ReadTransaction<'_, S> {
71    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        formatter
73            .debug_struct("ReadTransaction")
74            .field("database", &self.db.database_name())
75            .finish_non_exhaustive()
76    }
77}
78
79impl<'db, S: Schema> ReadTransaction<'db, S> {
80    pub(crate) async fn open(db: &'db Database<S>) -> Result<Self> {
81        let installed = Arc::clone(db.installed_schema().ok_or_else(schema_not_bound)?);
82        let registry = Arc::clone(db.match_registry().ok_or_else(schema_not_bound)?);
83        let tx = db
84            .inner_orm()
85            .transaction_context(TxType::Read)
86            .await
87            .map_err(Error::from_orm)?;
88        Ok(Self {
89            tx,
90            db,
91            installed,
92            registry,
93        })
94    }
95
96    /// Create a read-only exact entity manager borrowing this transaction.
97    /// Every derived filter terminal reuses the retained read context.
98    pub fn entities<M>(&self) -> crate::projected_filter::ReadEntityManager<'_, S, M>
99    where
100        M: crate::__codegen::EntityModel<Schema = S> + crate::__codegen::CompleteModel,
101    {
102        crate::projected_filter::ReadEntityManager::new(&self.installed, &self.tx)
103    }
104
105    /// Create a read-only exact relation manager borrowing this transaction.
106    /// Every derived filter terminal reuses the retained read context.
107    pub fn relations<M>(&self) -> crate::projected_filter::ReadRelationManager<'_, S, M>
108    where
109        M: crate::__codegen::RelationModel<Schema = S> + crate::__codegen::CompleteModel,
110    {
111        crate::projected_filter::ReadRelationManager::new(&self.installed, &self.tx)
112    }
113
114    /// Start one owner-branded query session borrowing this read context.
115    #[must_use]
116    pub fn query(&self) -> crate::query::QuerySession<'_, S> {
117        self.query_with_resources(
118            QueryExecutionResourceLimits::default(),
119            AnswerCancellation::default(),
120        )
121    }
122
123    /// Start one borrowed query session with one common tighten-only resource
124    /// policy and caller-owned cooperative cancellation signal.
125    #[must_use]
126    pub fn query_with_resources(
127        &self,
128        resources: QueryExecutionResourceLimits,
129        cancellation: AnswerCancellation,
130    ) -> crate::query::QuerySession<'_, S> {
131        crate::query::QuerySession::borrowed(
132            &self.installed,
133            Arc::clone(&self.registry),
134            &self.tx,
135            self.db.operation_limits(resources),
136            cancellation,
137        )
138    }
139
140    /// Close this read transaction without committing.
141    pub async fn close(self) -> Result<()> {
142        self.tx.close().await.map_err(Error::from_orm)
143    }
144}
145
146/// One client-owned open write transaction over a schema-bound database.
147///
148/// The wrapper is not cloneable and owns the sole retained engine context.
149/// Manager handles borrow the wrapper, so [`Self::commit`] and
150/// [`Self::rollback`] — which consume it — cannot run while a manager is
151/// retained, and a second terminal operation is unrepresentable. Operations
152/// never auto-commit: an operation error leaves terminal control with the
153/// caller, and dropping an open wrapper releases the context without commit.
154/// Under the successor runtime, a batch failure before mutation dispatch
155/// leaves the transaction active, while a failure after dispatch makes it
156/// rollback-only and [`Self::commit`] returns `transaction_rollback_only`.
157pub struct WriteTransaction<'db, S: Schema> {
158    tx: TransactionContext,
159    db: &'db Database<S>,
160}
161
162impl<S: Schema> std::fmt::Debug for WriteTransaction<'_, S> {
163    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        formatter
165            .debug_struct("WriteTransaction")
166            .field("database", &self.db.database_name())
167            .finish_non_exhaustive()
168    }
169}
170
171impl<'db, S: Schema> WriteTransaction<'db, S> {
172    pub(crate) async fn open(db: &'db Database<S>) -> Result<WriteTransaction<'db, S>> {
173        db.installed_schema().ok_or_else(schema_not_bound)?;
174        let tx = db
175            .inner_orm()
176            .transaction_context(TxType::Write)
177            .await
178            .map_err(Error::from_orm)?;
179        Ok(WriteTransaction { tx, db })
180    }
181
182    /// Create an exact entity manager borrowing this open transaction.
183    pub fn entities<M>(&self) -> TransactionEntityManager<'_, S, M>
184    where
185        M: EntityModel<Schema = S>,
186    {
187        TransactionEntityManager {
188            transaction: self,
189            marker: PhantomData,
190        }
191    }
192
193    /// Create an exact relation manager borrowing this open transaction.
194    pub fn relations<M>(&self) -> TransactionRelationManager<'_, S, M>
195    where
196        M: RelationModel<Schema = S>,
197    {
198        TransactionRelationManager {
199            transaction: self,
200            marker: PhantomData,
201        }
202    }
203
204    /// Commit every operation performed in this transaction, consuming it.
205    pub async fn commit(self) -> Result<()> {
206        if uses_successor_batch_runtime(self.installed()?) {
207            self.tx
208                .commit_sdk()
209                .await
210                .map_err(|error| Error::from_projected_batch(error, ModelValidationPhase::Input))
211        } else {
212            self.tx.commit().await.map_err(Error::from_orm)
213        }
214    }
215
216    /// Roll back every operation performed in this transaction, consuming it.
217    pub async fn rollback(self) -> Result<()> {
218        self.tx.rollback().await.map_err(Error::from_orm)
219    }
220
221    /// Roll back writes while retaining this transaction for more work.
222    pub async fn rollback_keep(&mut self) -> Result<()> {
223        self.tx.rollback().await.map_err(Error::from_orm)
224    }
225
226    fn installed(&self) -> Result<&InstalledRuntimeProjection> {
227        self.db
228            .installed_schema()
229            .map(Arc::as_ref)
230            .ok_or_else(schema_not_bound)
231    }
232}
233
234/// Schema-bound, model-branded exact entity manager borrowing one open
235/// client write transaction. Operations reuse the shared open context and
236/// never commit, roll back, or close it; errors are returned with the
237/// transaction left open for the caller to decide.
238pub struct TransactionEntityManager<'t, S: Schema, M: EntityModel<Schema = S>> {
239    transaction: &'t WriteTransaction<'t, S>,
240    marker: PhantomData<M>,
241}
242
243impl<'t, S: Schema, M: EntityModel<Schema = S>> Copy for TransactionEntityManager<'t, S, M> {}
244impl<'t, S: Schema, M: EntityModel<Schema = S>> Clone for TransactionEntityManager<'t, S, M> {
245    fn clone(&self) -> Self {
246        *self
247    }
248}
249
250impl<S, M> TransactionEntityManager<'_, S, M>
251where
252    S: Schema,
253    M: EntityModel<Schema = S> + CompleteModel,
254{
255    fn exact(
256        &self,
257    ) -> Result<(
258        TypeId,
259        &InstalledRuntimeProjection,
260        DynamicEntityManager<'static>,
261    )> {
262        let installed = self.transaction.installed()?;
263        let (id, descriptor): (TypeId, EntityDescriptor) = resolve_entity_authority(
264            M::TYPE_ID_JSON,
265            installed,
266            ModelValidationPhase::Input,
267            true,
268        )?;
269        let manager = DynamicEntityManager::with_canonical_transaction(
270            self.transaction.tx.clone(),
271            Arc::new(descriptor),
272        );
273        Ok((id, installed, manager))
274    }
275
276    /// Inserts one exact entity in the open transaction and returns its
277    /// complete freshly hydrated model without committing.
278    pub async fn insert(&self, input: M::Create) -> Result<M> {
279        let (id, installed, _manager) = self.exact()?;
280        let create = project_create(input, &id, installed)?;
281        let projected = ProjectedCrudExecutor::new(installed)
282            .insert_entity_in_transaction_with_compatibility(&self.transaction.tx, &create)
283            .await
284            .map_err(|error| {
285                Error::from_projected_crud(error, ModelKind::Entity, Some(CrudOperation::Insert))
286            })?;
287        materialize_projected(projected, installed)
288    }
289
290    /// Applies the exact key-or-insert put rule in the open transaction,
291    /// including complete replacement of non-key ownership for an existing
292    /// exact row, without committing.
293    pub async fn put(&self, input: M::Create) -> Result<M> {
294        let (id, installed, _manager) = self.exact()?;
295        let create = project_create(input, &id, installed)?;
296        let projected = ProjectedCrudExecutor::new(installed)
297            .put_entity_in_transaction_with_compatibility(&self.transaction.tx, &create)
298            .await
299            .map_err(|error| {
300                Error::from_projected_crud(error, ModelKind::Entity, Some(CrudOperation::Put))
301            })?;
302        materialize_projected(projected, installed)
303    }
304
305    /// Inserts each item in input order in the open transaction, returning
306    /// complete freshly hydrated models or one error, without committing.
307    /// A successor-runtime failure after mutation dispatch makes the
308    /// transaction rollback-only; a pre-dispatch failure leaves it active.
309    pub async fn insert_many(&self, inputs: Vec<M::Create>) -> Result<Vec<M>> {
310        if uses_successor_batch_runtime(self.transaction.installed()?) {
311            validate_binding_row_count(inputs.len())?;
312        }
313        self.write_many(inputs, false).await
314    }
315
316    /// Applies the per-item put rule in input order in the open transaction,
317    /// returning complete freshly hydrated models or one error, without
318    /// committing. A successor-runtime failure after mutation dispatch makes
319    /// the transaction rollback-only; a pre-dispatch failure leaves it active.
320    pub async fn put_many(&self, inputs: Vec<M::Create>) -> Result<Vec<M>> {
321        if uses_successor_batch_runtime(self.transaction.installed()?) {
322            validate_binding_row_count(inputs.len())?;
323        }
324        self.write_many(inputs, true).await
325    }
326
327    async fn write_many(&self, inputs: Vec<M::Create>, put: bool) -> Result<Vec<M>> {
328        let successor = uses_successor_batch_runtime(self.transaction.installed()?);
329        if inputs.is_empty() && !successor {
330            return Ok(Vec::new());
331        }
332        let (id, installed, manager) = self.exact()?;
333        if successor {
334            let rows = create_rows(installed, &id, inputs)?;
335            let operation = if put {
336                ProjectedBatchOperation::Put
337            } else {
338                ProjectedBatchOperation::Insert
339            };
340            let batch = prepare_batch(installed, id, operation, rows)?;
341            return execute_borrowed_things(&self.transaction.tx, installed, &batch).await;
342        }
343        let mut lowered = Vec::with_capacity(inputs.len());
344        for input in inputs {
345            lowered.push(lower_entity_create(input, &id, installed)?);
346        }
347        let iids = if put {
348            manager.put_many_exact(&lowered).await
349        } else {
350            manager.insert_many(&lowered).await
351        }
352        .map_err(Error::from_orm)?;
353        if iids.len() != lowered.len() {
354            return Err(Error::model_validation(
355                ModelValidationPhase::Hydration,
356                "iid_count_mismatch",
357                vec!["iid".into()],
358                "provider returned an unexpected IID count",
359                None,
360            ));
361        }
362        let mut out = Vec::with_capacity(iids.len());
363        for iid in iids {
364            out.push(rehydrate_written_entity(&manager, &iid, &id, installed).await?);
365        }
366        Ok(out)
367    }
368
369    /// Completely replaces non-key ownership on the exact model at canonical
370    /// `iid` in the open transaction, preserving that IID, without committing.
371    pub async fn update(&self, iid: &str, input: M::Create) -> Result<M> {
372        if !is_canonical_thing_iid(iid) {
373            return Err(invalid_iid());
374        }
375        let (id, installed, _manager) = self.exact()?;
376        let create = project_create(input, &id, installed)?;
377        let projected = ProjectedCrudExecutor::new(installed)
378            .update_entity_in_transaction_with_compatibility(&self.transaction.tx, iid, &create)
379            .await
380            .map_err(|error| {
381                Error::from_projected_crud(error, ModelKind::Entity, Some(CrudOperation::Update))
382            })?;
383        materialize_projected(projected, installed)
384    }
385
386    /// Deletes only the exact model at canonical `iid` in the open
387    /// transaction, without committing.
388    pub async fn delete(&self, iid: &str) -> Result<()> {
389        if !is_canonical_thing_iid(iid) {
390            return Err(invalid_iid());
391        }
392        let (id, installed, _manager) = self.exact()?;
393        ProjectedCrudExecutor::new(installed)
394            .delete_entity_by_iid_in_transaction_with_compatibility(&self.transaction.tx, &id, iid)
395            .await
396            .map_err(|error| {
397                Error::from_projected_crud(error, ModelKind::Entity, Some(CrudOperation::Delete))
398            })
399    }
400
401    /// Replaces each exact entity identified by its canonical IID in input
402    /// order without committing. Successor-runtime failures after mutation
403    /// dispatch make the transaction rollback-only.
404    pub async fn update_many(&self, inputs: Vec<(String, M::Create)>) -> Result<Vec<M>> {
405        let successor = uses_successor_batch_runtime(self.transaction.installed()?);
406        if successor {
407            validate_binding_row_count(inputs.len())?;
408        }
409        if inputs.is_empty() && !successor {
410            return Ok(Vec::new());
411        }
412        if successor {
413            let (id, installed, _manager) = self.exact()?;
414            let rows = update_rows(installed, &id, inputs)?;
415            let batch = prepare_batch(installed, id, ProjectedBatchOperation::Update, rows)?;
416            return execute_borrowed_things(&self.transaction.tx, installed, &batch).await;
417        }
418        if inputs.iter().any(|(iid, _)| !is_canonical_thing_iid(iid)) {
419            return Err(invalid_iid());
420        }
421        let (id, installed, manager) = self.exact()?;
422
423        let mut prepared = Vec::with_capacity(inputs.len());
424        for (iid, input) in inputs {
425            prepared.push((iid, lower_entity_create(input, &id, installed)?));
426        }
427        let mut output = Vec::with_capacity(prepared.len());
428        for (iid, attributes) in prepared {
429            manager
430                .update_exact(&iid, &attributes)
431                .await
432                .map_err(Error::from_orm)?;
433            output.push(rehydrate_written_entity(&manager, &iid, &id, installed).await?);
434        }
435        Ok(output)
436    }
437
438    /// Deletes every exact entity at the supplied canonical IIDs without
439    /// committing. Successor-runtime failures after mutation dispatch make
440    /// the transaction rollback-only.
441    pub async fn delete_many(&self, iids: &[String]) -> Result<()> {
442        let successor = uses_successor_batch_runtime(self.transaction.installed()?);
443        if successor {
444            validate_binding_row_count(iids.len())?;
445        }
446        if iids.is_empty() && !successor {
447            return Ok(());
448        }
449        if successor {
450            let (id, installed, _manager) = self.exact()?;
451            let batch = prepare_batch(
452                installed,
453                id,
454                ProjectedBatchOperation::Delete,
455                delete_rows(iids)?,
456            )?;
457            return execute_borrowed_delete(&self.transaction.tx, installed, &batch).await;
458        }
459        if iids.iter().any(|iid| !is_canonical_thing_iid(iid)) {
460            return Err(invalid_iid());
461        }
462        let (_id, _installed, manager) = self.exact()?;
463        for iid in iids {
464            manager
465                .delete_by_iid_exact(iid)
466                .await
467                .map_err(Error::from_orm)?;
468        }
469        Ok(())
470    }
471
472    /// Reads one exact model by canonical IID through the open transaction,
473    /// observing this transaction's uncommitted writes.
474    pub async fn get_by_iid(&self, iid: &str) -> Result<Option<M>> {
475        if !is_canonical_thing_iid(iid) {
476            return Err(invalid_iid());
477        }
478        let (id, installed, _manager) = self.exact()?;
479        ProjectedCrudExecutor::new(installed)
480            .get_entity_by_iid_in_transaction_with_compatibility(&self.transaction.tx, &id, iid)
481            .await
482            .map_err(|error| Error::from_projected_crud(error, ModelKind::Entity, None))?
483            .map(|projected| materialize_projected(projected, installed))
484            .transpose()
485    }
486
487    /// Reads all exact models through the open transaction, observing this
488    /// transaction's uncommitted writes.
489    pub async fn all(&self) -> Result<Vec<M>> {
490        let (id, installed, manager) = self.exact()?;
491        let rows = manager.all_exact().await.map_err(Error::from_orm)?;
492        rows.into_iter()
493            .map(|row| {
494                let hydrated = hydrate_entity(row, &id, installed)?;
495                M::materialize(&hydrated, &HydrationCapability::new())
496                    .map_err(|error| map_validation_error(error, ModelValidationPhase::Hydration))
497            })
498            .collect()
499    }
500
501    /// Counts only exact models through the open transaction.
502    pub async fn count(&self) -> Result<u64> {
503        let (id, installed, _manager) = self.exact()?;
504        ProjectedCrudExecutor::new(installed)
505            .count_entities_in_transaction_with_compatibility(&self.transaction.tx, &id)
506            .await
507            .map_err(|error| Error::from_projected_crud(error, ModelKind::Entity, None))
508    }
509}
510
511/// Schema-bound, model-branded exact relation manager borrowing one open
512/// client write transaction. Operations reuse the shared open context and
513/// never commit, roll back, or close it; errors are returned with the
514/// transaction left open for the caller to decide.
515pub struct TransactionRelationManager<'t, S: Schema, M: RelationModel<Schema = S>> {
516    transaction: &'t WriteTransaction<'t, S>,
517    marker: PhantomData<M>,
518}
519
520impl<'t, S: Schema, M: RelationModel<Schema = S>> Copy for TransactionRelationManager<'t, S, M> {}
521impl<'t, S: Schema, M: RelationModel<Schema = S>> Clone for TransactionRelationManager<'t, S, M> {
522    fn clone(&self) -> Self {
523        *self
524    }
525}
526
527impl<S, M> TransactionRelationManager<'_, S, M>
528where
529    S: Schema,
530    M: RelationModel<Schema = S> + CompleteModel,
531{
532    fn exact(
533        &self,
534    ) -> Result<(
535        TypeId,
536        &InstalledRuntimeProjection,
537        DynamicRelationManager<'static>,
538    )> {
539        let installed = self.transaction.installed()?;
540        let (id, descriptor): (TypeId, RelationDescriptor) = resolve_relation_authority(
541            M::TYPE_ID_JSON,
542            installed,
543            ModelValidationPhase::Input,
544            true,
545        )?;
546        let manager = DynamicRelationManager::with_canonical_transaction(
547            self.transaction.tx.clone(),
548            Arc::new(descriptor),
549        );
550        Ok((id, installed, manager))
551    }
552
553    /// Inserts one exact relation with its complete active role players in the
554    /// open transaction and returns its complete freshly hydrated model
555    /// without committing.
556    pub async fn insert(&self, input: M::Create) -> Result<M> {
557        let (id, installed, _manager) = self.exact()?;
558        let create = project_create(input, &id, installed)?;
559        let projected = ProjectedCrudExecutor::new(installed)
560            .insert_relation_in_transaction_with_compatibility(&self.transaction.tx, &create)
561            .await
562            .map_err(|error| {
563                Error::from_projected_crud(error, ModelKind::Relation, Some(CrudOperation::Insert))
564            })?;
565        materialize_projected(projected, installed)
566    }
567
568    /// Applies the exact key-or-insert put rule in the open transaction,
569    /// including complete replacement of non-key ownership and active role
570    /// players for an existing exact row, without committing.
571    pub async fn put(&self, input: M::Create) -> Result<M> {
572        let (id, installed, _manager) = self.exact()?;
573        let create = project_create(input, &id, installed)?;
574        let projected = ProjectedCrudExecutor::new(installed)
575            .put_relation_in_transaction_with_compatibility(&self.transaction.tx, &create)
576            .await
577            .map_err(|error| {
578                Error::from_projected_crud(error, ModelKind::Relation, Some(CrudOperation::Put))
579            })?;
580        materialize_projected(projected, installed)
581    }
582
583    /// Inserts each item in input order in the open transaction, returning
584    /// complete freshly hydrated models or one error, without committing.
585    /// A successor-runtime failure after mutation dispatch makes the
586    /// transaction rollback-only; a pre-dispatch failure leaves it active.
587    pub async fn insert_many(&self, inputs: Vec<M::Create>) -> Result<Vec<M>> {
588        if uses_successor_batch_runtime(self.transaction.installed()?) {
589            validate_binding_row_count(inputs.len())?;
590        }
591        self.write_many(inputs, false).await
592    }
593
594    /// Applies the per-item put rule in input order in the open transaction,
595    /// returning complete freshly hydrated models or one error, without
596    /// committing. A successor-runtime failure after mutation dispatch makes
597    /// the transaction rollback-only; a pre-dispatch failure leaves it active.
598    pub async fn put_many(&self, inputs: Vec<M::Create>) -> Result<Vec<M>> {
599        if uses_successor_batch_runtime(self.transaction.installed()?) {
600            validate_binding_row_count(inputs.len())?;
601        }
602        self.write_many(inputs, true).await
603    }
604
605    async fn write_many(&self, inputs: Vec<M::Create>, put: bool) -> Result<Vec<M>> {
606        let successor = uses_successor_batch_runtime(self.transaction.installed()?);
607        if inputs.is_empty() && !successor {
608            return Ok(Vec::new());
609        }
610        let (id, installed, manager) = self.exact()?;
611        if successor {
612            let rows = create_rows(installed, &id, inputs)?;
613            let operation = if put {
614                ProjectedBatchOperation::Put
615            } else {
616                ProjectedBatchOperation::Insert
617            };
618            let batch = prepare_batch(installed, id, operation, rows)?;
619            return execute_borrowed_things(&self.transaction.tx, installed, &batch).await;
620        }
621        let mut lowered: Vec<(DynamicAttributeMap, Vec<DynamicRolePlayerInput>)> =
622            Vec::with_capacity(inputs.len());
623        for input in inputs {
624            let prepared = lower_relation_create(input, &id, installed)?;
625            lowered.push((prepared.attributes, prepared.role_players));
626        }
627        let iids = if put {
628            manager.put_many_exact(&lowered).await
629        } else {
630            manager.insert_many(&lowered).await
631        }
632        .map_err(Error::from_orm)?;
633        if iids.len() != lowered.len() {
634            return Err(Error::model_validation(
635                ModelValidationPhase::Hydration,
636                "iid_count_mismatch",
637                vec!["iid".into()],
638                "provider returned an unexpected IID count",
639                None,
640            ));
641        }
642        let mut out = Vec::with_capacity(iids.len());
643        for iid in iids {
644            out.push(rehydrate_written_relation(&manager, &iid, &id, installed).await?);
645        }
646        Ok(out)
647    }
648
649    /// Completely replaces non-key ownership and the complete effective
650    /// active-role player set on the exact relation at canonical `iid` in the
651    /// open transaction, preserving that IID, without committing.
652    pub async fn update(&self, iid: &str, input: M::Create) -> Result<M> {
653        if !is_canonical_thing_iid(iid) {
654            return Err(invalid_iid());
655        }
656        let (id, installed, _manager) = self.exact()?;
657        let create = project_create(input, &id, installed)?;
658        let projected = ProjectedCrudExecutor::new(installed)
659            .update_relation_in_transaction_with_compatibility(&self.transaction.tx, iid, &create)
660            .await
661            .map_err(|error| {
662                Error::from_projected_crud(error, ModelKind::Relation, Some(CrudOperation::Update))
663            })?;
664        materialize_projected(projected, installed)
665    }
666
667    /// Deletes only the exact relation at canonical `iid` in the open
668    /// transaction, without committing.
669    pub async fn delete(&self, iid: &str) -> Result<()> {
670        if !is_canonical_thing_iid(iid) {
671            return Err(invalid_iid());
672        }
673        let (id, installed, _manager) = self.exact()?;
674        ProjectedCrudExecutor::new(installed)
675            .delete_relation_by_iid_in_transaction_with_compatibility(
676                &self.transaction.tx,
677                &id,
678                iid,
679            )
680            .await
681            .map_err(|error| {
682                Error::from_projected_crud(error, ModelKind::Relation, Some(CrudOperation::Delete))
683            })
684    }
685
686    /// Replaces each exact relation identified by its canonical IID in input
687    /// order without committing. Successor-runtime failures after mutation
688    /// dispatch make the transaction rollback-only.
689    pub async fn update_many(&self, inputs: Vec<(String, M::Create)>) -> Result<Vec<M>> {
690        let successor = uses_successor_batch_runtime(self.transaction.installed()?);
691        if successor {
692            validate_binding_row_count(inputs.len())?;
693        }
694        if inputs.is_empty() && !successor {
695            return Ok(Vec::new());
696        }
697        if successor {
698            let (id, installed, _manager) = self.exact()?;
699            let rows = update_rows(installed, &id, inputs)?;
700            let batch = prepare_batch(installed, id, ProjectedBatchOperation::Update, rows)?;
701            return execute_borrowed_things(&self.transaction.tx, installed, &batch).await;
702        }
703        if inputs.iter().any(|(iid, _)| !is_canonical_thing_iid(iid)) {
704            return Err(invalid_iid());
705        }
706        let (id, installed, manager) = self.exact()?;
707
708        let mut prepared = Vec::with_capacity(inputs.len());
709        for (iid, input) in inputs {
710            prepared.push((iid, lower_relation_create(input, &id, installed)?));
711        }
712        let mut output = Vec::with_capacity(prepared.len());
713        for (iid, replacement) in prepared {
714            manager
715                .update_exact(&iid, &replacement.attributes, &replacement.role_players)
716                .await
717                .map_err(Error::from_orm)?;
718            output.push(rehydrate_written_relation(&manager, &iid, &id, installed).await?);
719        }
720        Ok(output)
721    }
722
723    /// Deletes every exact relation at the supplied canonical IIDs without
724    /// committing. Successor-runtime failures after mutation dispatch make
725    /// the transaction rollback-only.
726    pub async fn delete_many(&self, iids: &[String]) -> Result<()> {
727        let successor = uses_successor_batch_runtime(self.transaction.installed()?);
728        if successor {
729            validate_binding_row_count(iids.len())?;
730        }
731        if iids.is_empty() && !successor {
732            return Ok(());
733        }
734        if successor {
735            let (id, installed, _manager) = self.exact()?;
736            let batch = prepare_batch(
737                installed,
738                id,
739                ProjectedBatchOperation::Delete,
740                delete_rows(iids)?,
741            )?;
742            return execute_borrowed_delete(&self.transaction.tx, installed, &batch).await;
743        }
744        if iids.iter().any(|iid| !is_canonical_thing_iid(iid)) {
745            return Err(invalid_iid());
746        }
747        let (_id, _installed, manager) = self.exact()?;
748        for iid in iids {
749            manager
750                .delete_by_iid_exact(iid)
751                .await
752                .map_err(Error::from_orm)?;
753        }
754        Ok(())
755    }
756
757    /// Reads one exact coalesced relation by canonical IID through the open
758    /// transaction, observing this transaction's uncommitted writes.
759    pub async fn get_by_iid(&self, iid: &str) -> Result<Option<M>> {
760        if !is_canonical_thing_iid(iid) {
761            return Err(invalid_iid());
762        }
763        let (id, installed, _manager) = self.exact()?;
764        ProjectedCrudExecutor::new(installed)
765            .get_relation_by_iid_in_transaction_with_compatibility(&self.transaction.tx, &id, iid)
766            .await
767            .map_err(|error| Error::from_projected_crud(error, ModelKind::Relation, None))?
768            .map(|projected| materialize_projected(projected, installed))
769            .transpose()
770    }
771
772    /// Reads all exact coalesced relations through the open transaction,
773    /// observing this transaction's uncommitted writes.
774    pub async fn all(&self) -> Result<Vec<M>> {
775        let (id, installed, manager) = self.exact()?;
776        let rows = manager.all_exact().await.map_err(Error::from_orm)?;
777        rows.into_iter()
778            .map(|row| {
779                let hydrated = hydrate_relation(row, &id, installed)?;
780                M::materialize(&hydrated, &HydrationCapability::new())
781                    .map_err(|error| map_validation_error(error, ModelValidationPhase::Hydration))
782            })
783            .collect()
784    }
785
786    /// Counts only exact relations through the open transaction.
787    pub async fn count(&self) -> Result<u64> {
788        let (id, installed, _manager) = self.exact()?;
789        ProjectedCrudExecutor::new(installed)
790            .count_relations_in_transaction_with_compatibility(&self.transaction.tx, &id)
791            .await
792            .map_err(|error| Error::from_projected_crud(error, ModelKind::Relation, None))
793    }
794}