cratestack_sqlx/query/write/
update.rs1use cratestack_core::{AuditOperation, CratestackContext, CratestackError, ModelEventKind};
4
5use crate::audit::{
6 RunInTxOutcome, build_audit_event, enqueue_audit_event, ensure_audit_table, fetch_for_audit,
7};
8use crate::descriptor::{enqueue_event_outbox, ensure_event_outbox_table};
9use crate::{ModelDescriptor, SqlxRuntime, UpdateModelInput, sqlx};
10
11use super::preview::render_update_preview_sql;
12use super::update_exec::update_record_in_conn;
13
14#[derive(Debug, Clone)]
15pub struct UpdateRecord<'a, M: 'static, PK: 'static> {
16 pub(crate) runtime: &'a SqlxRuntime,
17 pub(crate) descriptor: &'static ModelDescriptor<M, PK>,
18 pub(crate) id: PK,
19}
20
21impl<'a, M: 'static, PK: 'static> UpdateRecord<'a, M, PK> {
22 pub fn set<I>(self, input: I) -> UpdateRecordSet<'a, M, PK, I> {
23 UpdateRecordSet {
24 runtime: self.runtime,
25 descriptor: self.descriptor,
26 id: self.id,
27 input,
28 if_match: None,
29 }
30 }
31}
32
33#[derive(Debug, Clone)]
34pub struct UpdateRecordSet<'a, M: 'static, PK: 'static, I> {
35 pub(crate) runtime: &'a SqlxRuntime,
36 pub(crate) descriptor: &'static ModelDescriptor<M, PK>,
37 pub(crate) id: PK,
38 pub(crate) input: I,
39 pub(crate) if_match: Option<i64>,
40}
41
42impl<'a, M: 'static, PK: 'static, I> UpdateRecordSet<'a, M, PK, I>
43where
44 I: UpdateModelInput<M>,
45{
46 pub fn if_match(mut self, expected: i64) -> Self {
49 self.if_match = Some(expected);
50 self
51 }
52
53 pub fn preview_sql(&self) -> String {
54 let values = self.input.sql_values();
55 let columns: Vec<&str> = values.iter().map(|v| v.column).collect();
56 render_update_preview_sql(
57 self.descriptor.table_name,
58 self.descriptor.primary_key,
59 self.descriptor.version_column,
60 &columns,
61 &self.descriptor.select_projection(),
62 )
63 }
64
65 pub async fn run_in_tx<'tx>(
70 self,
71 tx: &mut sqlx::Transaction<'tx, sqlx::Postgres>,
72 ctx: &CratestackContext,
73 ) -> Result<RunInTxOutcome<M>, CratestackError>
74 where
75 for<'r> M: Send + Unpin + sqlx::FromRow<'r, sqlx::postgres::PgRow> + serde::Serialize,
76 PK: Send + Clone + sqlx::Type<sqlx::Postgres> + for<'q> sqlx::Encode<'q, sqlx::Postgres>,
77 {
78 if self.descriptor.version_column.is_some() && self.if_match.is_none() {
79 return Err(CratestackError::PreconditionFailed(
80 "If-Match header required for versioned model".to_owned(),
81 ));
82 }
83 let emits_event = self.descriptor.emits(ModelEventKind::Updated);
84 let audit_enabled = self.descriptor.audit_enabled;
85 if emits_event {
86 ensure_event_outbox_table(&mut **tx).await?;
87 }
88 if audit_enabled {
89 ensure_audit_table(self.runtime, &mut **tx).await?;
90 }
91 let before_record = if audit_enabled {
92 fetch_for_audit(&mut **tx, self.descriptor, self.id.clone()).await?
93 } else {
94 None
95 };
96 let before_snapshot = before_record
97 .as_ref()
98 .and_then(|m| serde_json::to_value(m).ok());
99 let record =
100 update_record_in_conn(tx, self.descriptor, self.id, self.input, ctx, self.if_match)
101 .await?;
102 if emits_event {
103 enqueue_event_outbox(
104 &mut **tx,
105 self.descriptor.schema_name,
106 ModelEventKind::Updated,
107 &record,
108 )
109 .await?;
110 }
111 let mut audit_event = None;
112 if audit_enabled {
113 let after = serde_json::to_value(&record).ok();
114 let event = build_audit_event(
115 self.descriptor,
116 AuditOperation::Update,
117 before_snapshot,
118 after,
119 ctx,
120 );
121 enqueue_audit_event(&mut **tx, &event).await?;
122 audit_event = Some(event);
123 }
124 Ok(RunInTxOutcome::new(
125 record,
126 audit_event.into_iter().collect(),
127 ))
128 }
129
130 pub async fn run(self, ctx: &CratestackContext) -> Result<M, CratestackError>
131 where
132 for<'r> M: Send + Unpin + sqlx::FromRow<'r, sqlx::postgres::PgRow> + serde::Serialize,
133 PK: Send + Clone + sqlx::Type<sqlx::Postgres> + for<'q> sqlx::Encode<'q, sqlx::Postgres>,
134 {
135 if let Some(bound) = self.runtime.bound() {
139 let emits = self
140 .descriptor
141 .emits(cratestack_core::ModelEventKind::Updated);
142 let outcome = crate::bound::in_bound_savepoint!(bound, |sp| self.run_in_tx(sp, ctx))?;
143 return Ok(bound.settle(outcome, emits));
144 }
145 super::update_run::run_update(
146 self.runtime,
147 self.descriptor,
148 self.id,
149 self.input,
150 self.if_match,
151 ctx,
152 )
153 .await
154 }
155}