uqa_execution/mutation/
statement_end.rs1use 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 static RUNNING_STATEMENTS: RefCell<Vec<Arc<StatementCommands>>> = const { RefCell::new(Vec::new()) };
24}
25
26pub 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
37pub fn enter_statement(statement: Arc<StatementCommands>) -> RunningStatement {
39 RUNNING_STATEMENTS.with(|statements| statements.borrow_mut().push(statement));
40 RunningStatement(())
41}
42
43pub 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
57fn started_by_another_statement() -> bool {
59 RUNNING_STATEMENTS.with(|statements| statements.borrow().len() > 1)
60}
61
62fn 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
74pub 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
87pub 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
103pub fn publication_batch(statement: &StatementCommands) -> MutationPublicationBatch {
105 MutationPublicationBatch::recording_writes(
106 statement.modifies_with() || started_by_another_statement(),
107 )
108}
109
110pub 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
125pub 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
135pub fn action_publication_batch() -> MutationPublicationBatch {
137 MutationPublicationBatch::recording_writes(started_by_another_statement())
138}
139
140pub fn note_action_rows(publication: &mut MutationPublicationBatch) {
142 note_triggered_rows(&publication.take_written());
143}
144
145pub 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}