1use crate::mutation::preparation::MutationPreparationContext;
9use crate::{
10 mutation::{
11 assignment::{validate_view_checks, ViewCheckContext},
12 conflict::update::{InsertConflictLocks, InsertConflictPreparation},
13 constraints::{
14 lock_document_key_dependencies, partition_insert_target,
15 validate_document_non_key_constraints, validate_key_constraints,
16 validate_key_constraints_with_previous, ConstraintStatement,
17 },
18 identity::refresh_insert_identity_after_trigger,
19 prepared::PreparedInsertConflict,
20 returning::{build_returning_row, ReturningProjectionRow},
21 row_images::{MutationRowImage, MutationRowImages},
22 staging::stage_prepared_document_rewrite,
23 },
24 query::CteScope,
25};
26use std::sync::Arc;
27use uqa_core::DocId;
28use uqa_sql::{plan::InsertPlan, SQLError, SQLParam};
29use uqa_storage::document_store::Document;
30pub struct StagedValuesInsertRow {
31 pub target_table: String,
32 pub document: Arc<Document>,
33 pub prepared: PreparedInsertConflict,
34 pub returning: Option<crate::OwnedPhysicalRow>,
35 pub after_row_events: Vec<crate::mutation::triggers::AfterRowTriggerEvent>,
36 pub prepared_effect: bool,
37}
38
39#[expect(
40 clippy::too_many_arguments,
41 reason = "keeps DML row-image inputs aligned"
42)]
43pub fn prepare_values_insert_row<S: Clone + 'static>(
44 services: MutationPreparationContext<'_, S>,
45 stmt: &InsertPlan,
46 statement: ConstraintStatement<'_>,
47 params: &[SQLParam],
48 snapshot_scope: &CteScope<S>,
49 conflict_update_columns: &[String],
50 id_column: &str,
51 identity_source: crate::mutation::identity::IdentitySource,
52 target_table: String,
53 mut document: Document,
54 mut insert_identity: (DocId, bool),
55 conflict_locks: &mut InsertConflictLocks,
56) -> Result<Option<StagedValuesInsertRow>, SQLError> {
57 let Some(triggered_document) = crate::mutation::triggers::fire_before_row_triggers(
58 &services.referential.triggers,
59 &target_table,
60 uqa_sql::ast::TriggerEvent::Insert,
61 insert_identity.0,
62 None,
63 Some(&document),
64 &[],
65 )?
66 else {
67 return Ok(None);
68 };
69 document = triggered_document;
70 crate::mutation::assignment::refresh_stored_generated_columns(
71 services.referential.assignment,
72 &target_table,
73 &mut document,
74 )?;
75 refresh_insert_identity_after_trigger(
76 crate::mutation::identity::IdentityAllocationContext {
77 identifiers: services.referential.identifiers,
78 partitions: services.referential.constraints.partitions.catalog,
79 },
80 &target_table,
81 id_column,
82 identity_source,
83 &document,
84 &mut insert_identity,
85 )?;
86 let trigger_target = partition_insert_target(
87 services.referential.constraints,
88 statement,
89 &stmt.table,
90 &document,
91 params,
92 stmt.include_descendants,
93 )?;
94 if trigger_target != target_table {
95 return Err(SQLError::Routine {
96 sqlstate: "0A000".into(),
97 message: "moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported".into(),
98 });
99 }
100 let prepared = if let Some(on_conflict) = stmt.on_conflict.as_ref() {
101 conflict_locks.prepare_document(InsertConflictPreparation {
102 context: services.referential,
103 target_table: &stmt.table,
104 table: &target_table,
105 target_qualifier: &stmt.target_qualifier,
106 on_conflict,
107 document: &document,
108 params,
109 scope: snapshot_scope,
110 })?
111 } else {
112 let _key_locks = lock_document_key_dependencies(
113 services.referential.constraints,
114 &target_table,
115 &document,
116 None,
117 )?;
118 PreparedInsertConflict::Unresolved
119 };
120 let mut prepared = attach_prepared_insert_identity(prepared, insert_identity);
121 let prepared_effect = !matches!(&prepared, PreparedInsertConflict::Skip);
122 let document = Arc::new(document);
123 let (returning, after_row_events) = stage_prepared_insert_row(
124 PreparedInsertRowContext {
125 services,
126 stmt,
127 statement,
128 storage_table: &target_table,
129 document: document.as_ref(),
130 shared_document: Some(&document),
131 conflict_update_columns,
132 params,
133 scope: snapshot_scope,
134 },
135 &mut prepared,
136 )?;
137 Ok(Some(StagedValuesInsertRow {
138 target_table,
139 document,
140 prepared,
141 returning,
142 after_row_events,
143 prepared_effect,
144 }))
145}
146
147pub fn attach_prepared_insert_identity(
148 prepared: PreparedInsertConflict,
149 (doc_id, supplied): (DocId, bool),
150) -> PreparedInsertConflict {
151 match prepared {
152 PreparedInsertConflict::Unresolved => PreparedInsertConflict::Insert { doc_id, supplied },
153 resolved => resolved,
154 }
155}
156
157#[expect(clippy::too_many_lines, reason = "preserves DML lock and event order")]
158pub fn stage_prepared_insert_row<S: Clone + 'static>(
159 context: PreparedInsertRowContext<'_, S>,
160 prepared: &mut PreparedInsertConflict,
161) -> Result<
162 (
163 Option<crate::OwnedPhysicalRow>,
164 Vec<crate::mutation::triggers::AfterRowTriggerEvent>,
165 ),
166 SQLError,
167> {
168 let PreparedInsertRowContext {
169 services,
170 stmt,
171 statement,
172 storage_table,
173 document,
174 shared_document,
175 conflict_update_columns,
176 params,
177 scope,
178 } = context;
179 validate_document_non_key_constraints(
180 services.referential.constraints,
181 Some(statement),
182 storage_table,
183 document,
184 params,
185 )?;
186 let (images, after_row_events) = match prepared {
187 PreparedInsertConflict::Insert { doc_id, .. } => {
188 validate_key_constraints(
189 services.referential.constraints,
190 storage_table,
191 document,
192 None,
193 )?;
194 validate_view_checks(ViewCheckContext {
195 services: services.referential.assignment,
196 constraints: services.referential.constraints,
197 statement,
198 table: &stmt.table,
199 storage_table,
200 target_qualifier: &stmt.target_qualifier,
201 doc_id: *doc_id,
202 document,
203 checks: &stmt.view_checks,
204 params,
205 scope,
206 })?;
207 if let Some(shared_document) = shared_document {
208 services.staging.commands.stage_shared_command_document(
209 storage_table,
210 *doc_id,
211 Some(Arc::clone(shared_document)),
212 )?;
213 } else {
214 services.staging.commands.stage_command_document(
215 storage_table,
216 *doc_id,
217 Some(document.clone()),
218 )?;
219 }
220 let mut after_row_events = Vec::new();
221 if let Some(event) = crate::mutation::triggers::AfterRowTriggerEvent::prepare(
222 &services.referential.triggers,
223 crate::mutation::triggers::AfterRowTriggerInput {
224 table: storage_table,
225 event: uqa_sql::ast::TriggerEvent::Insert,
226 old_doc_id: *doc_id,
227 new_doc_id: *doc_id,
228 old_document: None,
229 new_document: Some(document),
230 updated_columns: &[],
231 foreign_key_checks: crate::mutation::referential::checks::referencing_checks(
232 services.referential.constraints,
233 storage_table,
234 *doc_id,
235 document,
236 None,
237 )?,
238 },
239 )? {
240 after_row_events.push(event);
241 }
242 (
243 MutationRowImages {
244 old: None,
245 new: Some(MutationRowImage {
246 storage_table: storage_table.to_string(),
247 doc_id: *doc_id,
248 document,
249 metadata: crate::mutation::rows::new_tuple_metadata(
250 services.referential.assignment.rows,
251 )?,
252 }),
253 },
254 after_row_events,
255 )
256 }
257 PreparedInsertConflict::Updated(prepared) => {
258 let old_storage_table = prepared.table.clone();
259 let new_storage_table = prepared
260 .destination
261 .as_ref()
262 .map_or_else(|| old_storage_table.clone(), |(table, _)| table.clone());
263 let old_doc_id = prepared.doc_id;
264 let primary_key_doc_id = prepared.relocation;
265 let new_doc_id = prepared
266 .destination
267 .as_ref()
268 .map(|(_, doc_id)| *doc_id)
269 .or(primary_key_doc_id)
270 .unwrap_or(old_doc_id);
271 validate_key_constraints_with_previous(
272 services.referential.constraints,
273 &new_storage_table,
274 &prepared.new_document,
275 (new_storage_table == old_storage_table).then_some(old_doc_id),
276 (new_storage_table == old_storage_table).then_some(&prepared.old_document),
277 )?;
278 validate_view_checks(ViewCheckContext {
279 services: services.referential.assignment,
280 constraints: services.referential.constraints,
281 statement,
282 table: &stmt.table,
283 storage_table: &new_storage_table,
284 target_qualifier: &stmt.target_qualifier,
285 doc_id: new_doc_id,
286 document: &prepared.new_document,
287 checks: &stmt.view_checks,
288 params,
289 scope,
290 })?;
291 let old_metadata = crate::mutation::rows::existing_tuple_metadata(
292 services.referential.assignment.rows,
293 &old_storage_table,
294 old_doc_id,
295 )?;
296 let new_metadata =
297 crate::mutation::rows::new_tuple_metadata(services.referential.assignment.rows)?;
298 let mut after_row_events = Vec::new();
299 let doc_id = stage_prepared_document_rewrite(
300 services.staging,
301 prepared,
302 params,
303 statement,
304 Some(conflict_update_columns),
305 &mut after_row_events,
306 )?;
307 (
308 MutationRowImages {
309 old: Some(MutationRowImage {
310 storage_table: old_storage_table,
311 doc_id: old_doc_id,
312 document: &prepared.old_document,
313 metadata: old_metadata,
314 }),
315 new: Some(MutationRowImage {
316 storage_table: new_storage_table,
317 doc_id,
318 document: &prepared.new_document,
319 metadata: new_metadata,
320 }),
321 },
322 after_row_events,
323 )
324 }
325 PreparedInsertConflict::Skip => return Ok((None, Vec::new())),
326 PreparedInsertConflict::Unresolved => {
327 return Err(SQLError::Internal(
328 "INSERT command overlay has no prepared document identity".into(),
329 ))
330 }
331 };
332 let returning = if stmt.returning.is_empty() {
333 None
334 } else {
335 Some(build_returning_row(
336 services.returning,
337 ReturningProjectionRow {
338 table: &stmt.table,
339 target_qualifier: &stmt.target_qualifier,
340 images,
341 aliases: &stmt.returning_aliases,
342 context: None,
343 },
344 &stmt.returning,
345 params,
346 scope,
347 )?)
348 };
349 Ok((returning, after_row_events))
350}
351
352pub struct PreparedInsertRowContext<'a, S: Clone + 'static> {
353 pub services: MutationPreparationContext<'a, S>,
354 pub stmt: &'a InsertPlan,
355 pub statement: ConstraintStatement<'a>,
357 pub storage_table: &'a str,
358 pub document: &'a Document,
359 pub shared_document: Option<&'a Arc<Document>>,
360 pub conflict_update_columns: &'a [String],
361 pub params: &'a [SQLParam],
362 pub scope: &'a CteScope<S>,
363}