Skip to main content

cratestack_sqlx/query/batch/
upsert.rs

1//! `batch_upsert` driver — dedupes inputs by PK (different shape from
2//! `batch_update` because `UpsertModelInput` exposes a PK getter), then
3//! fans out to [`super::upsert_item::run_upsert_item`].
4
5use cratestack_core::{BatchResponse, CratestackContext, CratestackError, ModelEventKind};
6
7use crate::audit::{dispatch_audit_sink, ensure_audit_table};
8use crate::descriptor::ensure_event_outbox_table;
9use crate::{ModelDescriptor, SqlValue, SqlxRuntime, UpsertModelInput, sqlx};
10
11use super::upsert_item::run_upsert_item;
12use super::validate::{reject_duplicate_sql_values, validate_batch_size};
13
14#[derive(Debug, Clone)]
15pub struct BatchUpsert<'a, M: 'static, PK: 'static, I> {
16    pub(crate) runtime: &'a SqlxRuntime,
17    pub(crate) descriptor: &'static ModelDescriptor<M, PK>,
18    pub(crate) inputs: Vec<I>,
19}
20
21impl<'a, M: 'static, PK: 'static, I> BatchUpsert<'a, M, PK, I>
22where
23    I: UpsertModelInput<M>,
24{
25    pub async fn run(self, ctx: &CratestackContext) -> Result<BatchResponse<M>, CratestackError>
26    where
27        for<'r> M: Send + Unpin + sqlx::FromRow<'r, sqlx::postgres::PgRow> + serde::Serialize,
28        PK: Send + sqlx::Type<sqlx::Postgres> + for<'q> sqlx::Encode<'q, sqlx::Postgres>,
29    {
30        validate_batch_size(self.inputs.len())?;
31        // Upsert dedup runs on the per-input primary key — keeps two
32        // callers from both producing batches with the same key and
33        // ending up with surprising "second write wins" semantics.
34        let pks: Vec<SqlValue> = self
35            .inputs
36            .iter()
37            .map(UpsertModelInput::primary_key_value)
38            .collect();
39        reject_duplicate_sql_values(&pks)?;
40        if self.inputs.is_empty() {
41            return Ok(BatchResponse::from_results(vec![]));
42        }
43
44        let emits_created = self.descriptor.emits(ModelEventKind::Created);
45        let emits_updated = self.descriptor.emits(ModelEventKind::Updated);
46        let audit_enabled = self.descriptor.audit_enabled;
47
48        // A savepoint of the `@isolation` transaction when there is one
49        // (docs/design/procedure-isolation.md §4).
50        let (per_item, audit_events) = crate::bound::in_write_tx!(self.runtime, |tx| async {
51            if emits_created || emits_updated {
52                ensure_event_outbox_table(&mut **tx).await?;
53            }
54            if audit_enabled {
55                ensure_audit_table(self.runtime, &mut **tx).await?;
56            }
57
58            let mut per_item: Vec<Result<M, CratestackError>> =
59                Vec::with_capacity(self.inputs.len());
60            let mut audit_events = Vec::new();
61            for input in self.inputs {
62                let (outcome, audit_event) = run_upsert_item(
63                    tx,
64                    self.descriptor,
65                    input,
66                    ctx,
67                    emits_created,
68                    emits_updated,
69                    audit_enabled,
70                )
71                .await?;
72                per_item.push(outcome);
73                audit_events.extend(audit_event);
74            }
75
76            Ok((per_item, audit_events))
77        })?;
78
79        if emits_created || emits_updated {
80            let _ = self.runtime.drain_event_outbox().await;
81        }
82        dispatch_audit_sink(self.runtime, &audit_events).await;
83
84        Ok(BatchResponse::from_results(per_item))
85    }
86}