1mod 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
29pub 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 Position(usize),
40 InternalColumn(InternalColumnRef),
42 QualifiedColumn {
43 qualifier: String,
44 column: crate::ast::ReferenceName,
45 },
46 Literal(Value),
47 TypedLiteral {
49 value: Value,
50 ty: String,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 collation_oid: Option<u32>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 composite_source: Option<Box<crate::expr::composites::CompositeConstantSource>>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 bound_type: Option<ColumnType>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
62 parameter_index: Option<usize>,
63 },
64 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 #[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 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 #[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 #[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 #[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 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 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 #[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
218const 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 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 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 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 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}