Skip to main content

uqa_execution/mutation/
staging.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Stage candidate row images and capture trigger events before durable publication.
8use super::triggers::events::AfterRowEventSink;
9use super::{
10    constraints::{
11        context::ConstraintContext, validate_document_non_key_constraints,
12        validate_document_rewrite_constraints, validate_key_constraints, ConstraintStatement,
13    },
14    prepared::{PreparedDocumentDelete, PreparedDocumentRewrite},
15    triggers::context::TriggerContext,
16};
17use uqa_core::DocId;
18use uqa_sql::{SQLError, SQLParam};
19use uqa_storage::document_store::Document;
20pub trait MutationCommandRows {
21    fn stage_shared_command_document(
22        &self,
23        table: &str,
24        doc_id: DocId,
25        document: Option<std::sync::Arc<Document>>,
26    ) -> Result<(), SQLError>;
27    fn stage_command_document(
28        &self,
29        table: &str,
30        doc_id: DocId,
31        document: Option<Document>,
32    ) -> Result<(), SQLError>;
33}
34#[derive(Clone, Copy)]
35pub struct MutationStagingContext<'a> {
36    pub commands: &'a dyn MutationCommandRows,
37    pub constraints: ConstraintContext<'a>,
38    pub triggers: TriggerContext<'a>,
39}
40/// Stage the row that `statement` writes in place of a row, and queue the events of the change.
41#[expect(clippy::too_many_lines, reason = "preserves DML lock and event order")]
42pub fn stage_prepared_document_rewrite(
43    context: MutationStagingContext<'_>,
44    prepared: &mut PreparedDocumentRewrite,
45    params: &[SQLParam],
46    statement: ConstraintStatement<'_>,
47    root_updated_columns: Option<&[String]>,
48    after_row_events: &mut dyn AfterRowEventSink,
49) -> Result<DocId, SQLError> {
50    let trigger_updated_columns = root_updated_columns
51        .or_else(|| prepared.referential_columns())
52        .map(<[String]>::to_vec);
53    if let Some(delete) = prepared.partition_move_delete.as_deref() {
54        stage_document_delete(
55            &context,
56            delete,
57            crate::mutation::referential::checks::moved_row_delete_checks(
58                context.constraints,
59                &delete.table,
60                &delete.document,
61            )?,
62            after_row_events,
63        )?;
64        if prepared.capture_partition_move_update_transition {
65            if let Some(updated_columns) = trigger_updated_columns.as_deref() {
66                if let Some(event) =
67                    crate::mutation::triggers::AfterRowTriggerEvent::prepare_transition_capture(
68                        &context.triggers,
69                        crate::mutation::triggers::AfterRowTriggerInput {
70                            table: &prepared.table,
71                            event: uqa_sql::ast::TriggerEvent::Update,
72                            old_doc_id: prepared.doc_id,
73                            new_doc_id: prepared.doc_id,
74                            old_document: Some(&prepared.old_document),
75                            new_document: None,
76                            updated_columns,
77                            foreign_key_checks: Vec::new(),
78                        },
79                    )?
80                {
81                    after_row_events.push_event(event, &context.triggers)?;
82                }
83            }
84        }
85        return Ok(prepared.doc_id);
86    }
87    let rewritten_doc_id =
88        if let Some((destination_table, destination_doc_id)) = prepared.destination.as_ref() {
89            validate_document_non_key_constraints(
90                context.constraints,
91                Some(statement),
92                destination_table,
93                &prepared.new_document,
94                params,
95            )?;
96            validate_key_constraints(
97                context.constraints,
98                destination_table,
99                &prepared.new_document,
100                None,
101            )?;
102            context
103                .commands
104                .stage_command_document(&prepared.table, prepared.doc_id, None)?;
105            context.commands.stage_command_document(
106                destination_table,
107                *destination_doc_id,
108                Some(prepared.new_document.clone()),
109            )?;
110            *destination_doc_id
111        } else {
112            validate_document_rewrite_constraints(
113                context.constraints,
114                statement,
115                &prepared.table,
116                &prepared.old_document,
117                &prepared.new_document,
118                params,
119                prepared.doc_id,
120            )?;
121            let rewritten_doc_id = prepared.relocation.unwrap_or(prepared.doc_id);
122            if rewritten_doc_id != prepared.doc_id {
123                context
124                    .commands
125                    .stage_command_document(&prepared.table, prepared.doc_id, None)?;
126            }
127            context.commands.stage_command_document(
128                &prepared.table,
129                rewritten_doc_id,
130                Some(prepared.new_document.clone()),
131            )?;
132            rewritten_doc_id
133        };
134    if let Some((destination_table, _)) = prepared.destination.as_ref() {
135        if let Some(event) = crate::mutation::triggers::AfterRowTriggerEvent::prepare(
136            &context.triggers,
137            crate::mutation::triggers::AfterRowTriggerInput {
138                table: &prepared.table,
139                event: uqa_sql::ast::TriggerEvent::Delete,
140                old_doc_id: prepared.doc_id,
141                new_doc_id: prepared.doc_id,
142                old_document: Some(&prepared.old_document),
143                new_document: None,
144                updated_columns: &[],
145                // The table the UPDATE names checks the keys of its foreign keys that the moved row held.
146                foreign_key_checks: crate::mutation::referential::checks::moved_row_delete_checks(
147                    context.constraints,
148                    &prepared.table,
149                    &prepared.old_document,
150                )?,
151            },
152        )? {
153            after_row_events.push_event(event, &context.triggers)?;
154        }
155        if let Some(event) = crate::mutation::triggers::AfterRowTriggerEvent::prepare(
156            &context.triggers,
157            crate::mutation::triggers::AfterRowTriggerInput {
158                table: destination_table,
159                event: uqa_sql::ast::TriggerEvent::Insert,
160                old_doc_id: rewritten_doc_id,
161                new_doc_id: rewritten_doc_id,
162                old_document: None,
163                new_document: Some(&prepared.new_document),
164                updated_columns: &[],
165                foreign_key_checks: crate::mutation::referential::checks::referencing_checks(
166                    context.constraints,
167                    destination_table,
168                    rewritten_doc_id,
169                    &prepared.new_document,
170                    None,
171                )?,
172            },
173        )? {
174            after_row_events.push_event(event, &context.triggers)?;
175        }
176        if prepared.capture_partition_move_update_transition {
177            if let Some(updated_columns) = trigger_updated_columns.as_deref() {
178                if let Some(event) =
179                    crate::mutation::triggers::AfterRowTriggerEvent::prepare_transition_capture(
180                        &context.triggers,
181                        crate::mutation::triggers::AfterRowTriggerInput {
182                            table: &prepared.table,
183                            event: uqa_sql::ast::TriggerEvent::Update,
184                            old_doc_id: prepared.doc_id,
185                            new_doc_id: rewritten_doc_id,
186                            old_document: Some(&prepared.old_document),
187                            new_document: Some(&prepared.new_document),
188                            updated_columns,
189                            foreign_key_checks: Vec::new(),
190                        },
191                    )?
192                {
193                    after_row_events.push_event(event, &context.triggers)?;
194                }
195            }
196        }
197        // `PostgreSQL` fires the update triggers of the UPDATE's root for the referenced keys of a row it moved, after the row's insert into its new partition.
198        if let Some(event) = crate::mutation::triggers::AfterRowTriggerEvent::foreign_key_checks(
199            prepared.moved_through.as_deref().unwrap_or(&prepared.table),
200            uqa_sql::ast::TriggerEvent::Update,
201            crate::mutation::referential::checks::referenced_checks(
202                context.constraints,
203                &prepared.table,
204                &prepared.old_document,
205                Some(&prepared.new_document),
206                prepared.moved_through.as_deref(),
207            )?,
208        ) {
209            after_row_events.push_event(event, &context.triggers)?;
210        }
211    } else {
212        let mut foreign_key_checks = crate::mutation::referential::checks::referenced_checks(
213            context.constraints,
214            &prepared.table,
215            &prepared.old_document,
216            Some(&prepared.new_document),
217            None,
218        )?;
219        foreign_key_checks.extend(crate::mutation::referential::checks::referencing_checks(
220            context.constraints,
221            &prepared.table,
222            rewritten_doc_id,
223            &prepared.new_document,
224            Some(&prepared.old_document),
225        )?);
226        let event = match trigger_updated_columns.as_deref() {
227            Some(updated_columns) => crate::mutation::triggers::AfterRowTriggerEvent::prepare(
228                &context.triggers,
229                crate::mutation::triggers::AfterRowTriggerInput {
230                    table: &prepared.table,
231                    event: uqa_sql::ast::TriggerEvent::Update,
232                    old_doc_id: prepared.doc_id,
233                    new_doc_id: rewritten_doc_id,
234                    old_document: Some(&prepared.old_document),
235                    new_document: Some(&prepared.new_document),
236                    updated_columns,
237                    foreign_key_checks,
238                },
239            )?,
240            None => crate::mutation::triggers::AfterRowTriggerEvent::foreign_key_checks(
241                &prepared.table,
242                uqa_sql::ast::TriggerEvent::Update,
243                foreign_key_checks,
244            ),
245        };
246        if let Some(event) = event {
247            after_row_events.push_event(event, &context.triggers)?;
248        }
249    }
250    Ok(rewritten_doc_id)
251}
252
253/// Stage a rewrite that a referential action prepared, which writes as a statement of its own that names the foreign key's table and sets its columns.
254pub fn stage_referential_rewrite(
255    context: MutationStagingContext<'_>,
256    action: &mut PreparedDocumentRewrite,
257    params: &[SQLParam],
258    after_row_events: &mut dyn AfterRowEventSink,
259) -> Result<DocId, SQLError> {
260    let referential = action.referential_action.clone().ok_or_else(|| {
261        SQLError::Internal("a referential action rewrite does not name its foreign key".into())
262    })?;
263    stage_prepared_document_rewrite(
264        context,
265        action,
266        params,
267        ConstraintStatement::referential_action(&referential.relation, &referential.columns),
268        None,
269        after_row_events,
270    )
271}
272
273/// Stage the delete of a row, and queue the events of the change.
274pub fn stage_prepared_document_delete(
275    context: MutationStagingContext<'_>,
276    prepared: &PreparedDocumentDelete,
277    after_row_events: &mut dyn AfterRowEventSink,
278) -> Result<(), SQLError> {
279    let foreign_key_checks = crate::mutation::referential::checks::referenced_checks(
280        context.constraints,
281        &prepared.table,
282        &prepared.document,
283        None,
284        None,
285    )?;
286    stage_document_delete(&context, prepared, foreign_key_checks, after_row_events)
287}
288
289fn stage_document_delete(
290    context: &MutationStagingContext<'_>,
291    prepared: &PreparedDocumentDelete,
292    foreign_key_checks: Vec<crate::mutation::referential::checks::ForeignKeyCheck>,
293    after_row_events: &mut dyn AfterRowEventSink,
294) -> Result<(), SQLError> {
295    context
296        .commands
297        .stage_command_document(&prepared.table, prepared.doc_id, None)?;
298    if let Some(event) = crate::mutation::triggers::AfterRowTriggerEvent::prepare(
299        &context.triggers,
300        crate::mutation::triggers::AfterRowTriggerInput {
301            table: &prepared.table,
302            event: uqa_sql::ast::TriggerEvent::Delete,
303            old_doc_id: prepared.doc_id,
304            new_doc_id: prepared.doc_id,
305            old_document: Some(&prepared.document),
306            new_document: None,
307            updated_columns: &[],
308            foreign_key_checks,
309        },
310    )? {
311        after_row_events.push_event(event, &context.triggers)?;
312    }
313    Ok(())
314}