Skip to main content

uqa_execution/mutation/rules/
inputs.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Analyzed rule input expressions and the physical values they reference.
8
9use crate::{OwnedPhysicalRow, PhysicalRow, RowSchema};
10use std::collections::BTreeMap;
11use uqa_core::Value;
12use uqa_sql::{
13    ast::{ColumnType, InternalRelationId},
14    plan::ExpressionPlan,
15    ScalarExpr,
16};
17
18pub struct RuleInputProjection {
19    pub expressions: BTreeMap<String, ExpressionPlan>,
20    pub source: OwnedPhysicalRow,
21}
22
23impl Default for RuleInputProjection {
24    fn default() -> Self {
25        Self {
26            expressions: BTreeMap::new(),
27            source: OwnedPhysicalRow::new(RowSchema::default(), PhysicalRow::default()),
28        }
29    }
30}
31
32impl RuleInputProjection {
33    pub fn values(
34        values: impl IntoIterator<Item = (String, Value, Option<ColumnType>, Option<u32>)>,
35    ) -> Self {
36        let relation = InternalRelationId::allocate();
37        let mut expressions = BTreeMap::new();
38        let mut fields = Vec::new();
39        let mut types = Vec::new();
40        for (name, value, ty, collation_oid) in values {
41            expressions.insert(
42                name,
43                ExpressionPlan {
44                    scalar: ScalarExpr::InternalColumn(relation.column(fields.len())),
45                    subqueries: Vec::new(),
46                },
47            );
48            fields.push(value);
49            types.push((ty, collation_oid));
50        }
51        Self {
52            expressions,
53            source: OwnedPhysicalRow::new(
54                RowSchema::with_internal_relation_metadata(relation, types),
55                PhysicalRow::from_values(fields),
56            ),
57        }
58    }
59}
60
61pub(super) fn append_source(target: &mut OwnedPhysicalRow, source: &OwnedPhysicalRow) {
62    target.schema = RowSchema::join(&target.schema, &source.schema, std::iter::empty());
63    target.row = PhysicalRow::concat(&target.row, &source.row);
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use crate::scalar::plan::{eval_physical, PhysicalEvalContext};
70
71    #[test]
72    fn joined_rule_inputs_keep_runtime_types_and_lazy_errors() {
73        let left = RuleInputProjection::values([(
74            "guard".into(),
75            Value::Bool(true),
76            Some(ColumnType::Boolean),
77            None,
78        )]);
79        let right = RuleInputProjection::values([(
80            "divisor".into(),
81            Value::Int(0),
82            Some(ColumnType::SmallInteger),
83            None,
84        )]);
85        let mut source = left.source;
86        append_source(&mut source, &right.source);
87        let uqa_sql::plan::UnifiedPlan::Query(query) = uqa_sql::plan::UnifiedPlan::lower(
88            uqa_sql::compile("SELECT CASE WHEN $1 THEN 7 ELSE 1/$2 END")
89                .unwrap()
90                .remove(0),
91        ) else {
92            panic!("query");
93        };
94        let uqa_sql::plan::RelationalPlan::QueryBlock(mut block) = query.root else {
95            panic!("query block");
96        };
97        let mut plan = ExpressionPlan {
98            scalar: block.projections.remove(0).expr,
99            subqueries: block.subqueries,
100        };
101        uqa_sql::plan::rewrite_scalar_expression(&mut plan.scalar, &mut |node| match node {
102            ScalarExpr::Param(1) => *node = left.expressions["guard"].scalar.clone(),
103            ScalarExpr::Param(2) => *node = right.expressions["divisor"].scalar.clone(),
104            _ => {}
105        });
106        let view = source.view();
107        let context =
108            PhysicalEvalContext::from_row_lookup(&view, &[]).with_row_schema(&source.schema);
109        assert_eq!(eval_physical(&plan, &context).unwrap(), Value::Int(7));
110        assert_eq!(
111            eval_physical(&right.expressions["divisor"], &context).unwrap(),
112            Value::Int(0)
113        );
114        uqa_sql::plan::rewrite_scalar_expression(&mut plan.scalar, &mut |node| {
115            if *node == left.expressions["guard"].scalar {
116                *node = ScalarExpr::Literal(Value::Bool(false));
117            }
118        });
119        assert_eq!(
120            eval_physical(&plan, &context).unwrap_err().sqlstate(),
121            Some("22012")
122        );
123        let ScalarExpr::InternalColumn(divisor) = right.expressions["divisor"].scalar else {
124            panic!("runtime input");
125        };
126        assert_eq!(
127            source.schema.internal_type(divisor),
128            Some(&ColumnType::SmallInteger)
129        );
130    }
131}