Skip to main content

uqa_execution/mutation/
rules.rs

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