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::queue::StatementEvent;
14use crate::mutation::triggers::AfterRowTriggerEvent;
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    inherited: Option<&CteScope<S>>,
46) -> (Arc<StatementCommands>, Option<RunningStatement>) {
47    if let Some(statement) = inherited.and_then(CteScope::statement_commands) {
48        return (Arc::clone(statement), None);
49    }
50    let statement = Arc::<StatementCommands>::default();
51    let running = enter_statement(Arc::clone(&statement));
52    (statement, Some(running))
53}
54
55/// Whether a statement started the running one, whose writes it then finds modified by a later command.
56fn started_by_another_statement() -> bool {
57    RUNNING_STATEMENTS.with(|statements| statements.borrow().len() > 1)
58}
59
60/// Note rows that the running statement wrote for every statement that started it.
61fn note_triggered_rows(rows: &[PhysicalDocumentIdentity]) {
62    RUNNING_STATEMENTS.with(|statements| {
63        let statements = statements.borrow();
64        if let Some((_, starters)) = statements.split_last() {
65            for starter in starters {
66                starter.note_triggered(rows.iter().cloned());
67            }
68        }
69    });
70}
71
72/// Fire the BEFORE STATEMENT triggers of `statements` for a command of `statement`, each unless the statement already fired them for its relation and operation.
73pub fn fire_before_statements(
74    statement: &StatementCommands,
75    context: &TriggerContext<'_>,
76    statements: &[StatementEvent],
77) -> Result<(), SQLError> {
78    statements.iter().try_for_each(|event| {
79        statement
80            .after_triggers()
81            .fire_before_statement(context, event)
82    })
83}
84
85/// 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`).
86pub fn end_command(
87    statement: &StatementCommands,
88    context: &TriggerContext<'_>,
89    statements: &[StatementEvent],
90    rows: Vec<AfterRowTriggerEvent>,
91) -> Result<(), SQLError> {
92    statement
93        .after_triggers()
94        .queue_command(context, statements, rows)?;
95    if statement.modifies_with() {
96        return Ok(());
97    }
98    statement.after_triggers().fire(context)
99}
100
101/// 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.
102pub fn publication_batch(statement: &StatementCommands) -> MutationPublicationBatch {
103    MutationPublicationBatch::recording_writes(
104        statement.modifies_with() || started_by_another_statement(),
105    )
106}
107
108/// Note the rows a command's publication wrote for the other commands of its statement and for the statements that started it.
109pub fn note_written_rows(
110    statement: &StatementCommands,
111    publication: &mut MutationPublicationBatch,
112) {
113    let rows = publication.take_written();
114    if rows.is_empty() {
115        return;
116    }
117    note_triggered_rows(&rows);
118    if statement.modifies_with() {
119        statement.note_written(rows);
120    }
121}
122
123/// Note a row that the running statement wrote without a publication batch, for the statements that started it.
124pub fn note_written_row(table: &str, doc_id: uqa_core::DocId) {
125    if started_by_another_statement() {
126        note_triggered_rows(&[PhysicalDocumentIdentity {
127            table: table.to_string(),
128            doc_id,
129        }]);
130    }
131}
132
133/// A publication batch for a referential action of the running statement, which keeps the rows it writes when another statement started the running one.
134pub fn action_publication_batch() -> MutationPublicationBatch {
135    MutationPublicationBatch::recording_writes(started_by_another_statement())
136}
137
138/// Note the rows a referential action wrote for the statements that started the running statement.
139pub fn note_action_rows(publication: &mut MutationPublicationBatch) {
140    note_triggered_rows(&publication.take_written());
141}
142
143/// End a statement whose WITH, `ctes`, modifies data: run the items `scope` kept for after the primary query, then fire every AFTER event the statement's commands queued. A statement whose WITH only reads fired its events when its command ended, and one that did not get as far as its WITH has nothing left to end.
144pub fn finish_statement<S: Clone + Send + Sync + 'static>(
145    context: &MutationStatementContext<'_, S>,
146    params: &[SQLParam],
147    ctes: &[CtePlan],
148    scope: Option<&mut CteScope<S>>,
149) -> Result<(), SQLError> {
150    let Some(scope) = scope.filter(|_| ctes.iter().any(|cte| cte.body.modifies_data())) else {
151        return Ok(());
152    };
153    crate::query::cte::finish_statement_ctes(context.query.source.ctes, params, scope)?;
154    let Some(commands) = scope.statement_commands() else {
155        return Ok(());
156    };
157    commands
158        .after_triggers()
159        .fire(&context.mutation.preparation.referential.triggers)
160}