Skip to main content

uqa_execution/mutation/
statement_end.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The statement that a command belongs to, and the AFTER events and written rows that its commands leave for its end.
8
9use crate::mutation::candidate::PhysicalDocumentIdentity;
10use crate::mutation::publication::MutationPublicationBatch;
11use crate::mutation::statement::context::MutationStatementContext;
12use crate::mutation::triggers::context::TriggerContext;
13use crate::mutation::triggers::events::AfterRowEvents;
14use crate::mutation::triggers::queue::StatementEvent;
15use crate::query::scope::StatementCommands;
16use crate::query::CteScope;
17use std::cell::RefCell;
18use std::sync::Arc;
19use uqa_sql::{plan::CtePlan, SQLError, SQLParam};
20
21thread_local! {
22    /// The statements this thread runs, outermost first: a statement that the triggers or functions of another start runs above it.
23    static RUNNING_STATEMENTS: RefCell<Vec<Arc<StatementCommands>>> = const { RefCell::new(Vec::new()) };
24}
25
26/// A statement that runs above the statements that started it until the guard drops.
27pub struct RunningStatement(());
28
29impl Drop for RunningStatement {
30    fn drop(&mut self) {
31        RUNNING_STATEMENTS.with(|statements| {
32            statements.borrow_mut().pop();
33        });
34    }
35}
36
37/// Run `statement` above the statements that started it while the returned guard lives.
38pub fn enter_statement(statement: Arc<StatementCommands>) -> RunningStatement {
39    RUNNING_STATEMENTS.with(|statements| statements.borrow_mut().push(statement));
40    RunningStatement(())
41}
42
43/// The statement a command belongs to: the one whose WITH holds the command, or a statement of its own, which runs above the statements that started it while the guard lives.
44pub fn statement_commands<S: Clone>(
45    context: crate::query::cte::CteExecutionContext<'_, S>,
46    inherited: Option<&CteScope<S>>,
47) -> Result<(Arc<StatementCommands>, Option<RunningStatement>), SQLError> {
48    if let Some(statement) = inherited.and_then(CteScope::statement_commands) {
49        return Ok((Arc::clone(statement), None));
50    }
51    let resources = context.production_resources()?;
52    let statement = StatementCommands::with_control(&resources.control())?;
53    let running = enter_statement(Arc::clone(&statement));
54    Ok((statement, Some(running)))
55}
56
57/// Whether a statement started the running one, whose writes it then finds modified by a later command.
58fn started_by_another_statement() -> bool {
59    RUNNING_STATEMENTS.with(|statements| statements.borrow().len() > 1)
60}
61
62/// Note rows that the running statement wrote for every statement that started it.
63fn note_triggered_rows(rows: &[PhysicalDocumentIdentity]) {
64    RUNNING_STATEMENTS.with(|statements| {
65        let statements = statements.borrow();
66        if let Some((_, starters)) = statements.split_last() {
67            for starter in starters {
68                starter.note_triggered(rows.iter().cloned());
69            }
70        }
71    });
72}
73
74/// Fire the BEFORE STATEMENT triggers of `statements` for a command of `statement`, each unless the statement already fired them for its relation and operation.
75pub fn fire_before_statements(
76    statement: &StatementCommands,
77    context: &TriggerContext<'_>,
78    statements: &[StatementEvent],
79) -> Result<(), SQLError> {
80    statements.iter().try_for_each(|event| {
81        statement
82            .after_triggers()
83            .fire_before_statement(context, event)
84    })
85}
86
87/// End one command of `statement`: queue the AFTER events of its rows and of the relations and operations it wrote, and fire the queue unless the statement's WITH modifies data, whose commands fire theirs together once the statement ends (`AfterTriggerEndQuery`).
88pub fn end_command(
89    statement: &StatementCommands,
90    context: &TriggerContext<'_>,
91    statements: &[StatementEvent],
92    rows: AfterRowEvents,
93) -> Result<(), SQLError> {
94    statement
95        .after_triggers()
96        .queue_command(context, statements, rows)?;
97    if statement.modifies_with() {
98        return Ok(());
99    }
100    statement.after_triggers().fire(context)
101}
102
103/// A publication batch for a command of `statement`, which keeps the rows it writes when the statement's WITH modifies data or another statement started it.
104pub fn publication_batch(statement: &StatementCommands) -> MutationPublicationBatch {
105    MutationPublicationBatch::recording_writes(
106        statement.modifies_with() || started_by_another_statement(),
107    )
108}
109
110/// Note the rows a command's publication wrote for the other commands of its statement and for the statements that started it.
111pub fn note_written_rows(
112    statement: &StatementCommands,
113    publication: &mut MutationPublicationBatch,
114) {
115    let rows = publication.take_written();
116    if rows.is_empty() {
117        return;
118    }
119    note_triggered_rows(&rows);
120    if statement.modifies_with() {
121        statement.note_written(rows);
122    }
123}
124
125/// Note a row that the running statement wrote without a publication batch, for the statements that started it.
126pub fn note_written_row(table: &str, doc_id: uqa_core::DocId) {
127    if started_by_another_statement() {
128        note_triggered_rows(&[PhysicalDocumentIdentity {
129            table: table.to_string(),
130            doc_id,
131        }]);
132    }
133}
134
135/// A publication batch for a referential action of the running statement, which keeps the rows it writes when another statement started the running one.
136pub fn action_publication_batch() -> MutationPublicationBatch {
137    MutationPublicationBatch::recording_writes(started_by_another_statement())
138}
139
140/// Note the rows a referential action wrote for the statements that started the running statement.
141pub fn note_action_rows(publication: &mut MutationPublicationBatch) {
142    note_triggered_rows(&publication.take_written());
143}
144
145/// Finish successful command work and release the scope's CTE producers on every result. Data-modifying WITH items and their AFTER events run only after primary success; producer cleanup preserves any primary failure.
146pub fn finish_statement<S: Clone + Send + Sync + 'static, T>(
147    context: &MutationStatementContext<'_, S>,
148    params: &[SQLParam],
149    ctes: &[CtePlan],
150    scope: Option<&mut CteScope<S>>,
151    result: Result<T, SQLError>,
152) -> Result<T, SQLError> {
153    let Some(scope) = scope else {
154        return result;
155    };
156    let result = result.and_then(|output| {
157        if ctes.iter().any(|cte| cte.body.modifies_data()) {
158            crate::query::cte::finish_statement_ctes(context.query.source.ctes, params, scope)?;
159            if let Some(commands) = scope.statement_commands() {
160                commands
161                    .after_triggers()
162                    .fire(&context.mutation.preparation.referential.triggers)?;
163            }
164        }
165        Ok(output)
166    });
167    scope.finish_cte_producers(result)
168}