1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
//! A PartiQL abstract syntax tree (AST).
//!
//! This module contains the structures for the language AST.
//! Two main entities in the module are [`Item`] and [`ItemKind`]. `Item` represents an AST element
//! and `ItemKind` represents a concrete type with the data specific to the type of the item.

// As more changes to this AST are expected, unless explicitly advised, using the structures exposed
// in this crate directly is not recommended.

use partiql_source_map::location::{ByteOffset, BytePosition, Location};
use rust_decimal::Decimal as RustDecimal;

use std::fmt;
use std::fmt::Display;
use std::ops::Range;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Provides the required methods for AstNode conversations.
pub trait ToAstNode: Sized {
    /// Wraps the `self` to an [AstNode] and returns an `AstNodeBuilder` for
    /// further [AstNode] construction.
    /// ## Example:
    /// ```
    /// use partiql_ast::ast;
    /// use partiql_ast::ast::{SymbolPrimitive, ToAstNode};
    /// use partiql_ast::ast::CaseSensitivity::CaseInsensitive;
    /// use partiql_source_map::location::{ByteOffset, BytePosition, Location, ToLocated};
    ///
    /// let p = SymbolPrimitive {
    ///     value: "symbol2".to_string(),
    ///     case: Some(ast::CaseSensitivity::CaseInsensitive)
    ///  };
    ///
    /// let node = p
    ///     .to_node()
    ///     .location((BytePosition::from(12)..BytePosition::from(1)).into())
    ///     .build()
    ///     .expect("Could not retrieve ast node");
    /// ```
    fn to_node(self) -> AstNodeBuilder<Self, BytePosition>
    where
        Self: Clone,
    {
        AstNodeBuilder::default().node(self).clone()
    }

    fn to_ast<Loc, IntoLoc>(self, location: IntoLoc) -> AstNode<Self, Loc>
    where
        Loc: Display,
        IntoLoc: Into<Location<Loc>>,
    {
        AstNode {
            node: self,
            location: Some(location.into()),
        }
    }

    fn ast(self, Range { start, end }: Range<ByteOffset>) -> AstNode<Self, BytePosition> {
        self.to_ast(start.into()..end.into())
    }
}

/// Implements [ToAstNode] for all types within this crate, read further [here][1].
///
/// [1]: https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods
impl<T> ToAstNode for T {}

/// Represents an AST node. [AstNode] uses [derive_builder][1] to expose a Builder
/// for creating the node. See [ToAstNode] for more details on the usage.
///
/// [1]: https://crates.io/crates/derive_builder
#[derive(Builder, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct AstNode<T, Loc: Display> {
    pub node: T,
    #[builder(setter(strip_option), default)]
    pub location: Option<Location<Loc>>,
}

impl<T: PartialEq, Loc: Display> PartialEq for AstNode<T, Loc> {
    fn eq(&self, other: &Self) -> bool {
        self.node == other.node
    }
}

impl<T: Eq, Loc: Display> Eq for AstNode<T, Loc> {}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Item {
    pub kind: ItemKind,
    // We can/require to extend the fields as we get more clarity on the path forward.
    // Candidate additional fields are `name: Ident`, `span: Span`, `attr: Vec<Attribute>`.
}

