uqa_execution/mutation/
rules.rs1use std::cell::RefCell;
9use uqa_core::RelationIdentity;
10use uqa_sql::{ast::RuleEvent, SQLError};
11mod context;
12mod mutation_inputs;
13mod query_inputs;
14mod returning;
15pub mod schedule;
16pub use context::{RuleContext, RuleSecurity, RuleStatements, ViewRuleContext};
17pub use mutation_inputs::execute_mutation_query_rules;
18pub use query_inputs::run_insert_query_rules;
19pub use returning::{RuleOutputProjection, RuleReturningProjection, RuleReturningResult};
20pub use uqa_sql::semantics::rules::{
21 returning::RuleReturningRequest, validate_rule_returning_contract,
22};
23thread_local! {
24 static RULE_EXECUTION_STACK: RefCell<Vec<(String, RuleEvent)>> = const { RefCell::new(Vec::new()) };
25}
26#[derive(Default)]
27pub struct RuleExecutionOutcome {
28 pub returning: Option<RuleReturningResult>,
29 pub affected_rows: u64,
30 pub sets_command_tag: bool,
31}
32
33struct RuleExecutionGuard {
34 table: String,
35 event: RuleEvent,
36}
37
38impl RuleExecutionGuard {
39 fn enter(table: &str, event: RuleEvent) -> Result<Self, SQLError> {
40 ensure_not_recursive(table, event)?;
41 RULE_EXECUTION_STACK.with(|stack| stack.borrow_mut().push((table.to_string(), event)));
42 Ok(Self {
43 table: table.to_string(),
44 event,
45 })
46 }
47}
48
49impl Drop for RuleExecutionGuard {
50 fn drop(&mut self) {
51 RULE_EXECUTION_STACK.with(|stack| {
52 let popped = stack.borrow_mut().pop();
53 debug_assert_eq!(popped, Some((self.table.clone(), self.event)));
54 });
55 }
56}
57
58fn ensure_not_recursive(table: &str, event: RuleEvent) -> Result<(), SQLError> {
59 let recursive = RULE_EXECUTION_STACK.with(|stack| {
60 stack
61 .borrow()
62 .iter()
63 .any(|(active_table, active_event)| active_table == table && *active_event == event)
64 });
65 if !recursive {
66 return Ok(());
67 }
68 let relation = RelationIdentity::from_legacy_name(table)
69 .map_err(|error| SQLError::Internal(format!("decode rule relation `{table}`: {error}")))?;
70 Err(SQLError::Routine {
71 sqlstate: "42P17".into(),
72 message: format!(
73 "infinite recursion detected in rules for relation \"{}\"",
74 relation.name
75 ),
76 })
77}