Skip to main content

uqa_sql/semantics/rules/
returning.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Rule RETURNING image requirements, positional contracts, and action rewriting.
8use crate::{
9    ast::{RuleEvent, Statement},
10    SQLError,
11};
12use std::collections::BTreeSet;
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
14pub struct RuleReturningRequest {
15    capture: bool,
16    images: RuleReturningImages,
17}
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
20struct RuleReturningImages(u8);
21
22impl RuleReturningImages {
23    const CURRENT: Self = Self(1 << 0);
24    const OLD: Self = Self(1 << 1);
25    const NEW: Self = Self(1 << 2);
26
27    fn insert(&mut self, image: Self) {
28        self.0 |= image.0;
29    }
30
31    const fn contains(self, image: Self) -> bool {
32        self.0 & image.0 != 0
33    }
34}
35
36mod inspection;
37
38#[cfg(test)]
39mod tests;
40
41pub fn validate_rule_returning_provider_width(
42    provider_width: usize,
43    event_width: usize,
44) -> Result<(), SQLError> {
45    if provider_width < event_width {
46        return Err(SQLError::Internal(format!(
47            "could not find replacement targetlist entry for attno {}",
48            provider_width + 1
49        )));
50    }
51    if provider_width > event_width {
52        return Err(SQLError::Internal(format!(
53            "rewrite-rule RETURNING provider produced {provider_width} columns, expected {event_width}"
54        )));
55    }
56    Ok(())
57}
58
59/// Describe the stored action in its event namespace, before unevaluated caller inputs replace OLD and NEW. Stored stars keep their creation-time width.
60pub fn rule_action_returning_schema(
61    sources: &dyn super::action_binding::RuleSourceCatalog,
62    context: crate::semantics::returning::ReturningAnalysisContext<'_>,
63    action: &Statement,
64    event: RuleEvent,
65    columns: &[crate::ast::ColumnDef],
66) -> Result<crate::RowSchema, SQLError> {
67    let action_columns = super::action_binding::rule_action_target_columns(sources, action)?;
68    let mut resolver =
69        crate::catalog::events::validation::RuleRowTypeResolver::for_action(columns, event);
70    let bound =
71        super::action_binding::bind_rule_action(sources, action, &action_columns, &mut resolver)?;
72    crate::semantics::returning::dml_statement_returning_schema(context, bound)?
73        .ok_or_else(|| SQLError::Internal("rule action lost its RETURNING descriptor".into()))
74}
75
76mod augmentation;
77pub use augmentation::augment_rule_returning_action;
78pub(super) use augmentation::produce_rule_returning;