impl fmt::Display for Item {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Use Debug formatting for now
        write!(f, "{:?}", self.kind)
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ItemKind {
    // Data Definition Language statements
    Ddl(Ddl),
    // Data Modification Language statements
    Dml(Dml),
    // Data retrieval statements
    Query(Query),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Ddl {
    pub op: DdlOp,
}

/// A data definition operation.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DdlOp {
    pub kind: DdlOpKind,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum DdlOpKind {
    /// `CREATE TABLE <symbol>`
    CreateTable(CreateTable),
    /// `DROP TABLE <Ident>`
    DropTable(DropTable),
    /// `CREATE INDEX ON <Ident> (<expr> [, <expr>]...)`
    CreateIndex(CreateIndex),
    /// DROP INDEX <Ident> ON <Ident>
    /// In Statement, first <Ident> represents keys, second represents table
    DropIndex(DropIndex),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CreateTable {
    pub table_name: SymbolPrimitive,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DropTable {
    pub table_name: SymbolPrimitive,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CreateIndex {
    pub index_name: Ident,
    pub fields: Vec<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DropIndex {
    pub table: Ident,
    pub keys: Ident,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Dml {
    pub op: DmlOp,
}

/// A Data Manipulation Operation.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DmlOp {
    pub kind: DmlOpKind,
    pub from_clause: Option<FromClause>,
    pub where_clause: Option<Box<Expr>>,
    pub returning: Option<ReturningExpr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum DmlOpKind {
    /// `INSERT INTO <expr> <expr>`
    Insert(Insert),
    /// `INSERT INTO <expr> VALUE <expr> [AT <expr>]` [ON CONFLICT WHERE <expr> DO NOTHING]`
    InsertValue(InsertValue),
    /// `SET <assignment>...`
    Set(Set),
    /// `REMOVE <expr>`
    Remove(Remove),
    /// DELETE
    Delete,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Insert {
    pub target: Box<Expr>,
    pub values: Box<Expr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct InsertValue {
    pub target: Box<Expr>,
    pub value: Box<Expr>,
    pub index: Option<Box<Expr>>,
    pub on_conflict: Option<OnConflict>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Set {
    pub assignment: Assignment,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Remove {
    pub target: Box<Expr>,
}

/// `ON CONFLICT <expr> <conflict_action>`
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OnConflict {
    pub expr: Box<Expr>,
    pub conflict_action: ConflictAction,
}

/// `CONFLICT_ACTION <action>`
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ConflictAction {
    DoNothing,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Expr {
    pub kind: ExprKind,
}

/// Represents an AST Node of type T with BytePosition Location
pub type AstBytePos<T> = AstNode<T, BytePosition>;

pub type BagAst = AstBytePos<Bag>;
pub type BetweenAst = AstBytePos<Between>;
pub type BinOpAst = AstBytePos<BinOp>;
pub type CallAggAst = AstBytePos<CallAgg>;
pub type CallArgAst = AstBytePos<CallArg>;
pub type CallAst = AstBytePos<Call>;
pub type CaseAst = AstBytePos<Case>;
pub type FromClauseAst = AstBytePos<FromClause>;
pub type FromLetAst = AstBytePos<FromLet>;
pub type GroupByExprAst = AstBytePos<GroupByExpr>;
pub type GroupKeyAst = AstBytePos<GroupKey>;
pub type InAst = AstBytePos<In>;
pub type JoinAst = AstBytePos<Join>;
pub type JoinSpecAst = AstBytePos<JoinSpec>;
pub type LetAst = AstBytePos<Let>;
pub type LikeAst = AstBytePos<Like>;
pub type ListAst = AstBytePos<List>;
pub type LitAst = AstBytePos<Lit>;
pub type OrderByExprAst = AstBytePos<OrderByExpr>;
pub type ParamAst = AstBytePos<Param>;
pub type PathAst = AstBytePos<Path>;
pub type ProjectItemAst = AstBytePos<ProjectItem>;
pub type ProjectionAst = AstBytePos<Projection>;
pub type QueryAst = AstBytePos<Query>;
pub type QuerySetAst = AstBytePos<QuerySet>;
pub type SearchedCaseAst = AstBytePos<SearchedCase>;
pub type SelectAst = AstBytePos<Select>;
pub type SetExprAst = AstBytePos<SetExpr>;
pub type SexpAst = AstBytePos<Sexp>;
pub type SimpleCaseAst = AstBytePos<SimpleCase>;
pub type SortSpecAst = AstBytePos<SortSpec>;
pub type StructAst = AstBytePos<Struct>;
pub type UniOpAst = AstBytePos<UniOp>;
pub type VarRefAst = AstBytePos<VarRef>;

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Query {
    pub set: QuerySetAst,
    pub order_by: Option<Box<OrderByExprAst>>,
    pub limit: Option<Box<Expr>>,
    pub offset: Option<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum QuerySet {
    SetOp(Box<SetExprAst>),
    Select(Box<SelectAst>),
    Expr(Box<Expr>),
    Values(Vec<Box<Expr>>),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SetExpr {
    pub setop: SetOperator,
    pub setq: SetQuantifier,
    pub lhs: Box<QuerySetAst>,
    pub rhs: Box<QuerySetAst>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum SetOperator {
    Union,
    Except,
    Intersect,
}

/// The expressions that can result in values.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ExprKind {
    Lit(LitAst),
    /// Variable reference
    VarRef(VarRefAst),
    /// A parameter, i.e. `?`
    Param(ParamAst),
    /// Binary operator
    BinOp(BinOpAst),
    /// Unary operators
    UniOp(UniOpAst),
    /// Comparison operators
    Like(LikeAst),
    Between(BetweenAst),
    In(InAst),
    Case(CaseAst),
    /// Constructors
    Struct(StructAst),
    Bag(BagAst),
    List(ListAst),
    Sexp(SexpAst),
    /// Other expression types
    Path(PathAst),
    Call(CallAst),
    CallAgg(CallAggAst),

    /// Query, e.g. `UNION` | `EXCEPT` | `INTERSECT` | `SELECT` and their parts.
    Query(QueryAst),

    /// Indicates an error occurred during query processing; The exact error details are out of band of the AST
    Error,
}

/// `Lit` is mostly inspired by SQL-92 Literals standard and PartiQL specification.
/// See section 5.3 in the following:
/// <https://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt>
/// and Section 2 of the following (Figure 1: BNF Grammar for PartiQL Values):
/// <https://partiql.org/assets/PartiQL-Specification.pdf>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Lit {
    Null,
    Missing,
    Int8Lit(i8),
    Int16Lit(i16),
    Int32Lit(i32),
    Int64Lit(i64),
    DecimalLit(RustDecimal),
    NumericLit(RustDecimal),
    RealLit(f32),
    FloatLit(f32),
    DoubleLit(f64),
    BoolLit(bool),
    IonStringLit(String),
    CharStringLit(String),
    NationalCharStringLit(String),
    BitStringLit(String),
    HexStringLit(String),
    DateTimeLit(DateTimeLit),
    CollectionLit(CollectionLit),
    /// E.g. `TIME WITH TIME ZONE` in `SELECT TIME WITH TIME ZONE '12:00' FROM ...`
    TypedLit(String, Type),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CollectionLit {
    ArrayLit(String),
    BagLit(String),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum DateTimeLit {
    DateLit(String),
    TimeLit(String),
    TimestampLit(String),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct VarRef {
    pub name: SymbolPrimitive,
    pub qualifier: ScopeQualifier,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Param {
    pub index: i32,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BinOp {
    pub kind: BinOpKind,
    pub lhs: Box<Expr>,
    pub rhs: Box<Expr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum BinOpKind {
    // Arithmetic
    Add,
    Div,
    Exp,
    Mod,
    Mul,
    Neg,
    // Logical
    And,
    Or,
    // String
    Concat,
    // Comparison
    Eq,
    Gt,
    Gte,
    Lt,
    Lte,
    Ne,
    Is,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct UniOp {
    pub kind: UniOpKind,
    pub expr: Box<Expr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum UniOpKind {
    Pos,
    Neg,
    Not,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Like {
    pub value: Box<Expr>,
    pub pattern: Box<Expr>,
    pub escape: Option<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Between {
    pub value: Box<Expr>,
    pub from: Box<Expr>,
    pub to: Box<Expr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct In {
    pub lhs: Box<Expr>,
    pub rhs: Box<Expr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Case {
    pub kind: CaseKind,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CaseKind {
    /// CASE <expr> [ WHEN <expr> THEN <expr> ]... [ ELSE <expr> ] END
    SimpleCase(SimpleCase),
    /// CASE [ WHEN <expr> THEN <expr> ]... [ ELSE <expr> ] END
    SearchedCase(SearchedCase),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SimpleCase {
    pub expr: Box<Expr>,
    pub cases: Vec<ExprPair>,
    pub default: Option<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SearchedCase {
    pub cases: Vec<ExprPair>,
    pub default: Option<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Struct {
    pub fields: Vec<ExprPair>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Bag {
    pub values: Vec<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct List {
    pub values: Vec<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Sexp {
    pub values: Vec<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Call {
    pub func_name: SymbolPrimitive,
    pub args: Vec<CallArgAst>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CallArg {
    /// `*` used as an argument to a function call (e.g., in `count(*)`)
    Star(),
    /// positional argument to a function call (e.g., all arguments in `foo(1, 'a', 3)`)
    Positional(Box<Expr>),

    /// E.g. `INT` in `foo(INT)`
    PositionalType(Type),
    /// named argument to a function call (e.g., the `"from" : 2` in `substring(a, "from":2)`
    Named {
        name: SymbolPrimitive,
        value: Box<Expr>,
    },

    /// E.g. `AS: VARCHAR` in `CAST('abc' AS VARCHAR`
    NamedType { name: SymbolPrimitive, ty: Type },
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CallAgg {
    pub func_name: SymbolPrimitive,
    pub setq: Option<SetQuantifier>,
    pub args: Vec<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Select {
    pub project: ProjectionAst,
    pub from: Option<FromClauseAst>,
    pub from_let: Option<LetAst>,
    pub where_clause: Option<Box<Expr>>,
    pub group_by: Option<Box<GroupByExprAst>>,
    pub having: Option<Box<Expr>>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Path {
    pub root: Box<Expr>,
    pub steps: Vec<PathStep>,
}

/// A "step" within a path expression; that is the components of the expression following the root.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum PathStep {
    PathExpr(PathExpr),
    PathWildCard,
    PathUnpivot,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PathExpr {
    pub index: Box<Expr>,
}

/// Is used to determine if variable lookup should be case-sensitive or not.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CaseSensitivity {
    CaseSensitive,
    CaseInsensitive,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Projection {
    pub kind: ProjectionKind,
    pub setq: Option<SetQuantifier>,
}

/// Indicates the type of projection in a SFW query.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ProjectionKind {
    ProjectStar,
    ProjectList(Vec<ProjectItemAst>),
    ProjectPivot { key: Box<Expr>, value: Box<Expr> },
    ProjectValue(Box<Expr>),
}

/// An item to be projected in a `SELECT`-list.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ProjectItem {
    /// For `.*` in SELECT list
    ProjectAll(ProjectAll), // TODO remove this?
    /// For `<expr> [AS <id>]`
    ProjectExpr(ProjectExpr),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ProjectAll {
    pub expr: Box<Expr>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ProjectExpr {
    pub expr: Box<Expr>,
    pub as_alias: Option<SymbolPrimitive>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Let {
    /// A list of LET bindings
    pub let_bindings: Vec<LetBinding>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LetBinding {
    pub expr: Box<Expr>,
    pub name: SymbolPrimitive,
}

/// FROM clause of an SFW query
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum FromClause {
    FromLet(FromLetAst),
    /// <from_source> JOIN \[INNER | LEFT | RIGHT | FULL\] <from_source> ON <expr>
    Join(JoinAst),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FromLet {
    pub expr: Box<Expr>,
    pub kind: FromLetKind,
    pub as_alias: Option<SymbolPrimitive>,
    pub at_alias: Option<SymbolPrimitive>,
    pub by_alias: Option<SymbolPrimitive>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Join {
    pub kind: JoinKind,
    pub left: Box<FromClauseAst>,
    pub right: Box<FromClauseAst>,
    pub predicate: Option<JoinSpecAst>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum JoinSpec {
    On(Box<Expr>),
    Using(Vec<Path>),
    Natural,
}

/// Indicates the type of FromLet, see the following for more details:
/// https:///github.com/partiql/partiql-lang-kotlin/issues/242
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum FromLetKind {
    Scan,
    Unpivot,
}

/// Indicates the logical type of join.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum JoinKind {
    Inner,
    Left,
    Right,
    Full,
    Cross,
}

/// A generic pair of expressions. Used in the `pub struct`, `searched_case`
/// and `simple_case` expr variants above.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ExprPair {
    pub first: Box<Expr>,
    pub second: Box<Expr>,
}

/// GROUP BY <grouping_strategy> <group_key_list>... \[AS <symbol>\]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GroupByExpr {
    pub strategy: GroupingStrategy,
    pub key_list: GroupKeyList,
    pub group_as_alias: Option<SymbolPrimitive>,
}

/// Desired grouping qualifier:  ALL or PARTIAL.  Note: the `group_` prefix is
/// needed to avoid naming clashes.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum GroupingStrategy {
    GroupFull,
    GroupPartial,
}

/// <group_key>[, <group_key>]...
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GroupKeyList {
    pub keys: Vec<GroupKeyAst>,
}

/// <expr> [AS <symbol>]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GroupKey {
    pub expr: Box<Expr>,
    pub as_alias: Option<SymbolPrimitive>,
}

/// ORDER BY <sort_spec>...
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct OrderByExpr {
    pub sort_specs: Vec<SortSpecAst>,
}

/// <expr> [ASC | DESC] ?
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SortSpec {
    pub expr: Box<Expr>,
    pub ordering_spec: Option<OrderingSpec>,
    pub null_ordering_spec: Option<NullOrderingSpec>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum OrderingSpec {
    Asc,
    Desc,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum NullOrderingSpec {
    First,
    Last,
}

/// Indicates scope search order when resolving variables.
/// Has no effect except within `FROM` sources.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ScopeQualifier {
    /// Use the default search order.
    Unqualified,
    /// Skip the globals, first check within FROM sources and resolve starting with the local scope.
    Qualified,
}

/// Indicates if a set should be reduced to its distinct elements or not.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum SetQuantifier {
    All,
    Distinct,
}

/// `RETURNING (<returning_elem> [, <returning_elem>]...)`
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ReturningExpr {
    pub elems: Vec<ReturningElem>,
}

/// `<returning mapping> (<expr> [, <expr>]...)`
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ReturningElem {
    pub mapping: ReturningMapping,
    pub column: ColumnComponent,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ColumnComponent {
    ReturningWildcard,
    ReturningColumn(ReturningColumn),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ReturningColumn {
    pub expr: Box<Expr>,
}

/// ( MODIFIED | ALL ) ( NEW | OLD )
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ReturningMapping {
    ModifiedNew,
    ModifiedOld,
    AllNew,
    AllOld,
}

/// `Ident` can be used for names that need to be looked up with a notion of case-sensitivity.

/// For both `create_index` and `create_table`, there is no notion of case-sensitivity
/// for table Idents since they are *defining* new Idents.  However, for `drop_index` and
/// `drop_table` *do* have the notion of case sensitivity since they are referring to existing names.
/// Idents with case-sensitivity is already modeled with the `id` variant of `expr`,
/// but there is no way to specify to PIG that we want to only allow a single variant of a sum as
/// an element of a type.  (Even though in the Kotlin code each varaint is its own type.)  Hence, we
/// define an `Ident` type above which can be used without opening up an element's domain to
/// all of `expr`.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Ident {
    pub name: SymbolPrimitive,
    pub case: CaseSensitivity,
}

/// Represents `<expr> = <expr>` in a DML SET operation.  Note that in this case, `=` is representing
/// an assignment operation and *not* the equality operator.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Assignment {
    pub target: Box<Expr>,
    pub value: Box<Expr>,
}

/// Represents all possible PartiQL data types.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Type {
    NullType,
    BooleanType,
    Integer2Type,
    Integer4Type,
    Integer8Type,
    DecimalType,
    NumericType,
    RealType,
    DoublePrecisionType,
    TimestampType,
    CharacterType,
    CharacterVaryingType,
    MissingType,
    StringType,
    SymbolType,
    BlobType,
    ClobType,
    DateType,
    TimeType,
    ZonedTimestampType,
    StructType,
    TupleType,
    ListType,
    SexpType,
    BagType,
    AnyType,

    CustomType(CustomType),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CustomTypeParam {
    /// E.g. `2` in `VARCHAR(2)`
    Lit(Lit),
    /// E.g. `INT` in `FooType(INT)`
    Type(Type),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CustomTypePart {
    /// E.g. any of `WITH`, `TIME`, and`ZONE` in `TIME(20) WITH TIME ZONE`
    Name(SymbolPrimitive),
    /// E.g. `TIME(20) in `TIME(20) WITH TIME ZONE`
    Parameterized(SymbolPrimitive, Vec<CustomTypeParam>),
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CustomType {
    pub parts: Vec<CustomTypePart>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SymbolPrimitive {
    pub value: String,
    // Optional because string literal symbols don't have case sensitivity
    pub case: Option<CaseSensitivity>,
}