Skip to main content

uqa_sql/ir/
mod.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Serializable scalar SQL IR shared by analysis, planning, and execution.
8
9mod call_arguments;
10pub(crate) use call_arguments::scalar_call_argument_value_owned;
11mod collation;
12pub use collation::ResultCollation;
13mod retained;
14mod traversal;
15pub use call_arguments::{
16    analyze_expression_call_arguments, scalar_call_argument, scalar_call_arguments,
17    scalar_call_arguments_with_control, validate_scalar_call_arguments, ScalarCallArgument,
18};
19pub use retained::{
20    ConstantValueSource, ConstantValueStorage, RetainedConstantValue, RetainedScalarLiteral,
21};
22
23use crate::ast::{
24    BinaryOp, ColumnType, FrameExclusion, FrameMode, FunctionBinding, FunctionOrderSyntax,
25    InternalColumnRef, NullsOrder, WindowCallModifiers,
26};
27use uqa_core::Value;
28
29/// Index into the query children owned by the enclosing expression plan.
30pub type SubqueryId = usize;
31
32#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
33pub enum ScalarExpr {
34    Star,
35    QualifiedStar(String),
36    Default,
37    Column(String),
38    /// Logical position in an already-bound physical row schema. This variant is introduced only after relational binding so duplicate SQL labels remain independently addressable.
39    Position(usize),
40    /// Structural executor-only attribute, resolved independently of SQL relation and column names.
41    InternalColumn(InternalColumnRef),
42    QualifiedColumn {
43        qualifier: String,
44        column: String,
45    },
46    Literal(Value),
47    /// An already-coerced runtime datum whose declared type must survive lowering.
48    TypedLiteral {
49        value: Value,
50        ty: String,
51        /// Selected implicit result collation; absent metadata retains the declared type default.
52        #[serde(default, skip_serializing_if = "Option::is_none")]
53        collation_oid: Option<u32>,
54        /// Original composite input retained across non-invertible descriptor changes.
55        #[serde(default, skip_serializing_if = "Option::is_none")]
56        composite_source: Option<Box<crate::expr::composites::CompositeConstantSource>>,
57        /// Resolved identity of an already-bound datum, including domain OIDs and type modifiers.
58        #[serde(default, skip_serializing_if = "Option::is_none")]
59        bound_type: Option<ColumnType>,
60        /// Original SQL parameter slot when specialization replaces a bare parameter.
61        #[serde(default, skip_serializing_if = "Option::is_none")]
62        parameter_index: Option<usize>,
63    },
64    /// An analyzed expression's fixed result metadata, retained while optimizations replace or discard its inputs. This is an identity on values, not a new SQL COLLATE clause or cast.
65    Collated {
66        expr: Box<Self>,
67        ty: ColumnType,
68        collation: ResultCollation,
69    },
70    Param(usize),
71    Func {
72        name: String,
73        #[serde(default, skip_serializing_if = "Option::is_none")]
74        binding: Option<FunctionBinding>,
75        args: Vec<Self>,
76        distinct: bool,
77        order_by: Vec<ScalarOrder>,
78        #[serde(default, skip_serializing_if = "FunctionOrderSyntax::is_legacy")]
79        order_syntax: FunctionOrderSyntax,
80        filter: Option<Box<Self>>,
81    },
82    Array(Vec<Self>),
83    Row(Vec<Self>),
84    CompositeRow {
85        items: Vec<Self>,
86        binding: crate::ast::CompositeRowBinding,
87        /// Resolved result identity for physical inference without catalog callbacks.
88        #[serde(default, skip_serializing_if = "Option::is_none")]
89        bound_type: Option<ColumnType>,
90    },
91    Binary {
92        op: BinaryOp,
93        lhs: Box<Self>,
94        rhs: Box<Self>,
95    },
96    UnaryMinus(Box<Self>),
97    Not(Box<Self>),
98    And(Vec<Self>),
99    Or(Vec<Self>),
100    IsNull {
101        expr: Box<Self>,
102        negated: bool,
103    },
104    Between {
105        expr: Box<Self>,
106        low: Box<Self>,
107        high: Box<Self>,
108    },
109    InList {
110        expr: Box<Self>,
111        list: Vec<Self>,
112        negated: bool,
113    },
114    /// A window function call; `filter` is an aggregate's `FILTER (WHERE ...)` condition.
115    WindowCall {
116        name: String,
117        args: Vec<Self>,
118        spec: ScalarWindowSpec,
119        #[serde(default, skip_serializing_if = "Option::is_none")]
120        filter: Option<Box<Self>>,
121        #[serde(default, skip_serializing_if = "WindowCallModifiers::is_empty")]
122        modifiers: WindowCallModifiers,
123    },
124    Case {
125        base: Option<Box<Self>>,
126        when: Vec<(Self, Self)>,
127        else_branch: Option<Box<Self>>,
128    },
129    Cast {
130        /// Analysis introduced this coercion rather than retaining an explicit SQL cast. Stored definitions must distinguish array coercions from explicit constructor conversions.
131        #[serde(default, skip_serializing_if = "is_false")]
132        implicit: bool,
133        expr: Box<Self>,
134        ty: String,
135    },
136    ScalarSubquery(SubqueryId),
137    Exists {
138        subquery: SubqueryId,
139        negated: bool,
140    },
141    InSubquery {
142        expr: Box<Self>,
143        subquery: SubqueryId,
144        negated: bool,
145    },
146    /// An evaluated constant with shared bounded payload ownership. Serialized plans retain the ordinary literal representation; their reader can choose storage again at optimization.
147    #[serde(untagged, skip_deserializing)]
148    RetainedLiteral(Box<RetainedScalarLiteral>),
149}
150
151#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
152pub struct ScalarOrder {
153    pub expr: ScalarExpr,
154    pub descending: bool,
155    pub nulls: Option<NullsOrder>,
156}
157
158#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
159pub struct ScalarWindowSpec {
160    /// Canonical definition in the enclosing query block; absent in legacy inline plans.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub definition: Option<usize>,
163    pub partition_by: Vec<ScalarExpr>,
164    pub order_by: Vec<ScalarOrder>,
165    pub frame: Option<ScalarWindowFrame>,
166}
167
168impl ScalarWindowSpec {
169    /// Borrow each key and frame-offset root owned by this specification.
170    pub fn expressions(&self) -> impl Iterator<Item = &ScalarExpr> {
171        self.partition_by
172            .iter()
173            .chain(self.order_by.iter().map(|order| &order.expr))
174            .chain(
175                self.frame
176                    .iter()
177                    .flat_map(|frame| [&frame.start, &frame.end])
178                    .filter_map(|bound| match bound {
179                        ScalarFrameBound::Preceding(value) | ScalarFrameBound::Following(value) => {
180                            Some(value.as_ref())
181                        }
182                        _ => None,
183                    }),
184            )
185    }
186
187    /// Mutably borrow each key and frame-offset root without visiting derived call copies.
188    pub fn expressions_mut(&mut self) -> impl Iterator<Item = &mut ScalarExpr> {
189        self.partition_by
190            .iter_mut()
191            .chain(self.order_by.iter_mut().map(|order| &mut order.expr))
192            .chain(
193                self.frame
194                    .iter_mut()
195                    .flat_map(|frame| [&mut frame.start, &mut frame.end])
196                    .filter_map(|bound| match bound {
197                        ScalarFrameBound::Preceding(value) | ScalarFrameBound::Following(value) => {
198                            Some(value.as_mut())
199                        }
200                        _ => None,
201                    }),
202            )
203    }
204}
205
206#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
207pub struct ScalarWindowFrame {
208    pub mode: FrameMode,
209    pub start: ScalarFrameBound,
210    pub end: ScalarFrameBound,
211    /// Whether the frame was written `BETWEEN start AND end`; see [`crate::ast::WindowFrame::between`].
212    #[serde(default = "frame_written_between")]
213    pub between: bool,
214    #[serde(default, skip_serializing_if = "FrameExclusion::is_no_others")]
215    pub exclusion: FrameExclusion,
216}
217
218/// Frames recorded before the spelling was kept were deparsed with `BETWEEN`.
219const fn frame_written_between() -> bool {
220    true
221}
222
223#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
224pub enum ScalarFrameBound {
225    UnboundedPreceding,
226    UnboundedFollowing,
227    CurrentRow,
228    Preceding(Box<ScalarExpr>),
229    Following(Box<ScalarExpr>),
230}
231
232impl ScalarExpr {
233    #[must_use]
234    pub fn qualified_column(qualifier: impl Into<String>, column: impl Into<String>) -> Self {
235        Self::QualifiedColumn {
236            qualifier: qualifier.into(),
237            column: column.into(),
238        }
239    }
240}
241
242#[expect(
243    clippy::trivially_copy_pass_by_ref,
244    reason = "serde skip_serializing_if requires a borrowed field"
245)]
246const fn is_false(value: &bool) -> bool {
247    !*value
248}
249
250#[cfg(test)]
251mod tests {
252    use super::ScalarExpr;
253
254    #[test]
255    fn syntax_cast_origin_survives_owned_and_borrowed_lowering() {
256        use crate::{ast::Expr, plan::ExpressionPlan};
257        use uqa_core::{memory::MemoryBudget, CancellationToken};
258
259        let legacy = r#"{"Cast":{"expr":{"Column":"value"},"ty":"bigint[]"}}"#;
260        let explicit: Expr = serde_json::from_str(legacy).unwrap();
261        assert!(matches!(
262            explicit,
263            Expr::Cast {
264                implicit: false,
265                ..
266            }
267        ));
268        assert_eq!(serde_json::to_string(&explicit).unwrap(), legacy);
269        let mut implicit = explicit;
270        let Expr::Cast {
271            implicit: origin, ..
272        } = &mut implicit
273        else {
274            unreachable!()
275        };
276        *origin = true;
277        let stored = serde_json::to_string(&implicit).unwrap();
278        let restored: Expr = serde_json::from_str(&stored).unwrap();
279        let expected = ExpressionPlan::lower(restored.clone()).scalar;
280        assert!(matches!(expected, ScalarExpr::Cast { implicit: true, .. }));
281        let budget = MemoryBudget::new(1 << 20);
282        let token = CancellationToken::new();
283        let borrowed =
284            ExpressionPlan::lower_column_budgeted(&restored, &budget, &token, &token).unwrap();
285        assert_eq!(*borrowed, expected);
286    }
287
288    #[test]
289    fn cast_origin_survives_storage_and_legacy_casts_remain_explicit() {
290        let legacy = r#"{"Cast":{"expr":{"Column":"value"},"ty":"bigint[]"}}"#;
291        let explicit: ScalarExpr = serde_json::from_str(legacy).unwrap();
292        assert!(matches!(
293            explicit,
294            ScalarExpr::Cast {
295                implicit: false,
296                ..
297            }
298        ));
299        assert_eq!(serde_json::to_string(&explicit).unwrap(), legacy);
300        let mut implicit = explicit.clone();
301        let ScalarExpr::Cast {
302            implicit: origin, ..
303        } = &mut implicit
304        else {
305            unreachable!()
306        };
307        *origin = true;
308        let stored = serde_json::to_string(&implicit).unwrap();
309        assert_eq!(
310            serde_json::from_str::<ScalarExpr>(&stored).unwrap(),
311            implicit
312        );
313        assert_ne!(implicit, explicit);
314    }
315}