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