Skip to main content

uqa_execution/mutation/rules/
query_inputs.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Execute each rewritten action with its own unevaluated INSERT query input.
8
9use super::{RuleContext, RuleExecutionGuard, RuleExecutionOutcome, RuleReturningRequest};
10use crate::{
11    mutation::returning::ReturningRows, query::consumer::QueryRowConsumer,
12    statement::plan_executor::StatementOutput,
13};
14use std::rc::Rc;
15use uqa_core::memory::ProductionControl;
16use uqa_sql::{
17    ast::{InternalRelationId, RuleEvent, Statement},
18    plan::InsertPlan,
19    semantics::rules::{
20        action_binding::{
21            rule_action_target_columns_with_control, ActionColumns, BoundRuleStatement,
22        },
23        binding::{OwnedRuleQueryInput, OwnedRuleQueryResolver, RuleInputColumns},
24        returning::validate_rule_returning_provider_width,
25        statement_has_returning,
26    },
27    SQLError, SQLParam,
28};
29
30fn execute_insert_query_rules<S: Clone + 'static>(
31    context: &RuleContext<'_, S>,
32    insert: &InsertPlan,
33    params: &[SQLParam],
34    scope: &crate::query::CteScope<S>,
35    prune: crate::mutation::views::commands::SourceOutputPruning,
36) -> Result<RuleExecutionOutcome, SQLError> {
37    let rules = context.capture_rules(&insert.table, RuleEvent::Insert)?;
38    let _guard = RuleExecutionGuard::enter(&insert.table, RuleEvent::Insert)?;
39    let privilege_subject = context.security.privilege_subject(&insert.table)?;
40    let definitions = context.returning_columns(&insert.table)?;
41    let request = context.returning_request(
42        &insert.returning,
43        &insert.returning_aliases,
44        &insert.subqueries,
45    )?;
46    let retained = context.statements.read_control()?;
47    let control = ProductionControl::new(
48        retained.memory(),
49        retained.cancellation(),
50        context.cancellation,
51    );
52    let mut outcome = RuleExecutionOutcome::default();
53    for rule in rules.iter() {
54        let rule = rule?;
55        for action in &rule.definition.actions {
56            let target_columns = rule_action_target_columns_with_control(
57                context.analysis.sources,
58                action,
59                &control,
60            )?;
61            let relation = InternalRelationId::allocate();
62            let mut resolver = OwnedRuleQueryResolver::from_insert_with_control(
63                context.analysis,
64                insert,
65                relation,
66                &control,
67            )?;
68            let mut bound = BoundRuleStatement::bind(
69                context.analysis.sources,
70                action,
71                &*target_columns,
72                &mut resolver,
73                &control,
74            )?;
75            let condition = resolver.condition_with_control(
76                context.binding,
77                rule,
78                &definitions,
79                &privilege_subject,
80                &control,
81            )?;
82            let consumer = returning_consumer(
83                context,
84                &definitions,
85                action,
86                &mut bound,
87                request,
88                &*target_columns,
89                outcome.returning.is_some(),
90            )?;
91            let input = if matches!(action, Statement::Notify { .. }) {
92                None
93            } else {
94                let required = resolver.input_columns_with_control(
95                    context.analysis,
96                    insert,
97                    action,
98                    rule.definition.condition.as_ref(),
99                    &*target_columns,
100                    &control,
101                )?;
102                let query =
103                    copy_rule_input_query(context, insert, scope, required, prune, &control)?;
104                Some(OwnedRuleQueryInput {
105                    query,
106                    inline: insert
107                        .rule_values_input
108                        .as_ref()
109                        .is_some_and(uqa_sql::plan::RuleValuesInput::is_inline),
110                    relation,
111                    condition,
112                    expressions: control
113                        .finish(resolver.expressions, control.empty_reservation())?,
114                })
115            };
116            let result = context.execute_bound_action(
117                &bound,
118                input,
119                params,
120                scope,
121                &privilege_subject,
122                consumer
123                    .as_ref()
124                    .map(|consumer| Rc::clone(consumer) as Rc<dyn QueryRowConsumer>),
125            )?;
126
127            complete_action(
128                &mut outcome,
129                RuleEvent::Insert,
130                rule,
131                action,
132                result,
133                consumer,
134            )?;
135        }
136    }
137    Ok(outcome)
138}
139
140fn copy_rule_input_query<S: Clone + 'static>(
141    context: &RuleContext<'_, S>,
142    insert: &InsertPlan,
143    scope: &crate::query::CteScope<S>,
144    required: Option<RuleInputColumns>,
145    prune: crate::mutation::views::commands::SourceOutputPruning,
146    control: &ProductionControl<'_>,
147) -> Result<uqa_sql::plan::MutableQueryPlan, SQLError> {
148    let mut query = insert
149        .source
150        .as_deref()
151        .expect("query input")
152        .copy_for_rewrite(control)?;
153    if let Some(required) = required {
154        query = prune(
155            context.volatility,
156            context.returning.routines,
157            query,
158            &|position| required.positions.binary_search(&position).is_ok(),
159            required.width,
160            &|name| insert.ctes.iter().any(|cte| cte.name == name) || scope.contains_cte_name(name),
161            control,
162        )?;
163    }
164    Ok(query)
165}
166
167pub(super) fn complete_action(
168    outcome: &mut RuleExecutionOutcome,
169    event: RuleEvent,
170    rule: &uqa_sql::catalog::events::StoredRule,
171    action: &Statement,
172    result: StatementOutput,
173    consumer: Option<Rc<super::returning::RuleReturningConsumer<'_>>>,
174) -> Result<(), SQLError> {
175    if rule.definition.instead
176        && rule.definition.condition.is_none()
177        && matches!(
178            (event, action),
179            (RuleEvent::Insert, Statement::Insert(_))
180                | (RuleEvent::Update, Statement::Update(_))
181                | (RuleEvent::Delete, Statement::Delete(_))
182        )
183    {
184        outcome.affected_rows = match &result {
185            StatementOutput::Mutation(result) => result.affected_rows,
186            StatementOutput::Command(result) => result.affected_rows,
187            StatementOutput::Query(_) => 0,
188        };
189        outcome.sets_command_tag = true;
190    }
191    if let Some(consumer) = consumer {
192        let StatementOutput::Mutation(result) = result else {
193            return Err(SQLError::Internal(
194                "rule RETURNING provider is not a mutation".into(),
195            ));
196        };
197        let consumer = Rc::try_unwrap(consumer).map_err(|_| {
198            SQLError::Internal("completed rule action retained its row consumer".into())
199        })?;
200        outcome.returning = Some(consumer.finish(result.affected_rows));
201    }
202    Ok(())
203}
204
205fn returning_consumer<'a, S: Clone + 'static>(
206    context: &RuleContext<'a, S>,
207    definitions: &'a [uqa_sql::ast::ColumnDef],
208    action: &Statement,
209    bound: &mut BoundRuleStatement,
210    request: RuleReturningRequest,
211    target_columns: &dyn ActionColumns,
212    previous: bool,
213) -> Result<Option<Rc<super::returning::RuleReturningConsumer<'a>>>, SQLError> {
214    if !request.captures() || !statement_has_returning(action) {
215        bound.clear_returning()?;
216        return Ok(None);
217    }
218    if previous {
219        return Err(SQLError::Routine {
220            sqlstate: "0A000".into(),
221            message: "cannot have RETURNING lists in multiple rules".into(),
222        });
223    }
224    let provider = uqa_sql::semantics::rules::returning::rule_action_returning_schema(
225        context.analysis.sources,
226        context.returning,
227        action,
228        RuleEvent::Insert,
229        definitions,
230    )?;
231    validate_rule_returning_provider_width(provider.len(), definitions.len())?;
232    bound.augment_returning(None, definitions.len(), request, target_columns)?;
233    Ok(Some(Rc::new(super::returning::RuleReturningConsumer::new(
234        context.assignment,
235        definitions,
236        context.projection,
237        ReturningRows::with_budget(
238            context.memory.work_mem_bytes()?,
239            context.cancellation.clone(),
240        ),
241    ))))
242}
243
244pub fn run_insert_query_rules<S: Clone + 'static>(
245    rules: &RuleContext<'_, S>,
246    context: crate::mutation::returning::ReturningExecutionContext<'_, S>,
247    queries: &uqa_sql::semantics::rules::binding::OwnedInsertRuleQueries,
248    params: &[SQLParam],
249    scope: &crate::query::CteScope<S>,
250    prune: crate::mutation::views::commands::SourceOutputPruning,
251) -> Result<crate::mutation::output::MutationOutput, SQLError> {
252    let mut output = None;
253    let mut affected = 0;
254    for insert in queries.relations().rev() {
255        let projection = super::RuleOutputProjection::insert(context, insert, params, scope);
256        let outcome = execute_insert_query_rules(
257            &rules.with_projection(&projection),
258            insert,
259            params,
260            scope,
261            prune,
262        )?;
263        if outcome.sets_command_tag {
264            affected = outcome.affected_rows;
265        }
266        if let Some(returning) = outcome.returning {
267            if output.is_some() {
268                return Err(SQLError::Routine {
269                    sqlstate: "0A000".into(),
270                    message: "cannot have RETURNING lists in multiple rules".into(),
271                });
272            }
273            output = Some(returning.project(context, projection.shape)?);
274        }
275    }
276    Ok(output.unwrap_or_else(|| crate::mutation::output::MutationOutput::from_affected(affected)))
277}