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(crate::ast::ReferenceName),
36    Default,
37    Column(crate::ast::ReferenceName),
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: crate::ast::ReferenceName,
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    /// Relation qualifier of a named attribute or qualified wildcard.
235    pub fn reference_qualifier(&self) -> Option<&str> {
236        match self {
237            Self::QualifiedColumn { qualifier, .. } => Some(qualifier),
238            Self::QualifiedStar(qualifier) => Some(qualifier),
239            _ => None,
240        }
241    }
242
243    /// Rename qualification while retaining the original reference position.
244    pub fn reference_qualifier_mut(&mut self) -> Option<&mut String> {
245        match self {
246            Self::QualifiedColumn { qualifier, .. } => Some(qualifier),
247            Self::QualifiedStar(qualifier) => Some(qualifier),
248            _ => None,
249        }
250    }
251
252    /// Original one-based character position of a named SQL reference.
253    pub fn reference_position(&self) -> Option<u32> {
254        match self {
255            Self::Column(name) | Self::QualifiedStar(name) => name.position(),
256            Self::QualifiedColumn { column, .. } => column.position(),
257            _ => None,
258        }
259    }
260
261    /// Retain the caller's origin when binding replaces a name with its stored reference.
262    pub fn set_reference_position(&mut self, position: Option<u32>) {
263        match self {
264            Self::Column(name)
265            | Self::QualifiedStar(name)
266            | Self::QualifiedColumn { column: name, .. } => name.set_position(position),
267            _ => {}
268        }
269    }
270
271    pub fn qualified_column(
272        qualifier: impl Into<String>,
273        column: impl Into<crate::ast::ReferenceName>,
274    ) -> Self {
275        Self::QualifiedColumn {
276            qualifier: qualifier.into(),
277            column: column.into(),
278        }
279    }
280}
281
282#[expect(
283    clippy::trivially_copy_pass_by_ref,
284    reason = "serde skip_serializing_if requires a borrowed field"
285)]
286const fn is_false(value: &bool) -> bool {
287    !*value
288}
289
290#[cfg(test)]
291mod tests {
292    use super::ScalarExpr;
293
294    #[test]
295    fn syntax_cast_origin_survives_owned_and_borrowed_lowering() {
296        use crate::{ast::Expr, plan::ExpressionPlan};
297        use uqa_core::{memory::MemoryBudget, CancellationToken};
298
299        let legacy = r#"{"Cast":{"expr":{"Column":"value"},"ty":"bigint[]"}}"#;
300        let explicit: Expr = serde_json::from_str(legacy).unwrap();
301        assert!(matches!(
302            explicit,
303            Expr::Cast {
304                implicit: false,
305                ..
306            }
307        ));
308        assert_eq!(serde_json::to_string(&explicit).unwrap(), legacy);
309        let mut implicit = explicit;
310        let Expr::Cast {
311            implicit: origin, ..
312        } = &mut implicit
313        else {
314            unreachable!()
315        };
316        *origin = true;
317        let stored = serde_json::to_string(&implicit).unwrap();
318        let restored: Expr = serde_json::from_str(&stored).unwrap();
319        let expected = ExpressionPlan::lower(restored.clone()).scalar;
320        assert!(matches!(expected, ScalarExpr::Cast { implicit: true, .. }));
321        let budget = MemoryBudget::new(1 << 20);
322        let token = CancellationToken::new();
323        let borrowed =
324            ExpressionPlan::lower_column_budgeted(&restored, &budget, &token, &token).unwrap();
325        assert_eq!(*borrowed, expected);
326    }
327
328    #[test]
329    fn cast_origin_survives_storage_and_legacy_casts_remain_explicit() {
330        let legacy = r#"{"Cast":{"expr":{"Column":"value"},"ty":"bigint[]"}}"#;
331        let explicit: ScalarExpr = serde_json::from_str(legacy).unwrap();
332        assert!(matches!(
333            explicit,
334            ScalarExpr::Cast {
335                implicit: false,
336                ..
337            }
338        ));
339        assert_eq!(serde_json::to_string(&explicit).unwrap(), legacy);
340        let mut implicit = explicit.clone();
341        let ScalarExpr::Cast {
342            implicit: origin, ..
343        } = &mut implicit
344        else {
345            unreachable!()
346        };
347        *origin = true;
348        let stored = serde_json::to_string(&implicit).unwrap();
349        assert_eq!(
350            serde_json::from_str::<ScalarExpr>(&stored).unwrap(),
351            implicit
352        );
353        assert_ne!(implicit, explicit);
354    }
355}