1mod returning;
10
11use std::cell::RefCell;
12use std::collections::{BTreeMap, BTreeSet};
13
14use uqa_core::Value;
15use uqa_sql::ast::{RuleEvent, Statement};
16use uqa_sql::plpgsql::VariableResolver;
17use uqa_sql::SQLError;
18use uqa_storage::document_store::Document;
19
20use uqa_core::RelationIdentity;
21mod context;
22mod inputs;
23pub use context::{RuleContext, RuleExpressions, RuleSecurity, RuleStatements};
24pub use inputs::RuleInputProjection;
25
26pub use crate::mutation::row_images::RuleRowImage;
27use returning::capture_rule_returning_result;
28pub use returning::RuleReturningResult;
29use uqa_sql::semantics::rules::binding::{bind_insert_values_action, bind_set_oriented_action};
30pub use uqa_sql::semantics::rules::returning::RuleReturningRequest;
31pub use uqa_sql::semantics::rules::validate_rule_returning_contract;
32use uqa_sql::semantics::rules::{
33 analysis::{rule_columns, rule_condition_plan_references_row, rule_returning_columns},
34 clear_statement_returning,
35 returning::{augment_rule_returning_action, validate_rule_returning_provider_width},
36 statement_has_returning,
37};
38
39thread_local! {
40 static RULE_EXECUTION_STACK: RefCell<Vec<(String, RuleEvent)>> = const { RefCell::new(Vec::new()) };
41}
42
43struct PreparedRule {
44 rule: uqa_sql::catalog::events::StoredRule,
45 matching_rows: Vec<usize>,
46 condition_references_row: bool,
47 action_references_row: Vec<bool>,
48 action_row_columns: Vec<BTreeSet<String>>,
49 action_columns: Vec<BTreeSet<String>>,
50}
51
52use uqa_sql::semantics::rules::binding::RuleColumnMetadata;
53
54pub struct PreparedRuleBatch {
55 table: String,
56 event: RuleEvent,
57 rows: Vec<RuleRowImage>,
58 rules: Vec<PreparedRule>,
59 suppress_original: Vec<bool>,
60 action_qualification_count: Option<usize>,
61}
62
63pub struct RuleExecutionOutcome {
64 pub returning: Option<RuleReturningResult>,
65 pub affected_rows: u64,
66 pub sets_command_tag: bool,
67}
68
69#[derive(Clone, Copy)]
70pub enum RuleRowSide {
71 Old,
72 New,
73}
74
75impl PreparedRuleBatch {
76 pub fn event_row_count(&self) -> usize {
77 self.rows.len()
78 }
79
80 pub fn set_action_qualification_count(&mut self, count: usize) {
81 debug_assert!(matches!(self.event, RuleEvent::Update | RuleEvent::Delete));
82 self.action_qualification_count = Some(count);
83 }
84
85 pub fn suppresses(&self, index: usize) -> bool {
86 self.suppress_original.get(index).copied().unwrap_or(false)
87 }
88
89 pub fn matched_action_row_columns(&self) -> Vec<BTreeSet<String>> {
90 let mut rows = vec![BTreeSet::new(); self.rows.len()];
91 for rule in &self.rules {
92 for columns in &rule.action_row_columns {
93 for row in &rule.matching_rows {
94 if let Some(required) = rows.get_mut(*row) {
95 required.extend(columns.iter().cloned());
96 }
97 }
98 }
99 }
100 rows
101 }
102
103 pub fn missing_action_row_columns(&self) -> Vec<(BTreeSet<String>, BTreeSet<String>)> {
104 self.matched_action_row_columns()
105 .into_iter()
106 .zip(&self.rows)
107 .map(|(columns, row)| {
108 let missing = |record: &Option<Document>| {
109 if let Some(record) = record {
110 columns
111 .iter()
112 .filter(|column| !record.contains_key(*column))
113 .cloned()
114 .collect()
115 } else {
116 BTreeSet::new()
117 }
118 };
119 (missing(&row.old), missing(&row.new))
120 })
121 .collect()
122 }
123
124 pub fn supplement_rows(&mut self, rows: Vec<RuleRowImage>) -> Result<(), SQLError> {
125 if rows.len() != self.rows.len() {
126 return Err(SQLError::Internal(
127 "rewrite-rule supplemental row count changed after qualification".into(),
128 ));
129 }
130 for (target, supplemental) in self.rows.iter_mut().zip(rows) {
131 target.supplement_documents(supplemental);
132 }
133 Ok(())
134 }
135
136 pub fn execute_actions(
137 &self,
138 context: RuleContext<'_>,
139 request: RuleReturningRequest,
140 ) -> Result<Option<RuleReturningResult>, SQLError> {
141 Ok(self
142 .execute_actions_with_affected(context, request)?
143 .returning)
144 }
145
146 #[expect(
147 clippy::too_many_lines,
148 reason = "preserves action and RETURNING order"
149 )]
150 pub fn execute_actions_with_affected(
151 &self,
152 context: RuleContext<'_>,
153 request: RuleReturningRequest,
154 ) -> Result<RuleExecutionOutcome, SQLError> {
155 if self.rules.is_empty() {
156 return Ok(RuleExecutionOutcome {
157 returning: None,
158 affected_rows: 0,
159 sets_command_tag: false,
160 });
161 }
162 let privilege_subject = context.security.privilege_subject(&self.table)?;
163 let _guard = RuleExecutionGuard::enter(&self.table, self.event)?;
164 let columns = rule_columns(context.analysis, &self.table)?;
165 let returning_columns = request
166 .captures()
167 .then(|| rule_returning_columns(context.analysis, &self.table))
168 .transpose()?;
169 let provider_exists = request.captures()
170 && self.rules.iter().any(|prepared| {
171 prepared
172 .rule
173 .definition
174 .actions
175 .iter()
176 .any(statement_has_returning)
177 });
178 let mut returning = provider_exists.then(RuleReturningResult::empty);
179 let mut affected_rows = 0_u64;
180 let mut sets_command_tag = false;
181 let mut provider_captured = false;
182 for prepared in &self.rules {
183 for (action_index, action) in prepared.rule.definition.actions.iter().enumerate() {
184 let action_columns =
185 prepared.action_columns.get(action_index).ok_or_else(|| {
186 SQLError::Internal(
187 "rewrite rule lost its prepared action column contract".into(),
188 )
189 })?;
190 let mut reevaluated_rows;
191 let reevaluated_matching_rows;
192 let (action_matching_rows, action_rows) = if self.event == RuleEvent::Insert
193 && prepared.rule.bound_condition_plan().is_some()
194 {
195 reevaluated_rows = self.rows.clone();
196 let mut matched = Vec::new();
197 for (row_index, row) in reevaluated_rows.iter_mut().enumerate() {
198 if rule_condition_matches(
199 context,
200 &prepared.rule,
201 &privilege_subject,
202 row_index,
203 row,
204 &columns,
205 &mut |_, _, _| Ok(RuleInputProjection::default()),
206 )? {
207 matched.push(row_index);
208 }
209 }
210 reevaluated_matching_rows = matched;
211 (
212 reevaluated_matching_rows.as_slice(),
213 reevaluated_rows.as_slice(),
214 )
215 } else {
216 (prepared.matching_rows.as_slice(), self.rows.as_slice())
217 };
218 let action_returns = statement_has_returning(action);
219 let captures_action = request.captures() && action_returns;
220 let captures_source_context = captures_action
221 && matches!(action, Statement::Update(_) | Statement::Delete(_))
222 && action_matching_rows.iter().any(|row_index| {
223 action_rows
224 .get(*row_index)
225 .is_some_and(|row| row.context.is_some())
226 });
227 let action_references_row = prepared
228 .action_references_row
229 .get(action_index)
230 .copied()
231 .unwrap_or(false);
232 let uses_action_qualification =
233 matches!(self.event, RuleEvent::Update | RuleEvent::Delete)
234 && !prepared.condition_references_row
235 && !action_references_row
236 && !captures_source_context
237 && self.action_qualification_count.is_some();
238 let qualification_rows;
239 let qualification_indices;
240 let (matching_rows, rows) = if uses_action_qualification {
241 let count = self.action_qualification_count.unwrap_or_default();
242 let mut matched = Vec::with_capacity(count);
243 for qualification_index in 0..count {
244 let mut row = RuleRowImage::empty();
245 if rule_condition_matches(
246 context,
247 &prepared.rule,
248 &privilege_subject,
249 qualification_index,
250 &mut row,
251 &columns,
252 &mut |_, _, _| Ok(RuleInputProjection::default()),
253 )? {
254 matched.push(row);
255 }
256 }
257 qualification_rows = matched;
258 qualification_indices = (0..qualification_rows.len()).collect::<Vec<_>>();
259 (
260 qualification_indices.as_slice(),
261 qualification_rows.as_slice(),
262 )
263 } else {
264 (action_matching_rows, action_rows)
265 };
266 let bind_action = |resolver: &mut dyn VariableResolver| {
267 uqa_sql::semantics::rules::action_binding::bind_rule_action(
268 context.analysis.sources,
269 action,
270 action_columns,
271 resolver,
272 )
273 };
274 let needs_row_source = !matches!(action, Statement::Notify { .. })
275 && (self.event == RuleEvent::Insert
276 || prepared.condition_references_row
277 || action_references_row
278 || captures_source_context
279 || uses_action_qualification);
280 if needs_row_source
281 && matching_rows.len() > 1
282 && uqa_sql::semantics::rules::action_binding::rule_action_has_set_operation(
283 action,
284 )
285 {
286 return Err(SQLError::Routine {
287 sqlstate: "0A000".into(),
288 message:
289 "conditional UNION/INTERSECT/EXCEPT statements are not implemented"
290 .into(),
291 });
292 }
293 let (mut bound, source_index) = if needs_row_source
294 && matches!(action, Statement::Insert(insert) if !insert.rows.is_empty())
295 {
296 (
297 bind_insert_values_action(matching_rows, rows, &columns, &bind_action)?,
298 None,
299 )
300 } else if needs_row_source {
301 let bound =
302 bind_set_oriented_action(matching_rows, rows, &columns, &bind_action)?;
303 let source_index = captures_source_context.then_some(bound.source_index);
304 (bound.statement, source_index)
305 } else {
306 (action.clone(), None)
307 };
308 if captures_action {
309 if provider_captured {
310 return Err(SQLError::Routine {
311 sqlstate: "0A000".into(),
312 message: "cannot have RETURNING lists in multiple rules".into(),
313 });
314 }
315 provider_captured = true;
316 let event_width = returning_columns.as_ref().map_or(0, Vec::len);
317 let provider_width =
318 uqa_sql::semantics::returning::dml_statement_returning_schema(
319 context.returning,
320 bound.clone(),
321 )?
322 .ok_or_else(|| {
323 SQLError::Internal(
324 "rewrite-rule RETURNING provider lost its declared row type".into(),
325 )
326 })?
327 .len();
328 validate_rule_returning_provider_width(provider_width, event_width)?;
329 augment_rule_returning_action(
330 &mut bound,
331 source_index,
332 event_width,
333 request,
334 action_columns,
335 )?;
336 } else if action_returns {
337 clear_statement_returning(&mut bound);
338 }
339 let result = context.statements.execute(bound, &privilege_subject)?;
340 if prepared.rule.definition.instead
341 && prepared.rule.definition.condition.is_none()
342 && matches!(
343 (self.event, action),
344 (RuleEvent::Insert, Statement::Insert(_))
345 | (RuleEvent::Update, Statement::Update(_))
346 | (RuleEvent::Delete, Statement::Delete(_))
347 )
348 {
349 affected_rows = result.affected_rows;
350 sets_command_tag = true;
351 }
352 if captures_action {
353 let definitions = returning_columns.as_deref().ok_or_else(|| {
354 SQLError::Internal(
355 "rewrite-rule RETURNING capture lost the event row type".into(),
356 )
357 })?;
358 let captured = capture_rule_returning_result(
359 context.assignment,
360 result,
361 definitions,
362 captures_source_context.then_some(self.rows.as_slice()),
363 )?;
364 returning = Some(captured);
365 }
366 }
367 }
368 Ok(RuleExecutionOutcome {
369 returning,
370 affected_rows,
371 sets_command_tag,
372 })
373 }
374}
375
376pub fn prepare_rule_batch(
377 context: RuleContext<'_>,
378 table: &str,
379 event: RuleEvent,
380 rows: Vec<RuleRowImage>,
381) -> Result<PreparedRuleBatch, SQLError> {
382 prepare_rule_batch_with_projection(context, table, event, rows, |_, _, _| {
383 Ok(RuleInputProjection::default())
384 })
385}
386
387pub fn prepare_rule_batch_with_projection<F>(
388 context: RuleContext<'_>,
389 table: &str,
390 event: RuleEvent,
391 mut rows: Vec<RuleRowImage>,
392 mut project: F,
393) -> Result<PreparedRuleBatch, SQLError>
394where
395 F: FnMut(usize, RuleRowSide, &BTreeSet<String>) -> Result<RuleInputProjection, SQLError>,
396{
397 let table = context
398 .analysis
399 .rules
400 .resolve_rule_relation(table)?
401 .qualified_name();
402 let rules = context.analysis.rules.rules_for(&table, event)?;
403 if rules.is_empty() {
404 return Ok(PreparedRuleBatch {
405 table,
406 event,
407 suppress_original: vec![false; rows.len()],
408 rows,
409 rules: Vec::new(),
410 action_qualification_count: None,
411 });
412 }
413 ensure_not_recursive(&table, event)?;
414 let columns = rule_columns(context.analysis, &table)?;
415 let privilege_subject = context.security.privilege_subject(&table)?;
416 let mut suppress_original = vec![false; rows.len()];
417 let mut prepared_rules = Vec::with_capacity(rules.len());
418 for rule in rules {
419 let mut prepared = prepare_rule_actions(context, rule, &columns)?;
420 for (index, row) in rows.iter_mut().enumerate() {
421 if rule_condition_matches(
422 context,
423 &prepared.rule,
424 &privilege_subject,
425 index,
426 row,
427 &columns,
428 &mut project,
429 )? {
430 prepared.matching_rows.push(index);
431 if prepared.rule.definition.instead {
432 suppress_original[index] = true;
433 }
434 }
435 }
436 prepared_rules.push(prepared);
437 }
438 Ok(PreparedRuleBatch {
439 table,
440 event,
441 rows,
442 rules: prepared_rules,
443 suppress_original,
444 action_qualification_count: None,
445 })
446}
447
448struct RuleExecutionGuard {
449 table: String,
450 event: RuleEvent,
451}
452
453impl RuleExecutionGuard {
454 fn enter(table: &str, event: RuleEvent) -> Result<Self, SQLError> {
455 ensure_not_recursive(table, event)?;
456 RULE_EXECUTION_STACK.with(|stack| stack.borrow_mut().push((table.to_string(), event)));
457 Ok(Self {
458 table: table.to_string(),
459 event,
460 })
461 }
462}
463
464impl Drop for RuleExecutionGuard {
465 fn drop(&mut self) {
466 RULE_EXECUTION_STACK.with(|stack| {
467 let popped = stack.borrow_mut().pop();
468 debug_assert_eq!(popped, Some((self.table.clone(), self.event)));
469 });
470 }
471}
472
473fn ensure_not_recursive(table: &str, event: RuleEvent) -> Result<(), SQLError> {
474 let recursive = RULE_EXECUTION_STACK.with(|stack| {
475 stack
476 .borrow()
477 .iter()
478 .any(|(active_table, active_event)| active_table == table && *active_event == event)
479 });
480 if !recursive {
481 return Ok(());
482 }
483 let relation = RelationIdentity::from_legacy_name(table)
484 .map_err(|error| SQLError::Internal(format!("decode rule relation `{table}`: {error}")))?;
485 Err(SQLError::Routine {
486 sqlstate: "42P17".into(),
487 message: format!(
488 "infinite recursion detected in rules for relation \"{}\"",
489 relation.name
490 ),
491 })
492}
493
494mod condition_binding;
495use condition_binding::rule_condition_matches;
496
497pub mod views;
498
499fn prepare_rule_actions(
500 context: RuleContext<'_>,
501 mut rule: uqa_sql::catalog::events::StoredRule,
502 columns: &BTreeMap<String, RuleColumnMetadata>,
503) -> Result<PreparedRule, SQLError> {
504 if let Some((plan, binding)) = rule
505 .condition_plan
506 .as_mut()
507 .zip(rule.condition_binding.as_ref())
508 {
509 let mut ordered = columns.iter().collect::<Vec<_>>();
510 ordered.sort_by_key(|(_, column)| column.position);
511 let binding = binding.refresh_columns(
512 ordered.iter().map(|(name, _)| (*name).clone()).collect(),
513 plan,
514 );
515 if uqa_sql::semantics::rules::action_binding::rule_condition_plan_references_whole_row(plan)
516 {
517 let columns = ordered
518 .into_iter()
519 .map(|(name, column)| {
520 let mut definition =
521 uqa_sql::ast::ColumnDef::nullable(name.clone(), column.ty.clone());
522 definition.collation_oid = column.collation_oid;
523 definition
524 })
525 .collect::<Vec<_>>();
526 context
527 .binding
528 .bind_rule_inputs(plan, &binding, &rule.definition.table, &columns)?;
529 }
530 rule.condition_binding = Some(binding);
531 }
532 if let Some(condition) = &mut rule.condition_plan {
533 context.expressions.prepare_condition(condition)?;
534 }
535 let condition_references_row = if rule.bound_condition_plan().is_some() {
536 rule_condition_plan_references_row(&rule)
537 } else {
538 rule.definition
539 .condition
540 .as_ref()
541 .is_some_and(uqa_sql::semantics::rules::action_binding::rule_expr_references_row)
542 };
543 let action_columns = rule
544 .definition
545 .actions
546 .iter()
547 .map(|action| {
548 uqa_sql::semantics::rules::action_binding::rule_action_target_columns(
549 context.analysis.sources,
550 action,
551 )
552 })
553 .collect::<Result<Vec<_>, SQLError>>()?;
554 let action_references_row = rule
555 .definition
556 .actions
557 .iter()
558 .zip(&action_columns)
559 .map(|(action, columns)| {
560 uqa_sql::semantics::rules::action_binding::rule_statement_references_row(
561 context.analysis.sources,
562 action,
563 columns,
564 )
565 })
566 .collect::<Result<Vec<_>, SQLError>>()?;
567 let action_row_columns = rule
568 .definition
569 .actions
570 .iter()
571 .zip(&action_columns)
572 .map(|(action, action_columns)| {
573 if uqa_sql::semantics::rules::action_binding::rule_statement_references_whole_row(
574 context.analysis.sources,
575 action,
576 action_columns,
577 )? {
578 Ok(columns.keys().cloned().collect())
579 } else {
580 uqa_sql::semantics::rules::action_binding::rule_statement_row_columns(
581 context.analysis.sources,
582 action,
583 action_columns,
584 )
585 }
586 })
587 .collect::<Result<Vec<_>, SQLError>>()?;
588 Ok(PreparedRule {
589 rule,
590 matching_rows: Vec::new(),
591 condition_references_row,
592 action_references_row,
593 action_row_columns,
594 action_columns,
595 })
596}