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(crate::ast::ReferenceName),
267 Default,
269 Column(crate::ast::ReferenceName),
271 QualifiedColumn {
273 qualifier: String,
274 column: crate::ast::ReferenceName,
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 reference_qualifier(&self) -> Option<&str> {
404 match self {
405 Self::QualifiedColumn { qualifier, .. } => Some(qualifier),
406 Self::QualifiedStar(qualifier) => Some(qualifier),
407 _ => None,
408 }
409 }
410
411 pub fn reference_qualifier_mut(&mut self) -> Option<&mut String> {
413 match self {
414 Self::QualifiedColumn { qualifier, .. } => Some(qualifier),
415 Self::QualifiedStar(qualifier) => Some(qualifier),
416 _ => None,
417 }
418 }
419
420 pub fn reference_position(&self) -> Option<u32> {
422 match self {
423 Self::Column(name) | Self::QualifiedStar(name) => name.position(),
424 Self::QualifiedColumn { column, .. } => column.position(),
425 _ => None,
426 }
427 }
428
429 pub fn set_reference_position(&mut self, position: Option<u32>) {
431 match self {
432 Self::Column(name)
433 | Self::QualifiedStar(name)
434 | Self::QualifiedColumn { column: name, .. } => name.set_position(position),
435 _ => {}
436 }
437 }
438
439 pub fn qualified_column(
440 qualifier: impl Into<String>,
441 column: impl Into<crate::ast::ReferenceName>,
442 ) -> Self {
443 Self::QualifiedColumn {
444 qualifier: qualifier.into(),
445 column: column.into(),
446 }
447 }
448
449 #[doc(hidden)]
451 #[expect(
452 clippy::too_many_lines,
453 reason = "exhaustive AST migration preserves every serialized variant"
454 )]
455 pub fn upgrade_legacy_serialized_dispatches(&mut self) -> bool {
456 let mut changed = false;
457 match self {
458 Self::Func {
459 name,
460 binding,
461 args,
462 order_by,
463 filter,
464 ..
465 } => {
466 for argument in args.iter_mut() {
467 changed |= argument.upgrade_legacy_serialized_dispatches();
468 }
469 for order in order_by {
470 changed |= order.expr.upgrade_legacy_serialized_dispatches();
471 }
472 if let Some(filter) = filter {
473 changed |= filter.upgrade_legacy_serialized_dispatches();
474 }
475 changed |=
476 super::FunctionBinding::upgrade_legacy_serialized_dispatch(name, binding);
477 changed |= super::FunctionBinding::upgrade_legacy_array_slices(
478 binding,
479 args.len(),
480 |index| matches!(args[index], Expr::Literal(Value::Null)),
481 );
482 }
483 Self::Array(items)
484 | Self::Row(items)
485 | Self::CompositeRow { items, .. }
486 | Self::And(items)
487 | Self::Or(items) => {
488 for item in items {
489 changed |= item.upgrade_legacy_serialized_dispatches();
490 }
491 }
492 Self::Binary { lhs, rhs, .. } => {
493 changed |= lhs.upgrade_legacy_serialized_dispatches();
494 changed |= rhs.upgrade_legacy_serialized_dispatches();
495 }
496 Self::UnaryMinus(inner)
497 | Self::Not(inner)
498 | Self::IsNull { expr: inner, .. }
499 | Self::Cast { expr: inner, .. } => {
500 changed |= inner.upgrade_legacy_serialized_dispatches();
501 }
502 Self::Between { expr, low, high } => {
503 changed |= expr.upgrade_legacy_serialized_dispatches();
504 changed |= low.upgrade_legacy_serialized_dispatches();
505 changed |= high.upgrade_legacy_serialized_dispatches();
506 }
507 Self::InList { expr, list, .. } => {
508 changed |= expr.upgrade_legacy_serialized_dispatches();
509 for item in list {
510 changed |= item.upgrade_legacy_serialized_dispatches();
511 }
512 }
513 Self::WindowCall {
514 args, spec, filter, ..
515 } => {
516 for argument in args {
517 changed |= argument.upgrade_legacy_serialized_dispatches();
518 }
519 if let Some(filter) = filter {
520 changed |= filter.upgrade_legacy_serialized_dispatches();
521 }
522 for partition in &mut spec.partition_by {
523 changed |= partition.upgrade_legacy_serialized_dispatches();
524 }
525 for order in &mut spec.order_by {
526 changed |= order.expr.upgrade_legacy_serialized_dispatches();
527 }
528 if let Some(frame) = &mut spec.frame {
529 for bound in [&mut frame.start, &mut frame.end] {
530 match bound {
531 FrameBound::Preceding(expression)
532 | FrameBound::Following(expression) => {
533 changed |= expression.upgrade_legacy_serialized_dispatches();
534 }
535 FrameBound::UnboundedPreceding
536 | FrameBound::UnboundedFollowing
537 | FrameBound::CurrentRow => {}
538 }
539 }
540 }
541 }
542 Self::Case {
543 base,
544 when,
545 else_branch,
546 } => {
547 if let Some(base) = base {
548 changed |= base.upgrade_legacy_serialized_dispatches();
549 }
550 for (condition, result) in when {
551 changed |= condition.upgrade_legacy_serialized_dispatches();
552 changed |= result.upgrade_legacy_serialized_dispatches();
553 }
554 if let Some(branch) = else_branch {
555 changed |= branch.upgrade_legacy_serialized_dispatches();
556 }
557 }
558 Self::InSubquery { expr, body, .. } => {
559 changed |= expr.upgrade_legacy_serialized_dispatches();
560 changed |= body.upgrade_legacy_serialized_dispatches();
561 }
562 Self::ScalarSubquery(body) | Self::Exists { body, .. } => {
563 changed |= body.upgrade_legacy_serialized_dispatches();
564 }
565 Self::Default
566 | Self::Star
567 | Self::QualifiedStar(_)
568 | Self::Column(_)
569 | Self::QualifiedColumn { .. }
570 | Self::InternalColumn(_)
571 | Self::Literal(_)
572 | Self::TypedLiteral { .. }
573 | Self::RetainedLiteral(_)
574 | Self::Param(_) => {}
575 }
576 crate::type_resolution::between::restore_ast_node(self) | changed
577 }
578
579 #[must_use]
581 pub fn contains_window(&self) -> bool {
582 self.any_node(&|node| matches!(node, Self::WindowCall { .. }))
583 }
584
585 #[must_use]
587 pub fn contains_aggregate(&self) -> bool {
588 self.any_node(
589 &|node| matches!(node, Self::Func { name, .. } if is_builtin_aggregate_function(name)),
590 )
591 }
592
593 #[must_use]
595 pub fn contains_unqualified_column(&self) -> bool {
596 self.any_node(&|node| matches!(node, Self::Column(_)))
597 }
598
599 #[must_use]
601 pub fn contains_function_with_unknown_strictness(&self) -> bool {
602 self.any_node(&|node| {
603 matches!(
604 node,
605 Self::Func {
606 name,
607 args,
608 binding,
609 ..
610 } if crate::expr::bound_scalar_function_strictness(
611 name,
612 binding.as_ref(),
613 args.len(),
614 )
615 .is_none()
616 )
617 })
618 }
619
620 #[must_use]
622 pub fn any_node(&self, hit: &dyn Fn(&Self) -> bool) -> bool {
623 if hit(self) {
624 return true;
625 }
626 match self {
627 Self::Func {
628 args,
629 order_by,
630 filter,
631 ..
632 } => {
633 args.iter().any(|arg| arg.any_node(hit))
634 || order_by.iter().any(|order| order.expr.any_node(hit))
635 || filter.as_deref().is_some_and(|filter| filter.any_node(hit))
636 }
637 Self::Array(items)
638 | Self::Row(items)
639 | Self::CompositeRow { items, .. }
640 | Self::And(items)
641 | Self::Or(items) => items.iter().any(|item| item.any_node(hit)),
642 Self::UnaryMinus(expr) | Self::Not(expr) | Self::Cast { expr, .. } => {
643 expr.any_node(hit)
644 }
645 Self::Binary { lhs, rhs, .. } => lhs.any_node(hit) || rhs.any_node(hit),
646 Self::IsNull { expr, .. } | Self::InSubquery { expr, .. } => expr.any_node(hit),
647 Self::Between { expr, low, high } => {
648 expr.any_node(hit) || low.any_node(hit) || high.any_node(hit)
649 }
650 Self::InList { expr, list, .. } => {
651 expr.any_node(hit) || list.iter().any(|item| item.any_node(hit))
652 }
653 Self::Case {
654 base,
655 when,
656 else_branch,
657 } => {
658 base.as_deref().is_some_and(|base| base.any_node(hit))
659 || when
660 .iter()
661 .any(|(condition, result)| condition.any_node(hit) || result.any_node(hit))
662 || else_branch
663 .as_deref()
664 .is_some_and(|branch| branch.any_node(hit))
665 }
666 Self::WindowCall { .. }
667 | Self::Star
668 | Self::QualifiedStar(_)
669 | Self::Default
670 | Self::Column(_)
671 | Self::QualifiedColumn { .. }
672 | Self::InternalColumn(_)
673 | Self::Literal(_)
674 | Self::TypedLiteral { .. }
675 | Self::RetainedLiteral(_)
676 | Self::Param(_)
677 | Self::ScalarSubquery(_)
678 | Self::Exists { .. } => false,
679 }
680 }
681}
682
683#[must_use]
685pub fn is_builtin_aggregate_function(name: &str) -> bool {
686 const NAMES: [&str; 22] = [
687 "count",
688 "sum",
689 "avg",
690 "min",
691 "max",
692 "string_agg",
693 "array_agg",
694 "bool_and",
695 "bool_or",
696 "stddev",
697 "stddev_samp",
698 "stddev_pop",
699 "variance",
700 "var_samp",
701 "var_pop",
702 "percentile_cont",
703 "percentile_disc",
704 "mode",
705 "json_agg",
706 "jsonb_agg",
707 "json_object_agg",
708 "jsonb_object_agg",
709 ];
710 NAMES
711 .iter()
712 .any(|candidate| name.eq_ignore_ascii_case(candidate))
713}
714
715#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
716pub enum BinaryOp {
717 Equal,
718 NotEqual,
719 Less,
720 LessEqual,
721 Greater,
722 GreaterEqual,
723 Add,
724 Subtract,
725 Multiply,
726 Divide,
727}
728
729pub type ValueExpr = Expr;