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_with_executor;
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).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 = update_record_with_executor(
100 &mut **tx,
101 self.runtime.pool(),
102 self.descriptor,
103 self.id,
104 self.input,
105 ctx,
106 self.if_match,
107 )
108 .await?;
109 if emits_event {
110 enqueue_event_outbox(
111 &mut **tx,
112 self.descriptor.schema_name,
113 ModelEventKind::Updated,
114 &record,
115 )
116 .await?;
117 }
118 let mut audit_event = None;
119 if audit_enabled {
120 let after = serde_json::to_value(&record).ok();
121 let event = build_audit_event(
122 self.descriptor,
123 AuditOperation::Update,
124 before_snapshot,
125 after,
126 ctx,
127 );
128 enqueue_audit_event(&mut **tx, &event).await?;
129 audit_event = Some(event);
130 }
131 Ok(RunInTxOutcome::new(
132 record,
133 audit_event.into_iter().collect(),
134 ))
135 }
136
137 pub async fn run(self, ctx: &CratestackContext) -> Result<M, CratestackError>
138 where
139 for<'r> M: Send + Unpin + sqlx::FromRow<'r, sqlx::postgres::PgRow> + serde::Serialize,
140 PK: Send + Clone + sqlx::Type<sqlx::Postgres> + for<'q> sqlx::Encode<'q, sqlx::Postgres>,
141 {
142 super::update_run::run_update(
143 self.runtime,
144 self.descriptor,
145 self.id,
146 self.input,
147 self.if_match,
148 ctx,
149 )
150 .await
151 }
152}