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