Skip to main content

uqa_sql/semantics/rules/action_binding/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bound action bodies and replaceable RETURNING lists retire their allocations independently.
8
9use super::{
10    bind_rule_statement_body, returning, RuleActionBodyResolver, RuleBindingContext,
11    RuleBindingScope, RuleSourceCatalog, SyntaxProduction,
12};
13use crate::ast::Projection;
14use crate::{
15    ast::{RuleEvent, Statement},
16    plpgsql::VariableResolver,
17    SQLError,
18};
19use uqa_core::memory::{MemoryReservation, OwnedProductionControl, Produced, ProductionControl};
20
21/// Only SQL-owned operations can replace a clause; callers borrow the complete statement without detaching its allocation owners.
22pub struct BoundRuleStatement {
23    statement: Statement,
24    body_memory: Option<MemoryReservation>,
25    returning_memory: Option<MemoryReservation>,
26    control: OwnedProductionControl,
27}
28
29impl BoundRuleStatement {
30    pub fn bind(
31        catalog: &dyn RuleSourceCatalog,
32        action: &Statement,
33        action_columns: &dyn super::ActionColumns,
34        resolver: &mut dyn VariableResolver,
35        control: &ProductionControl<'_>,
36    ) -> Result<Self, SQLError> {
37        control.check()?;
38        let context = RuleBindingContext::with_control(catalog, true, control);
39        let body = SyntaxProduction::new(*control);
40        let (returning, event, aliases) = match action {
41            Statement::Insert(action) => (
42                &action.returning,
43                RuleEvent::Insert,
44                &action.returning_aliases,
45            ),
46            Statement::Update(action) => (
47                &action.returning,
48                RuleEvent::Update,
49                &action.returning_aliases,
50            ),
51            Statement::Delete(action) => (
52                &action.returning,
53                RuleEvent::Delete,
54                &action.returning_aliases,
55            ),
56            _ => {
57                let statement = bind_rule_statement_body(
58                    action,
59                    resolver,
60                    &RuleBindingScope::default(),
61                    &context,
62                    &body,
63                )?;
64                let (statement, body_memory) = body.finish(statement)?.into_parts();
65                return Ok(Self {
66                    statement,
67                    body_memory,
68                    returning_memory: control.empty_reservation(),
69                    control: control.capture(),
70                });
71            }
72        };
73        let statement = bind_rule_statement_body(
74            action,
75            &mut RuleActionBodyResolver {
76                action_columns,
77                action_event: event,
78                event_resolver: resolver,
79            },
80            &RuleBindingScope::default(),
81            &context,
82            &body,
83        )?;
84        let body = body.finish(statement)?;
85        let output = SyntaxProduction::new(*control);
86        let projections = returning::bind_rule_action_returning(
87            returning,
88            action_columns,
89            aliases,
90            event,
91            resolver,
92            &context,
93            &output,
94        )?;
95        let projections = output.finish(projections)?;
96        let (mut statement, body_memory) = body.into_parts();
97        let (projections, returning_memory) = projections.into_parts();
98        *returning_mut(&mut statement).expect("bound DML action") = projections;
99        Ok(Self {
100            statement,
101            body_memory,
102            returning_memory,
103            control: control.capture(),
104        })
105    }
106
107    pub fn statement(&self) -> &Statement {
108        &self.statement
109    }
110
111    pub fn reserved_bytes(&self) -> usize {
112        self.body_memory
113            .as_ref()
114            .map_or(0, MemoryReservation::bytes)
115            + self
116                .returning_memory
117                .as_ref()
118                .map_or(0, MemoryReservation::bytes)
119    }
120
121    pub fn into_produced(self) -> Result<Produced<Statement>, SQLError> {
122        let control = self.control.control();
123        Ok(control.finish(
124            self.statement,
125            control.combine(self.body_memory, self.returning_memory),
126        )?)
127    }
128
129    pub fn clear_returning(&mut self) -> Result<(), SQLError> {
130        self.control.control().check()?;
131        if let Some(returning) = returning_mut(&mut self.statement) {
132            drop(std::mem::take(returning));
133            self.returning_memory = self.control.control().empty_reservation();
134        }
135        Ok(())
136    }
137
138    /// Construct all requested images before replacing the old list. Rejection or cancellation leaves the original statement and its leases intact.
139    pub fn augment_returning(
140        &mut self,
141        source_index: Option<&crate::ast::Expr>,
142        event_width: usize,
143        request: crate::semantics::rules::returning::RuleReturningRequest,
144        target_columns: &dyn super::ActionColumns,
145    ) -> Result<(), SQLError> {
146        if let Some(output) = crate::semantics::rules::returning::produce_rule_returning(
147            &self.statement,
148            source_index,
149            event_width,
150            request,
151            target_columns,
152            &self.control.control(),
153        )? {
154            self.replace_returning(output);
155        }
156        Ok(())
157    }
158
159    pub fn append_returning_context(
160        &mut self,
161        expressions: &[crate::ast::Expr],
162    ) -> Result<(), SQLError> {
163        let control = self.control.control();
164        control.check()?;
165        if expressions.is_empty() {
166            return Ok(());
167        }
168        let returning = match &self.statement {
169            Statement::Update(action) => &action.returning,
170            Statement::Delete(action) => &action.returning,
171            _ => {
172                return Err(SQLError::Internal(
173                    "rule source context requires UPDATE or DELETE".into(),
174                ))
175            }
176        };
177        let production = SyntaxProduction::new(control);
178        let mut output = production.vector(returning.len().saturating_add(expressions.len()))?;
179        for projection in returning {
180            output.push(production.copy(projection)?)?;
181        }
182        for expression in expressions {
183            output.push(Projection {
184                expr: production.copy(expression)?,
185                alias: None,
186            })?;
187        }
188        let output = output.finish()?;
189        let output = production.finish(output)?;
190        self.replace_returning(output);
191        Ok(())
192    }
193
194    fn replace_returning(&mut self, output: Produced<Vec<Projection>>) {
195        let (value, memory) = output.into_parts();
196        let slot =
197            returning_mut(&mut self.statement).expect("RETURNING producer validated DML action");
198        drop(std::mem::replace(slot, value));
199        self.returning_memory = memory;
200    }
201}
202
203pub(crate) fn returning_mut(statement: &mut Statement) -> Option<&mut Vec<Projection>> {
204    match statement {
205        Statement::Insert(action) => Some(&mut action.returning),
206        Statement::Update(action) => Some(&mut action.returning),
207        Statement::Delete(action) => Some(&mut action.returning),
208        _ => None,
209    }
210}