Skip to main content

uqa_sql/semantics/rules/binding/actions/query/schedule/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Each INSERT relation retains an independent admitted query until its original or rule action consumes it.
8
9use super::super::{values::ValuesInput, OwnedRuleQueryResolver};
10use crate::{
11    ast::{BooleanTest, FunctionBinding, FunctionDispatch, InternalRelationId, RuleEvent},
12    catalog::roles::RoleReference,
13    plan::{
14        input_projection::substitute_expression_inputs_owned, CommandPlan, ExpressionPlan,
15        InsertPlan, MutableCommandPlan, MutableExecutablePlan, MutableQueryPlan, MutableSourcePlan,
16        OwnedProjection, OwnedScalarExpr, QueryPlan, RelationalPlan,
17    },
18    production::Buffer,
19    semantics::rules::{
20        action_binding::bind_rule_expr_scoped_with_control, analysis::RuleAnalysisContext,
21    },
22    SQLError, ScalarExpr,
23};
24use std::collections::BTreeSet;
25use uqa_core::memory::{Produced, ProductionControl};
26
27pub struct OwnedInsertRuleQueries {
28    pub original: Option<MutableQueryPlan>,
29    relations: Buffer<MutableCommandPlan>,
30}
31
32impl OwnedInsertRuleQueries {
33    pub fn relations(&self) -> impl DoubleEndedIterator<Item = &InsertPlan> {
34        self.relations.iter().map(insert_plan)
35    }
36
37    pub fn reserved_bytes(&self) -> usize {
38        self.original
39            .as_ref()
40            .map_or(0, MutableQueryPlan::reserved_bytes)
41            + self
42                .relations
43                .iter()
44                .map(MutableCommandPlan::reserved_bytes)
45                .sum::<usize>()
46            + self.relations.reserved_bytes()
47    }
48
49    pub fn bind(
50        context: RuleAnalysisContext<'_>,
51        insert: &InsertPlan,
52        subjects: &dyn Fn(&str) -> Result<RoleReference, SQLError>,
53        input_subject: &RoleReference,
54        control: &ProductionControl<'_>,
55    ) -> Result<Self, SQLError> {
56        let (mut values, mut source) = initial_source(context, insert, control)?;
57        if source.relation_privilege_subject.is_none() {
58            source = source
59                .set_privilege_subject(Some(input_subject.clone_with_control(control)?), control)?;
60        }
61        let mut relations = Buffer::new(control);
62        for layer in insert
63            .view_rule_insert_plans
64            .iter()
65            .map(Some)
66            .chain(std::iter::once(None))
67        {
68            let command = insert.copy_rule_layer_for_rewrite(layer, false, control)?;
69            let mut command = command.map_insert_source(control, |_, previous| {
70                debug_assert!(previous.is_none());
71                Ok(source)
72            })?;
73            if let Some(input) = &values {
74                command = input.project_layer_with_control(context, command, control)?;
75                values = ValuesInput::describe_with_control(insert_plan(&command), control)?;
76            }
77            let original = original_query(context, insert_plan(&command), subjects, control)?;
78            relations.push(command, control)?;
79            let Some(original) = original else {
80                return Ok(Self {
81                    original: None,
82                    relations,
83                });
84            };
85            source = original;
86        }
87        let source = if let Some(values) = values {
88            finish_values(&values, source, control)?
89        } else {
90            source
91        };
92        Ok(Self {
93            original: Some(source),
94            relations,
95        })
96    }
97}
98
99fn insert_plan(command: &MutableCommandPlan) -> &InsertPlan {
100    let CommandPlan::Insert(insert) = &**command else {
101        unreachable!("INSERT schedule owner")
102    };
103    insert
104}
105
106fn initial_source(
107    context: RuleAnalysisContext<'_>,
108    insert: &InsertPlan,
109    control: &ProductionControl<'_>,
110) -> Result<(Option<Produced<ValuesInput>>, MutableQueryPlan), SQLError> {
111    control.check()?;
112    if let Some(source) = &insert.source {
113        return Ok((
114            ValuesInput::describe_with_control(insert, control)?,
115            source.copy_for_rewrite(control)?,
116        ));
117    }
118    let command =
119        insert.copy_rule_layer_for_rewrite(insert.view_rule_insert_plans.first(), true, control)?;
120    let values =
121        ValuesInput::describe_with_control(insert_plan(&command), control)?.expect("VALUES input");
122    let source = values.initial_source_with_control(context, command, control)?;
123    Ok((Some(values), source))
124}
125
126fn original_query(
127    context: RuleAnalysisContext<'_>,
128    insert: &InsertPlan,
129    subjects: &dyn Fn(&str) -> Result<RoleReference, SQLError>,
130    control: &ProductionControl<'_>,
131) -> Result<Option<MutableQueryPlan>, SQLError> {
132    let rules =
133        context
134            .rules
135            .capture_rules_with_control(&insert.table, RuleEvent::Insert, control)?;
136    for rule in rules.iter() {
137        control.check()?;
138        let rule = rule?;
139        if rule.definition.instead && rule.definition.condition.is_none() {
140            return Ok(None);
141        }
142    }
143    let mut conditions = Buffer::new(control);
144    for rule in rules.iter() {
145        control.check()?;
146        let rule = rule?;
147        if rule.definition.instead {
148            if let Some(condition) = &rule.definition.condition {
149                conditions.push(condition, control)?;
150            }
151        }
152    }
153    let source = insert.source.as_deref().expect("INSERT query input");
154    if conditions.is_empty() {
155        return Ok(Some(source.copy_for_rewrite(control)?));
156    }
157    let subject = subjects(&insert.table)?;
158    let relation = InternalRelationId::allocate();
159    let mut resolver =
160        OwnedRuleQueryResolver::from_insert_with_control(context, insert, relation, control)?;
161    let mut query = original_block(insert, source, relation, resolver.column_count(), control)?;
162    for condition in conditions {
163        let expression = bind_rule_expr_scoped_with_control(
164            condition,
165            &mut resolver,
166            &BTreeSet::new(),
167            control,
168        )?;
169        let mut condition = ExpressionPlan::lower_borrowed_for_rewrite(&expression, control)?;
170        condition = condition.map_scalar(control, |scalar, _| {
171            let binding = FunctionBinding::dispatched_with_control(
172                FunctionDispatch::BooleanTest(BooleanTest::IsNotTrue),
173                control,
174            )?;
175            Ok(OwnedScalarExpr::call(
176                control.copy_text(&binding.name)?,
177                Some(binding),
178                std::iter::once(scalar),
179                control,
180            )?)
181        })?;
182        for index in 0..condition.queries().len() {
183            condition = condition.map_query(index, control, |query| {
184                let MutableExecutablePlan::Query(query) =
185                    MutableExecutablePlan::Query(query).mark_catalog_relations_bound(control)?
186                else {
187                    unreachable!()
188                };
189                query.set_privilege_subject(Some(subject.clone_with_control(control)?), control)
190            })?;
191        }
192        query = query.map_where_input(control, |previous, arena| {
193            let condition = arena.append_expression(condition, control)?;
194            Ok(Some(match previous {
195                Some(previous) => {
196                    OwnedScalarExpr::boolean([previous, condition].into_iter(), true, control)?
197                }
198                None => condition,
199            }))
200        })?;
201    }
202    let (query, expression) = query.take_where_expression(control)?;
203    let query = query.replace_where_expression(
204        substitute_expression_inputs_owned(
205            expression.expect("original rule condition"),
206            &resolver.expressions,
207            control,
208        )?,
209        control,
210    )?;
211    Ok(Some(
212        query
213            .set_analyzed_output(source.analyzed_output.clone(), control)?
214            .set_privilege_subject(
215                source
216                    .relation_privilege_subject
217                    .as_ref()
218                    .map(|subject| subject.clone_with_control(control))
219                    .transpose()?,
220                control,
221            )?
222            .set_relations_bound(insert.relations_bound, control)?,
223    ))
224}
225
226fn original_block(
227    insert: &InsertPlan,
228    source: &QueryPlan,
229    relation: InternalRelationId,
230    default_width: usize,
231    control: &ProductionControl<'_>,
232) -> Result<MutableQueryPlan, SQLError> {
233    if insert
234        .rule_values_input
235        .as_ref()
236        .is_some_and(ValuesInput::is_inline)
237    {
238        let RelationalPlan::QueryBlock(block) = &source.root else {
239            return Err(SQLError::Internal(
240                "rule target list lost its query block".into(),
241            ));
242        };
243        return block.copy_for_rewrite(control);
244    }
245    let width = source.analyzed_output.as_ref().map_or_else(
246        || match &source.root {
247            RelationalPlan::QueryBlock(block) => block.projections.len(),
248            RelationalPlan::Values { rows, .. } => rows.first().map_or(0, Vec::len),
249            RelationalPlan::SetOp { .. } => {
250                if insert.columns.is_empty() {
251                    default_width
252                } else {
253                    insert.columns.len()
254                }
255            }
256        },
257        crate::RowSchema::len,
258    );
259    captured_projection(source.copy_for_rewrite(control)?, relation, width, control)
260}
261
262fn captured_projection(
263    source: MutableQueryPlan,
264    relation: InternalRelationId,
265    width: usize,
266    control: &ProductionControl<'_>,
267) -> Result<MutableQueryPlan, SQLError> {
268    let mut projections = Buffer::new(control);
269    for position in 0..width {
270        projections.push(
271            OwnedProjection {
272                expression: ScalarExpr::InternalColumn(relation.column(position))
273                    .copy_for_rewrite(control)?,
274                alias: None,
275            },
276            control,
277        )?;
278    }
279    let query = MutableQueryPlan::projected(projections.into_iter(), control)?;
280    let source = MutableSourcePlan::subquery(
281        source,
282        None,
283        control.finish(Vec::new(), control.empty_reservation())?,
284        Some(relation),
285        false,
286        control,
287    )?;
288    query.replace_source(Some(source), control)
289}
290
291fn finish_values(
292    values: &ValuesInput,
293    source: MutableQueryPlan,
294    control: &ProductionControl<'_>,
295) -> Result<MutableQueryPlan, SQLError> {
296    if values.is_inline() || values.defaults.is_empty() {
297        return Ok(source);
298    }
299    let subject = source
300        .relation_privilege_subject
301        .as_ref()
302        .map(|subject| subject.clone_with_control(control))
303        .transpose()?;
304    let bound = source.relations_bound;
305    let source = source.set_analyzed_output(None, control)?;
306    captured_projection(
307        source,
308        InternalRelationId::allocate(),
309        values.width,
310        control,
311    )?
312    .set_privilege_subject(subject, control)?
313    .set_relations_bound(bound, control)
314}