1use serde::{Deserialize, Serialize};
8use std::sync::atomic::{AtomicU64, Ordering};
9use uqa_core::Value;
10
11use super::{FunctionBinding, SelectStmt};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[doc(hidden)]
16pub struct InternalRelationId(u64);
17
18impl InternalRelationId {
19 #[must_use]
21 pub fn allocate() -> Self {
22 static NEXT_ID: AtomicU64 = AtomicU64::new(1);
23 let id = uqa_core::atomic::try_update_u64(
24 &NEXT_ID,
25 Ordering::Relaxed,
26 Ordering::Relaxed,
27 |current| current.checked_add(1),
28 )
29 .expect("internal relation identity space exhausted");
30 Self(id)
31 }
32
33 #[must_use]
35 pub fn column(self, attribute: usize) -> InternalColumnRef {
36 InternalColumnRef {
37 relation: self,
38 attribute: u32::try_from(attribute).expect("internal relation attribute exceeds u32"),
39 }
40 }
41
42 #[must_use]
43 pub const fn raw(self) -> u64 {
44 self.0
45 }
46
47 #[must_use]
48 pub const fn from_raw(raw: u64) -> Self {
49 Self(raw)
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
55#[doc(hidden)]
56pub struct InternalColumnRef {
57 relation: InternalRelationId,
58 attribute: u32,
59}
60
61impl InternalColumnRef {
62 #[must_use]
63 pub const fn relation(self) -> InternalRelationId {
64 self.relation
65 }
66
67 #[must_use]
68 pub const fn attribute(self) -> usize {
69 self.attribute as usize
70 }
71
72 #[must_use]
73 pub const fn from_raw(relation: u64, attribute: u32) -> Self {
74 Self {
75 relation: InternalRelationId::from_raw(relation),
76 attribute,
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub struct Projection {
83 pub expr: Expr,
84 pub alias: Option<String>,
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub struct OrderBy {
89 pub expr: Expr,
90 pub descending: bool,
91 pub nulls: Option<NullsOrder>,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
98pub enum NullsOrder {
99 First,
100 Last,
101}
102
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct WindowDefinition<S = WindowSpec> {
106 pub name: Option<String>,
107 pub inherited: Option<usize>,
108 pub spec: S,
109}
110
111#[derive(Debug, Clone, PartialEq)]
113pub struct WindowDefinitionSyntax(pub(crate) serde_json::Value);
114
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116pub struct WindowSpec {
117 #[serde(skip)]
119 pub raw_definition: Option<WindowDefinitionSyntax>,
120 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub definition: Option<usize>,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub reference: Option<WindowReference>,
126 pub partition_by: Vec<Expr>,
127 pub order_by: Vec<OrderBy>,
128 pub frame: Option<WindowFrame>,
131}
132
133impl WindowSpec {
134 pub fn expressions_mut(&mut self) -> impl Iterator<Item = &mut Expr> {
136 self.partition_by
137 .iter_mut()
138 .chain(self.order_by.iter_mut().map(|order| &mut order.expr))
139 .chain(
140 self.frame
141 .iter_mut()
142 .flat_map(|frame| [&mut frame.start, &mut frame.end])
143 .filter_map(|bound| match bound {
144 FrameBound::Preceding(value) | FrameBound::Following(value) => {
145 Some(value.as_mut())
146 }
147 _ => None,
148 }),
149 )
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct WindowReference {
155 pub name: String,
156 pub kind: WindowReferenceKind,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160pub enum WindowReferenceKind {
161 Direct,
163 Copy,
165}
166
167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
168pub struct WindowFrame {
169 pub mode: FrameMode,
170 pub start: FrameBound,
171 pub end: FrameBound,
172 #[serde(default = "super::default_true")]
174 pub between: bool,
175 #[serde(default, skip_serializing_if = "FrameExclusion::is_no_others")]
176 pub exclusion: FrameExclusion,
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
180pub enum FrameMode {
181 Rows,
182 Range,
183 Groups,
184}
185
186#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
188pub enum FunctionCallSyntax {
189 #[default]
190 Legacy,
191 Ordinary,
192 WithinGroup,
193 Extract,
194}
195
196pub type FunctionOrderSyntax = FunctionCallSyntax;
198
199impl FunctionCallSyntax {
200 #[must_use]
201 pub const fn is_legacy(&self) -> bool {
202 matches!(self, Self::Legacy)
203 }
204}
205
206#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
208pub struct WindowCallModifiers {
209 pub distinct: bool,
210 pub ordered: bool,
212 pub within_group: bool,
213}
214
215impl WindowCallModifiers {
216 #[must_use]
217 pub const fn is_empty(&self) -> bool {
218 !self.distinct && !self.ordered && !self.within_group
219 }
220}
221
222#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
224pub enum FrameExclusion {
225 #[default]
226 NoOthers,
227 CurrentRow,
228 Group,
230 Ties,
232}
233
234impl FrameExclusion {
235 #[must_use]
236 pub const fn is_no_others(&self) -> bool {
237 matches!(self, Self::NoOthers)
238 }
239
240 #[must_use]
242 pub const fn sql(self) -> Option<&'static str> {
243 match self {
244 Self::NoOthers => None,
245 Self::CurrentRow => Some("EXCLUDE CURRENT ROW"),
246 Self::Group => Some("EXCLUDE GROUP"),
247 Self::Ties => Some("EXCLUDE TIES"),
248 }
249 }
250}
251
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253pub enum FrameBound {
254 UnboundedPreceding,
255 UnboundedFollowing,
256 CurrentRow,
257 Preceding(Box<Expr>),
258 Following(Box<Expr>),
259}
260
261#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263pub enum Expr {
264 Star,
265 QualifiedStar(String),
267 Default,
269 Column(String),
271 QualifiedColumn {
273 qualifier: String,
274 column: String,
275 },
276 #[doc(hidden)]
278 InternalColumn(InternalColumnRef),
279 Literal(Value),
280 #[doc(hidden)]
282 TypedLiteral {
283 value: Value,
284 ty: String,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
287 collation_oid: Option<u32>,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
290 composite_source: Option<Box<crate::expr::composites::CompositeConstantSource>>,
291 },
292 Param(usize),
294 Func {
296 name: String,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
298 binding: Option<FunctionBinding>,
299 args: Vec<Expr>,
300 distinct: bool,
303 order_by: Vec<OrderBy>,
305 #[serde(default, skip_serializing_if = "FunctionOrderSyntax::is_legacy")]
306 order_syntax: FunctionOrderSyntax,
307 filter: Option<Box<Expr>>,
309 },
310 Array(Vec<Expr>),
312 Row(Vec<Expr>),
314 CompositeRow {
316 items: Vec<Expr>,
317 binding: super::CompositeRowBinding,
318 },
319 Binary {
321 op: BinaryOp,
322 lhs: Box<Expr>,
323 rhs: Box<Expr>,
324 },
325 UnaryMinus(Box<Expr>),
328 Not(Box<Expr>),
330 And(Vec<Expr>),
332 Or(Vec<Expr>),
334 IsNull {
336 expr: Box<Expr>,
337 negated: bool,
338 },
339 Between {
341 expr: Box<Expr>,
342 low: Box<Expr>,
343 high: Box<Expr>,
344 },
345 InList {
347 expr: Box<Expr>,
348 list: Vec<Expr>,
349 negated: bool,
350 },
351 WindowCall {
353 name: String,
354 args: Vec<Expr>,
355 spec: Box<WindowSpec>,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 filter: Option<Box<Expr>>,
358 #[serde(default, skip_serializing_if = "WindowCallModifiers::is_empty")]
359 modifiers: WindowCallModifiers,
360 },
361 Case {
366 base: Option<Box<Expr>>,
367 when: Vec<(Expr, Expr)>,
368 else_branch: Option<Box<Expr>>,
369 },
370 Cast {
373 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
375 implicit: bool,
376 expr: Box<Expr>,
377 ty: String,
378 },
379 ScalarSubquery(Box<SelectStmt>),
382 Exists {
385 body: Box<SelectStmt>,
386 negated: bool,
387 },
388 InSubquery {
392 expr: Box<Expr>,
393 body: Box<SelectStmt>,
394 negated: bool,
395 },
396 #[serde(untagged, skip_deserializing)]
398 RetainedLiteral(Box<super::RetainedInputLiteral>),
399}
400
401impl Expr {
402 pub fn qualified_column(qualifier: impl Into<String>, column: impl Into<String>) -> Self {
403 Self::QualifiedColumn {
404 qualifier: qualifier.into(),
405 column: column.into(),
406 }
407 }
408
409 #[doc(hidden)]
411 #[expect(
412 clippy::too_many_lines,
413 reason = "exhaustive AST migration preserves every serialized variant"
414 )]
415 pub fn upgrade_legacy_serialized_dispatches(&mut self) -> bool {
416 let mut changed = false;
417 match self {
418 Self::Func {
419 name,
420 binding,
421 args,
422 order_by,
423 filter,
424 ..
425 } => {
426 for argument in args.iter_mut() {
427 changed |= argument.upgrade_legacy_serialized_dispatches();
428 }
429 for order in order_by {
430 changed |= order.expr.upgrade_legacy_serialized_dispatches();
431 }
432 if let Some(filter) = filter {
433 changed |= filter.upgrade_legacy_serialized_dispatches();
434 }
435 changed |=
436 super::FunctionBinding::upgrade_legacy_serialized_dispatch(name, binding);
437 changed |= super::FunctionBinding::upgrade_legacy_array_slices(
438 binding,
439 args.len(),
440 |index| matches!(args[index], Expr::Literal(Value::Null)),
441 );
442 }
443 Self::Array(items)
444 | Self::Row(items)
445 | Self::CompositeRow { items, .. }
446 | Self::And(items)
447 | Self::Or(items) => {
448 for item in items {
449 changed |= item.upgrade_legacy_serialized_dispatches();
450 }
451 }
452 Self::Binary { lhs, rhs, .. } => {
453 changed |= lhs.upgrade_legacy_serialized_dispatches();
454 changed |= rhs.upgrade_legacy_serialized_dispatches();
455 }
456 Self::UnaryMinus(inner)
457 | Self::Not(inner)
458 | Self::IsNull { expr: inner, .. }
459 | Self::Cast { expr: inner, .. } => {
460 changed |= inner.upgrade_legacy_serialized_dispatches();
461 }
462 Self::Between { expr, low, high } => {
463 changed |= expr.upgrade_legacy_serialized_dispatches();
464 changed |= low.upgrade_legacy_serialized_dispatches();
465 changed |= high.upgrade_legacy_serialized_dispatches();
466 }
467 Self::InList { expr, list, .. } => {
468 changed |= expr.upgrade_legacy_serialized_dispatches();
469 for item in list {
470 changed |= item.upgrade_legacy_serialized_dispatches();
471 }
472 }
473 Self::WindowCall {
474 args, spec, filter, ..
475 } => {
476 for argument in args {
477 changed |= argument.upgrade_legacy_serialized_dispatches();
478 }
479 if let Some(filter) = filter {
480 changed |= filter.upgrade_legacy_serialized_dispatches();
481 }
482 for partition in &mut spec.partition_by {
483 changed |= partition.upgrade_legacy_serialized_dispatches();
484 }
485 for order in &mut spec.order_by {
486 changed |= order.expr.upgrade_legacy_serialized_dispatches();
487 }
488 if let Some(frame) = &mut spec.frame {
489 for bound in [&mut frame.start, &mut frame.end] {
490 match bound {
491 FrameBound::Preceding(expression)
492 | FrameBound::Following(expression) => {
493 changed |= expression.upgrade_legacy_serialized_dispatches();
494 }
495 FrameBound::UnboundedPreceding
496 | FrameBound::UnboundedFollowing
497 | FrameBound::CurrentRow => {}
498 }
499 }
500 }
501 }
502 Self::Case {
503 base,
504 when,
505 else_branch,
506 } => {
507 if let Some(base) = base {
508 changed |= base.upgrade_legacy_serialized_dispatches();
509 }
510 for (condition, result) in when {
511 changed |= condition.upgrade_legacy_serialized_dispatches();
512 changed |= result.upgrade_legacy_serialized_dispatches();
513 }
514 if let Some(branch) = else_branch {
515 changed |= branch.upgrade_legacy_serialized_dispatches();
516 }
517 }
518 Self::InSubquery { expr, body, .. } => {
519 changed |= expr.upgrade_legacy_serialized_dispatches();
520 changed |= body.upgrade_legacy_serialized_dispatches();
521 }
522 Self::ScalarSubquery(body) | Self::Exists { body, .. } => {
523 changed |= body.upgrade_legacy_serialized_dispatches();
524 }
525 Self::Default
526 | Self::Star
527 | Self::QualifiedStar(_)
528 | Self::Column(_)
529 | Self::QualifiedColumn { .. }
530 | Self::InternalColumn(_)
531 | Self::Literal(_)
532 | Self::TypedLiteral { .. }
533 | Self::RetainedLiteral(_)
534 | Self::Param(_) => {}
535 }
536 crate::type_resolution::between::restore_ast_node(self) | changed
537 }
538
539 #[must_use]
541 pub fn contains_window(&self) -> bool {
542 self.any_node(&|node| matches!(node, Self::WindowCall { .. }))
543 }
544
545 #[must_use]
547 pub fn contains_aggregate(&self) -> bool {
548 self.any_node(
549 &|node| matches!(node, Self::Func { name, .. } if is_builtin_aggregate_function(name)),
550 )
551 }
552
553 #[must_use]
555 pub fn contains_unqualified_column(&self) -> bool {
556 self.any_node(&|node| matches!(node, Self::Column(_)))
557 }
558
559 #[must_use]
561 pub fn contains_function_with_unknown_strictness(&self) -> bool {
562 self.any_node(&|node| {
563 matches!(
564 node,
565 Self::Func {
566 name,
567 args,
568 binding,
569 ..
570 } if crate::expr::bound_scalar_function_strictness(
571 name,
572 binding.as_ref(),
573 args.len(),
574 )
575 .is_none()
576 )
577 })
578 }
579
580 #[must_use]
582 pub fn any_node(&self, hit: &dyn Fn(&Self) -> bool) -> bool {
583 if hit(self) {
584 return true;
585 }
586 match self {
587 Self::Func {
588 args,
589 order_by,
590 filter,
591 ..
592 } => {
593 args.iter().any(|arg| arg.any_node(hit))
594 || order_by.iter().any(|order| order.expr.any_node(hit))
595 || filter.as_deref().is_some_and(|filter| filter.any_node(hit))
596 }
597 Self::Array(items)
598 | Self::Row(items)
599 | Self::CompositeRow { items, .. }
600 | Self::And(items)
601 | Self::Or(items) => items.iter().any(|item| item.any_node(hit)),
602 Self::UnaryMinus(expr) | Self::Not(expr) | Self::Cast { expr, .. } => {
603 expr.any_node(hit)
604 }
605 Self::Binary { lhs, rhs, .. } => lhs.any_node(hit) || rhs.any_node(hit),
606 Self::IsNull { expr, .. } | Self::InSubquery { expr, .. } => expr.any_node(hit),
607 Self::Between { expr, low, high } => {
608 expr.any_node(hit) || low.any_node(hit) || high.any_node(hit)
609 }
610 Self::InList { expr, list, .. } => {
611 expr.any_node(hit) || list.iter().any(|item| item.any_node(hit))
612 }
613 Self::Case {
614 base,
615 when,
616 else_branch,
617 } => {
618 base.as_deref().is_some_and(|base| base.any_node(hit))
619 || when
620 .iter()
621 .any(|(condition, result)| condition.any_node(hit) || result.any_node(hit))
622 || else_branch
623 .as_deref()
624 .is_some_and(|branch| branch.any_node(hit))
625 }
626 Self::WindowCall { .. }
627 | Self::Star
628 | Self::QualifiedStar(_)
629 | Self::Default
630 | Self::Column(_)
631 | Self::QualifiedColumn { .. }
632 | Self::InternalColumn(_)
633 | Self::Literal(_)
634 | Self::TypedLiteral { .. }
635 | Self::RetainedLiteral(_)
636 | Self::Param(_)
637 | Self::ScalarSubquery(_)
638 | Self::Exists { .. } => false,
639 }
640 }
641}
642
643#[must_use]
645pub fn is_builtin_aggregate_function(name: &str) -> bool {
646 matches!(
647 name.to_ascii_lowercase().as_str(),
648 "count"
649 | "sum"
650 | "avg"
651 | "min"
652 | "max"
653 | "string_agg"
654 | "array_agg"
655 | "bool_and"
656 | "bool_or"
657 | "stddev"
658 | "stddev_samp"
659 | "stddev_pop"
660 | "variance"
661 | "var_samp"
662 | "var_pop"
663 | "percentile_cont"
664 | "percentile_disc"
665 | "mode"
666 | "json_agg"
667 | "jsonb_agg"
668 | "json_object_agg"
669 | "jsonb_object_agg"
670 )
671}
672
673#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
674pub enum BinaryOp {
675 Equal,
676 NotEqual,
677 Less,
678 LessEqual,
679 Greater,
680 GreaterEqual,
681 Add,
682 Subtract,
683 Multiply,
684 Divide,
685}
686
687pub type ValueExpr = Expr;