1pub mod check;
4pub mod fmt;
5
6use std::num::ParseIntError;
7use std::ops::Deref;
8use std::str::{self, Bytes, FromStr};
9
10use strum_macros::{EnumIter, EnumString};
11
12use fmt::{ToTokens, TokenStream};
13use indexmap::{IndexMap, IndexSet};
14
15use crate::custom_err;
16use crate::dialect::TokenType::{self, *};
17use crate::dialect::{from_token, is_identifier, Token};
18use crate::parser::{parse::YYCODETYPE, ParserError};
19
20#[derive(Default)]
22pub struct ParameterInfo {
23 pub count: u32,
25 pub names: IndexSet<String>,
27}
28
29impl TokenStream for ParameterInfo {
31 type Error = ParseIntError;
32
33 fn append(&mut self, ty: TokenType, value: Option<&str>) -> Result<(), Self::Error> {
34 if ty == TK_VARIABLE {
35 if let Some(variable) = value {
36 if variable == "?" {
37 self.count = self.count.saturating_add(1);
38 } else if variable.as_bytes()[0] == b'?' {
39 let n = u32::from_str(&variable[1..])?;
40 if n > self.count {
41 self.count = n;
42 }
43 } else if self.names.insert(variable.to_owned()) {
44 self.count = self.count.saturating_add(1);
45 }
46 }
47 }
48 Ok(())
49 }
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
55pub enum Cmd {
56 Explain(Stmt),
58 ExplainQueryPlan(Stmt),
60 Stmt(Stmt),
62}
63
64pub(crate) enum ExplainKind {
65 Explain,
66 QueryPlan,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73pub enum Stmt {
74 AlterTable(Box<(QualifiedName, AlterTableBody)>),
76 Analyze(Option<QualifiedName>),
78 Attach {
80 expr: Box<Expr>,
83 db_name: Box<Expr>,
85 key: Option<Box<Expr>>,
87 },
88 Begin(Option<TransactionType>, Option<Name>),
90 Commit(Option<Name>), CreateIndex {
94 unique: bool,
96 if_not_exists: bool,
98 idx_name: Box<QualifiedName>,
100 tbl_name: Name,
102 columns: Vec<SortedColumn>,
104 where_clause: Option<Box<Expr>>,
106 },
107 CreateTable {
109 temporary: bool, if_not_exists: bool,
113 tbl_name: QualifiedName,
115 body: Box<CreateTableBody>,
117 },
118 CreateTrigger(Box<CreateTrigger>),
120 CreateView {
122 temporary: bool,
124 if_not_exists: bool,
126 view_name: QualifiedName,
128 columns: Option<Vec<IndexedColumn>>,
130 select: Box<Select>,
132 },
133 CreateVirtualTable(Box<CreateVirtualTable>),
135 Delete(Box<Delete>),
137 Detach(Box<Expr>), DropIndex {
141 if_exists: bool,
143 idx_name: QualifiedName,
145 },
146 DropTable {
148 if_exists: bool,
150 tbl_name: QualifiedName,
152 },
153 DropTrigger {
155 if_exists: bool,
157 trigger_name: QualifiedName,
159 },
160 DropView {
162 if_exists: bool,
164 view_name: QualifiedName,
166 },
167 Insert(Box<Insert>),
169 Pragma(Box<QualifiedName>, Option<Box<PragmaBody>>),
171 Reindex {
173 obj_name: Option<QualifiedName>,
175 },
176 Release(Name), Rollback {
180 tx_name: Option<Name>,
182 savepoint_name: Option<Name>, },
185 Savepoint(Name),
187 Select(Box<Select>),
189 Update(Box<Update>),
191 Vacuum(Option<Name>, Option<Box<Expr>>),
193}
194
195#[derive(Clone, Debug, PartialEq, Eq)]
197#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
198pub struct CreateVirtualTable {
199 pub if_not_exists: bool,
201 pub tbl_name: QualifiedName,
203 pub module_name: Name,
205 pub args: Option<Vec<String>>, }
208
209#[derive(Clone, Debug, PartialEq, Eq)]
211#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
212pub struct CreateTrigger {
213 pub temporary: bool,
215 pub if_not_exists: bool,
217 pub trigger_name: QualifiedName,
219 pub time: Option<TriggerTime>,
221 pub event: TriggerEvent,
223 pub tbl_name: QualifiedName,
225 pub for_each_row: bool,
227 pub when_clause: Option<Expr>,
229 pub commands: Vec<TriggerCmd>,
231}
232
233#[derive(Clone, Debug, PartialEq, Eq)]
235#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
236pub struct Insert {
237 pub with: Option<With>,
239 pub or_conflict: Option<ResolveType>, pub tbl_name: QualifiedName,
243 pub columns: Option<DistinctNames>,
245 pub body: InsertBody,
247 pub returning: Option<Vec<ResultColumn>>,
249}
250
251#[derive(Clone, Debug, PartialEq, Eq)]
253#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
254pub struct Update {
255 pub with: Option<With>,
257 pub or_conflict: Option<ResolveType>,
259 pub tbl_name: QualifiedName,
261 pub indexed: Option<Indexed>,
263 pub sets: Vec<Set>,
265 pub from: Option<FromClause>,
267 pub where_clause: Option<Box<Expr>>,
269 pub returning: Option<Vec<ResultColumn>>,
271 pub order_by: Option<Vec<SortedColumn>>,
273 pub limit: Option<Box<Limit>>,
275}
276
277#[derive(Clone, Debug, PartialEq, Eq)]
279#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
280pub struct Delete {
281 pub with: Option<With>,
283 pub tbl_name: QualifiedName,
285 pub indexed: Option<Indexed>,
287 pub where_clause: Option<Box<Expr>>,
289 pub returning: Option<Vec<ResultColumn>>,
291 pub order_by: Option<Vec<SortedColumn>>,
293 pub limit: Option<Box<Limit>>,
295}
296
297#[repr(transparent)]
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
300pub struct TableInternalId(usize);
308
309impl Default for TableInternalId {
310 fn default() -> Self {
311 Self(1)
312 }
313}
314
315impl From<usize> for TableInternalId {
316 fn from(value: usize) -> Self {
317 Self(value)
318 }
319}
320
321impl std::ops::AddAssign<usize> for TableInternalId {
322 fn add_assign(&mut self, rhs: usize) {
323 self.0 += rhs;
324 }
325}
326
327impl From<TableInternalId> for usize {
328 fn from(value: TableInternalId) -> Self {
329 value.0
330 }
331}
332
333impl std::fmt::Display for TableInternalId {
334 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335 write!(f, "t{}", self.0)
336 }
337}
338
339#[derive(Clone, Debug, PartialEq, Eq)]
342#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
343pub enum Expr {
344 Between {
346 lhs: Box<Expr>,
348 not: bool,
350 start: Box<Expr>,
352 end: Box<Expr>,
354 },
355 Binary(Box<Expr>, Operator, Box<Expr>),
357 Case {
359 base: Option<Box<Expr>>,
361 when_then_pairs: Vec<(Expr, Expr)>,
363 else_expr: Option<Box<Expr>>,
365 },
366 Cast {
368 expr: Box<Expr>,
370 type_name: Option<Type>,
372 },
373 Collate(Box<Expr>, String),
375 DoublyQualified(Name, Name, Name),
377 Exists(Box<Select>),
379 FunctionCall {
381 name: Id,
383 distinctness: Option<Distinctness>,
385 args: Option<Vec<Expr>>,
387 order_by: Option<Vec<SortedColumn>>,
389 filter_over: Option<FunctionTail>,
391 },
392 FunctionCallStar {
394 name: Id,
396 filter_over: Option<FunctionTail>,
398 },
399 Id(Id),
401 Column {
403 database: Option<usize>,
405 table: TableInternalId,
407 column: usize,
409 is_rowid_alias: bool,
411 },
412 RowId {
414 database: Option<usize>,
416 table: TableInternalId,
418 },
419 InList {
421 lhs: Box<Expr>,
423 not: bool,
425 rhs: Option<Vec<Expr>>,
427 },
428 InSelect {
430 lhs: Box<Expr>,
432 not: bool,
434 rhs: Box<Select>,
436 },
437 InTable {
439 lhs: Box<Expr>,
441 not: bool,
443 rhs: QualifiedName,
445 args: Option<Vec<Expr>>,
447 },
448 IsNull(Box<Expr>),
450 Like {
452 lhs: Box<Expr>,
454 not: bool,
456 op: LikeOperator,
458 rhs: Box<Expr>,
460 escape: Option<Box<Expr>>,
462 },
463 Literal(Literal),
465 Name(Name),
467 NotNull(Box<Expr>),
469 Parenthesized(Vec<Expr>),
471 Qualified(Name, Name),
473 Raise(ResolveType, Option<Box<Expr>>),
475 Subquery(Box<Select>),
477 Unary(UnaryOperator, Box<Expr>),
479 Variable(String),
481}
482
483impl Expr {
484 pub fn parenthesized(x: Self) -> Self {
486 Self::Parenthesized(vec![x])
487 }
488 pub fn id(xt: YYCODETYPE, x: Token) -> Self {
490 Self::Id(Id::from_token(xt, x))
491 }
492 pub fn collate(x: Self, ct: YYCODETYPE, c: Token) -> Self {
494 Self::Collate(Box::new(x), from_token(ct, c))
495 }
496 pub fn cast(x: Self, type_name: Option<Type>) -> Self {
498 Self::Cast {
499 expr: Box::new(x),
500 type_name,
501 }
502 }
503 pub fn binary(left: Self, op: YYCODETYPE, right: Self) -> Self {
505 Self::Binary(Box::new(left), Operator::from(op), Box::new(right))
506 }
507 pub fn ptr(left: Self, op: Token, right: Self) -> Self {
509 let mut ptr = Operator::ArrowRight;
510 if op.1 == b"->>" {
511 ptr = Operator::ArrowRightShift;
512 }
513 Self::Binary(Box::new(left), ptr, Box::new(right))
514 }
515 pub fn like(lhs: Self, not: bool, op: LikeOperator, rhs: Self, escape: Option<Self>) -> Self {
517 Self::Like {
518 lhs: Box::new(lhs),
519 not,
520 op,
521 rhs: Box::new(rhs),
522 escape: escape.map(Box::new),
523 }
524 }
525 pub fn not_null(x: Self, op: YYCODETYPE) -> Self {
527 if op == TK_ISNULL as YYCODETYPE {
528 Self::IsNull(Box::new(x))
529 } else if op == TK_NOTNULL as YYCODETYPE {
530 Self::NotNull(Box::new(x))
531 } else {
532 unreachable!()
533 }
534 }
535 pub fn unary(op: UnaryOperator, x: Self) -> Self {
537 Self::Unary(op, Box::new(x))
538 }
539 pub fn between(lhs: Self, not: bool, start: Self, end: Self) -> Self {
541 Self::Between {
542 lhs: Box::new(lhs),
543 not,
544 start: Box::new(start),
545 end: Box::new(end),
546 }
547 }
548 pub fn in_list(lhs: Self, not: bool, rhs: Option<Vec<Self>>) -> Self {
550 Self::InList {
551 lhs: Box::new(lhs),
552 not,
553 rhs,
554 }
555 }
556 pub fn in_select(lhs: Self, not: bool, rhs: Select) -> Self {
558 Self::InSelect {
559 lhs: Box::new(lhs),
560 not,
561 rhs: Box::new(rhs),
562 }
563 }
564 pub fn in_table(lhs: Self, not: bool, rhs: QualifiedName, args: Option<Vec<Self>>) -> Self {
566 Self::InTable {
567 lhs: Box::new(lhs),
568 not,
569 rhs,
570 args,
571 }
572 }
573 pub fn sub_query(query: Select) -> Self {
575 Self::Subquery(Box::new(query))
576 }
577}
578
579#[derive(Clone, Debug, PartialEq, Eq)]
581#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
582pub enum Literal {
583 Numeric(String),
585 String(String),
588 Blob(String),
591 Keyword(String),
593 Null,
595 CurrentDate,
597 CurrentTime,
599 CurrentTimestamp,
601}
602
603impl Literal {
604 pub fn from_ctime_kw(token: Token) -> Self {
606 if b"CURRENT_DATE".eq_ignore_ascii_case(token.1) {
607 Self::CurrentDate
608 } else if b"CURRENT_TIME".eq_ignore_ascii_case(token.1) {
609 Self::CurrentTime
610 } else if b"CURRENT_TIMESTAMP".eq_ignore_ascii_case(token.1) {
611 Self::CurrentTimestamp
612 } else {
613 unreachable!()
614 }
615 }
616}
617
618#[derive(Copy, Clone, Debug, PartialEq, Eq)]
620#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
621pub enum LikeOperator {
622 Glob,
624 Like,
626 Match,
628 Regexp,
630}
631
632impl LikeOperator {
633 pub fn from_token(token_type: YYCODETYPE, token: Token) -> Self {
635 if token_type == TK_MATCH as YYCODETYPE {
636 return Self::Match;
637 } else if token_type == TK_LIKE_KW as YYCODETYPE {
638 let token = token.1;
639 if b"LIKE".eq_ignore_ascii_case(token) {
640 return Self::Like;
641 } else if b"GLOB".eq_ignore_ascii_case(token) {
642 return Self::Glob;
643 } else if b"REGEXP".eq_ignore_ascii_case(token) {
644 return Self::Regexp;
645 }
646 }
647 unreachable!()
648 }
649}
650
651#[derive(Copy, Clone, Debug, PartialEq, Eq)]
653#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
654pub enum Operator {
655 Add,
657 And,
659 ArrowRight,
661 ArrowRightShift,
663 BitwiseAnd,
665 BitwiseOr,
667 BitwiseNot,
669 Concat,
671 Equals,
673 Divide,
675 Greater,
677 GreaterEquals,
679 Is,
681 IsNot,
683 LeftShift,
685 Less,
687 LessEquals,
689 Modulus,
691 Multiply,
693 NotEquals,
695 Or,
697 RightShift,
699 Subtract,
701}
702
703impl From<YYCODETYPE> for Operator {
704 fn from(token_type: YYCODETYPE) -> Self {
705 match token_type {
706 x if x == TK_AND as YYCODETYPE => Self::And,
707 x if x == TK_OR as YYCODETYPE => Self::Or,
708 x if x == TK_LT as YYCODETYPE => Self::Less,
709 x if x == TK_GT as YYCODETYPE => Self::Greater,
710 x if x == TK_GE as YYCODETYPE => Self::GreaterEquals,
711 x if x == TK_LE as YYCODETYPE => Self::LessEquals,
712 x if x == TK_EQ as YYCODETYPE => Self::Equals,
713 x if x == TK_NE as YYCODETYPE => Self::NotEquals,
714 x if x == TK_BITAND as YYCODETYPE => Self::BitwiseAnd,
715 x if x == TK_BITOR as YYCODETYPE => Self::BitwiseOr,
716 x if x == TK_BITNOT as YYCODETYPE => Self::BitwiseNot,
717 x if x == TK_LSHIFT as YYCODETYPE => Self::LeftShift,
718 x if x == TK_RSHIFT as YYCODETYPE => Self::RightShift,
719 x if x == TK_PLUS as YYCODETYPE => Self::Add,
720 x if x == TK_MINUS as YYCODETYPE => Self::Subtract,
721 x if x == TK_STAR as YYCODETYPE => Self::Multiply,
722 x if x == TK_SLASH as YYCODETYPE => Self::Divide,
723 x if x == TK_REM as YYCODETYPE => Self::Modulus,
724 x if x == TK_CONCAT as YYCODETYPE => Self::Concat,
725 x if x == TK_IS as YYCODETYPE => Self::Is,
726 x if x == TK_NOT as YYCODETYPE => Self::IsNot,
727 _ => unreachable!(),
728 }
729 }
730}
731
732impl Operator {
733 pub fn is_commutative(&self) -> bool {
735 matches!(
736 self,
737 Operator::Add
738 | Operator::Multiply
739 | Operator::BitwiseAnd
740 | Operator::BitwiseOr
741 | Operator::Equals
742 | Operator::NotEquals
743 )
744 }
745
746 pub fn is_comparison(&self) -> bool {
748 matches!(
749 self,
750 Self::Equals
751 | Self::NotEquals
752 | Self::Less
753 | Self::LessEquals
754 | Self::Greater
755 | Self::GreaterEquals
756 | Self::Is
757 | Self::IsNot
758 )
759 }
760}
761
762#[derive(Copy, Clone, Debug, PartialEq, Eq)]
764#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
765pub enum UnaryOperator {
766 BitwiseNot,
768 Negative,
770 Not,
772 Positive,
774}
775
776impl From<YYCODETYPE> for UnaryOperator {
777 fn from(token_type: YYCODETYPE) -> Self {
778 match token_type {
779 x if x == TK_BITNOT as YYCODETYPE => Self::BitwiseNot,
780 x if x == TK_MINUS as YYCODETYPE => Self::Negative,
781 x if x == TK_NOT as YYCODETYPE => Self::Not,
782 x if x == TK_PLUS as YYCODETYPE => Self::Positive,
783 _ => unreachable!(),
784 }
785 }
786}
787
788#[derive(Clone, Debug, PartialEq, Eq)]
792#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
793pub struct Select {
794 pub with: Option<With>,
796 pub body: SelectBody,
798 pub order_by: Option<Vec<SortedColumn>>, pub limit: Option<Box<Limit>>,
802}
803
804#[derive(Clone, Debug, PartialEq, Eq)]
806#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
807pub struct SelectBody {
808 pub select: Box<OneSelect>,
810 pub compounds: Option<Vec<CompoundSelect>>,
812}
813
814impl SelectBody {
815 pub(crate) fn push(&mut self, cs: CompoundSelect) -> Result<(), ParserError> {
816 use crate::ast::check::ColumnCount;
817 if let ColumnCount::Fixed(n) = self.select.column_count() {
818 if let ColumnCount::Fixed(m) = cs.select.column_count() {
819 if n != m {
820 return Err(custom_err!(
821 "SELECTs to the left and right of {} do not have the same number of result columns",
822 cs.operator
823 ));
824 }
825 }
826 }
827 if let Some(ref mut v) = self.compounds {
828 v.push(cs);
829 } else {
830 self.compounds = Some(vec![cs]);
831 }
832 Ok(())
833 }
834}
835
836#[derive(Clone, Debug, PartialEq, Eq)]
838#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
839pub struct CompoundSelect {
840 pub operator: CompoundOperator,
842 pub select: Box<OneSelect>,
844}
845
846#[derive(Copy, Clone, Debug, PartialEq, Eq)]
849#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
850pub enum CompoundOperator {
851 Union,
853 UnionAll,
855 Except,
857 Intersect,
859}
860
861#[derive(Clone, Debug, PartialEq, Eq)]
864#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
865pub enum OneSelect {
866 Select(Box<SelectInner>),
868 Values(Vec<Vec<Expr>>),
870}
871
872#[derive(Clone, Debug, PartialEq, Eq)]
873#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
874pub struct SelectInner {
876 pub distinctness: Option<Distinctness>,
878 pub columns: Vec<ResultColumn>,
880 pub from: Option<FromClause>,
882 pub where_clause: Option<Expr>,
884 pub group_by: Option<GroupBy>,
886 pub window_clause: Option<Vec<WindowDef>>,
888}
889
890#[derive(Clone, Debug, PartialEq, Eq)]
893#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
894pub struct FromClause {
895 pub select: Option<Box<SelectTable>>, pub joins: Option<Vec<JoinedSelectTable>>,
899 op: Option<JoinOperator>, }
901impl FromClause {
902 pub(crate) fn empty() -> Self {
903 Self {
904 select: None,
905 joins: None,
906 op: None,
907 }
908 }
909
910 pub(crate) fn push(
911 &mut self,
912 table: SelectTable,
913 jc: Option<JoinConstraint>,
914 ) -> Result<(), ParserError> {
915 let op = self.op.take();
916 if let Some(op) = op {
917 let jst = JoinedSelectTable {
918 operator: op,
919 table,
920 constraint: jc,
921 };
922 if jst.operator.is_natural() && jst.constraint.is_some() {
923 return Err(custom_err!(
924 "a NATURAL join may not have an ON or USING clause"
925 ));
926 }
927 if let Some(ref mut joins) = self.joins {
928 joins.push(jst);
929 } else {
930 self.joins = Some(vec![jst]);
931 }
932 } else {
933 if jc.is_some() {
934 return Err(custom_err!("a JOIN clause is required before ON"));
935 }
936 debug_assert!(self.select.is_none());
937 debug_assert!(self.joins.is_none());
938 self.select = Some(Box::new(table));
939 }
940 Ok(())
941 }
942
943 pub(crate) fn push_op(&mut self, op: JoinOperator) {
944 self.op = Some(op);
945 }
946}
947
948#[derive(Copy, Clone, Debug, PartialEq, Eq)]
950#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
951pub enum Distinctness {
952 Distinct,
954 All,
956}
957
958#[derive(Clone, Debug, PartialEq, Eq)]
961#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
962pub enum ResultColumn {
963 Expr(Expr, Option<As>),
965 Star,
967 TableStar(Name),
969}
970
971#[derive(Clone, Debug, PartialEq, Eq)]
973#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
974pub enum As {
975 As(Name),
977 Elided(Name), }
980
981#[derive(Clone, Debug, PartialEq, Eq)]
984#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
985pub struct JoinedSelectTable {
986 pub operator: JoinOperator,
988 pub table: SelectTable,
990 pub constraint: Option<JoinConstraint>,
992}
993
994#[derive(Clone, Debug, PartialEq, Eq)]
997#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
998pub enum SelectTable {
999 Table(QualifiedName, Option<As>, Option<Indexed>),
1001 TableCall(QualifiedName, Option<Vec<Expr>>, Option<As>),
1003 Select(Box<Select>, Option<As>),
1005 Sub(FromClause, Option<As>),
1007}
1008
1009#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1012#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1013pub enum JoinOperator {
1014 Comma,
1016 TypedJoin(Option<JoinType>),
1018}
1019
1020impl JoinOperator {
1021 pub(crate) fn from(
1022 token: Token,
1023 n1: Option<Name>,
1024 n2: Option<Name>,
1025 ) -> Result<Self, ParserError> {
1026 Ok({
1027 let mut jt = JoinType::try_from(token.1)?;
1028 for n in [&n1, &n2].into_iter().flatten() {
1029 jt |= JoinType::try_from(n.0.as_ref())?;
1030 }
1031 if (jt & (JoinType::INNER | JoinType::OUTER)) == (JoinType::INNER | JoinType::OUTER)
1032 || (jt & (JoinType::OUTER | JoinType::LEFT | JoinType::RIGHT)) == JoinType::OUTER
1033 {
1034 return Err(custom_err!(
1035 "unsupported JOIN type: {:?} {:?} {:?}",
1036 str::from_utf8(token.1),
1037 n1,
1038 n2
1039 ));
1040 }
1041 Self::TypedJoin(Some(jt))
1042 })
1043 }
1044 fn is_natural(&self) -> bool {
1045 match self {
1046 Self::TypedJoin(Some(jt)) => jt.contains(JoinType::NATURAL),
1047 _ => false,
1048 }
1049 }
1050}
1051
1052bitflags::bitflags! {
1054 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1056 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1057 pub struct JoinType: u8 {
1058 const INNER = 0x01;
1060 const CROSS = 0x02;
1062 const NATURAL = 0x04;
1064 const LEFT = 0x08;
1066 const RIGHT = 0x10;
1068 const OUTER = 0x20;
1070 }
1071}
1072
1073impl TryFrom<&[u8]> for JoinType {
1074 type Error = ParserError;
1075 fn try_from(s: &[u8]) -> Result<Self, ParserError> {
1076 if b"CROSS".eq_ignore_ascii_case(s) {
1077 Ok(Self::INNER | Self::CROSS)
1078 } else if b"FULL".eq_ignore_ascii_case(s) {
1079 Ok(Self::LEFT | Self::RIGHT | Self::OUTER)
1080 } else if b"INNER".eq_ignore_ascii_case(s) {
1081 Ok(Self::INNER)
1082 } else if b"LEFT".eq_ignore_ascii_case(s) {
1083 Ok(Self::LEFT | Self::OUTER)
1084 } else if b"NATURAL".eq_ignore_ascii_case(s) {
1085 Ok(Self::NATURAL)
1086 } else if b"RIGHT".eq_ignore_ascii_case(s) {
1087 Ok(Self::RIGHT | Self::OUTER)
1088 } else if b"OUTER".eq_ignore_ascii_case(s) {
1089 Ok(Self::OUTER)
1090 } else {
1091 Err(custom_err!(
1092 "unsupported JOIN type: {:?}",
1093 str::from_utf8(s)
1094 ))
1095 }
1096 }
1097}
1098
1099#[derive(Clone, Debug, PartialEq, Eq)]
1101#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1102
1103pub enum JoinConstraint {
1104 On(Expr),
1106 Using(DistinctNames),
1108}
1109
1110#[derive(Clone, Debug, PartialEq, Eq)]
1112#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1113pub struct GroupBy {
1114 pub exprs: Vec<Expr>,
1116 pub having: Option<Box<Expr>>, }
1119
1120#[derive(Clone, Debug, PartialEq, Eq)]
1122#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1123pub struct Id(pub String);
1124
1125impl Id {
1126 pub fn from_token(ty: YYCODETYPE, token: Token) -> Self {
1128 Self(from_token(ty, token))
1129 }
1130}
1131
1132#[derive(Clone, Debug, Eq)]
1136#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1137pub struct Name(pub String); impl Name {
1140 pub fn from_token(ty: YYCODETYPE, token: Token) -> Self {
1142 Self(from_token(ty, token))
1143 }
1144
1145 fn as_bytes(&self) -> QuotedIterator<'_> {
1146 if self.0.is_empty() {
1147 return QuotedIterator(self.0.bytes(), 0);
1148 }
1149 let bytes = self.0.as_bytes();
1150 let mut quote = bytes[0];
1151 if quote != b'"' && quote != b'`' && quote != b'\'' && quote != b'[' {
1152 return QuotedIterator(self.0.bytes(), 0);
1153 } else if quote == b'[' {
1154 quote = b']';
1155 }
1156 debug_assert!(bytes.len() > 1);
1157 debug_assert_eq!(quote, bytes[bytes.len() - 1]);
1158 let sub = &self.0.as_str()[1..bytes.len() - 1];
1159 if quote == b']' {
1160 return QuotedIterator(sub.bytes(), 0); }
1162 QuotedIterator(sub.bytes(), quote)
1163 }
1164}
1165
1166struct QuotedIterator<'s>(Bytes<'s>, u8);
1167impl Iterator for QuotedIterator<'_> {
1168 type Item = u8;
1169
1170 fn next(&mut self) -> Option<u8> {
1171 match self.0.next() {
1172 x @ Some(b) => {
1173 if b == self.1 && self.0.next() != Some(self.1) {
1174 panic!("Malformed string literal: {:?}", self.0);
1175 }
1176 x
1177 }
1178 x => x,
1179 }
1180 }
1181
1182 fn size_hint(&self) -> (usize, Option<usize>) {
1183 if self.1 == 0 {
1184 return self.0.size_hint();
1185 }
1186 (0, None)
1187 }
1188}
1189
1190fn eq_ignore_case_and_quote(mut it: QuotedIterator<'_>, mut other: QuotedIterator<'_>) -> bool {
1191 loop {
1192 match (it.next(), other.next()) {
1193 (Some(b1), Some(b2)) => {
1194 if !b1.eq_ignore_ascii_case(&b2) {
1195 return false;
1196 }
1197 }
1198 (None, None) => break,
1199 _ => return false,
1200 }
1201 }
1202 true
1203}
1204
1205impl std::hash::Hash for Name {
1207 fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
1208 self.as_bytes()
1209 .for_each(|b| hasher.write_u8(b.to_ascii_lowercase()));
1210 }
1211}
1212impl PartialEq for Name {
1214 fn eq(&self, other: &Self) -> bool {
1215 eq_ignore_case_and_quote(self.as_bytes(), other.as_bytes())
1216 }
1217}
1218impl PartialEq<str> for Name {
1220 fn eq(&self, other: &str) -> bool {
1221 eq_ignore_case_and_quote(self.as_bytes(), QuotedIterator(other.bytes(), 0u8))
1222 }
1223}
1224impl PartialEq<&str> for Name {
1226 fn eq(&self, other: &&str) -> bool {
1227 eq_ignore_case_and_quote(self.as_bytes(), QuotedIterator(other.bytes(), 0u8))
1228 }
1229}
1230
1231#[derive(Clone, Debug, PartialEq, Eq)]
1233#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1234pub struct QualifiedName {
1235 pub db_name: Option<Name>,
1237 pub name: Name,
1239 pub alias: Option<Name>, }
1242
1243impl QualifiedName {
1244 pub fn single(name: Name) -> Self {
1246 Self {
1247 db_name: None,
1248 name,
1249 alias: None,
1250 }
1251 }
1252 pub fn fullname(db_name: Name, name: Name) -> Self {
1254 Self {
1255 db_name: Some(db_name),
1256 name,
1257 alias: None,
1258 }
1259 }
1260 pub fn xfullname(db_name: Name, name: Name, alias: Name) -> Self {
1262 Self {
1263 db_name: Some(db_name),
1264 name,
1265 alias: Some(alias),
1266 }
1267 }
1268 pub fn alias(name: Name, alias: Name) -> Self {
1270 Self {
1271 db_name: None,
1272 name,
1273 alias: Some(alias),
1274 }
1275 }
1276}
1277
1278#[derive(Clone, Debug, PartialEq, Eq)]
1280#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1281pub struct DistinctNames(IndexSet<Name>);
1282
1283impl DistinctNames {
1284 pub fn new(name: Name) -> Self {
1286 let mut dn = Self(IndexSet::new());
1287 dn.0.insert(name);
1288 dn
1289 }
1290 pub fn single(name: Name) -> Self {
1292 let mut dn = Self(IndexSet::with_capacity(1));
1293 dn.0.insert(name);
1294 dn
1295 }
1296 pub fn insert(&mut self, name: Name) -> Result<(), ParserError> {
1298 if self.0.contains(&name) {
1299 return Err(custom_err!("column \"{}\" specified more than once", name));
1300 }
1301 self.0.insert(name);
1302 Ok(())
1303 }
1304}
1305impl Deref for DistinctNames {
1306 type Target = IndexSet<Name>;
1307
1308 fn deref(&self) -> &IndexSet<Name> {
1309 &self.0
1310 }
1311}
1312
1313#[derive(Clone, Debug, PartialEq, Eq)]
1316#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1317pub enum AlterTableBody {
1318 RenameTo(Name),
1320 AddColumn(ColumnDefinition), RenameColumn {
1324 old: Name,
1326 new: Name,
1328 },
1329 DropColumn(Name), }
1332
1333#[derive(Clone, Debug, PartialEq, Eq)]
1337#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1338pub enum CreateTableBody {
1339 ColumnsAndConstraints {
1341 columns: IndexMap<Name, ColumnDefinition>,
1343 constraints: Option<Vec<NamedTableConstraint>>,
1345 options: TableOptions,
1347 },
1348 AsSelect(Box<Select>),
1350}
1351
1352impl CreateTableBody {
1353 pub fn columns_and_constraints(
1355 columns: IndexMap<Name, ColumnDefinition>,
1356 constraints: Option<Vec<NamedTableConstraint>>,
1357 options: TableOptions,
1358 ) -> Result<Self, ParserError> {
1359 Ok(Self::ColumnsAndConstraints {
1360 columns,
1361 constraints,
1362 options,
1363 })
1364 }
1365}
1366
1367#[derive(Clone, Debug, PartialEq, Eq)]
1370#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1371pub struct ColumnDefinition {
1372 pub col_name: Name,
1374 pub col_type: Option<Type>,
1376 pub constraints: Vec<NamedColumnConstraint>,
1378}
1379
1380impl ColumnDefinition {
1381 pub fn add_column(columns: &mut IndexMap<Name, Self>, mut cd: Self) -> Result<(), ParserError> {
1383 let col_name = &cd.col_name;
1384 if columns.contains_key(col_name) {
1385 return Err(custom_err!("duplicate column name: {}", col_name));
1387 }
1388 if let Some(ref mut col_type) = cd.col_type {
1390 let mut split = col_type.name.split_ascii_whitespace();
1391 let truncate = if split
1392 .next_back()
1393 .is_some_and(|s| s.eq_ignore_ascii_case("ALWAYS"))
1394 && split
1395 .next_back()
1396 .is_some_and(|s| s.eq_ignore_ascii_case("GENERATED"))
1397 {
1398 let mut generated = false;
1399 for constraint in &cd.constraints {
1400 if let ColumnConstraint::Generated { .. } = constraint.constraint {
1401 generated = true;
1402 break;
1403 }
1404 }
1405 generated
1406 } else {
1407 false
1408 };
1409 if truncate {
1410 let new_type: Vec<&str> = split.collect();
1412 col_type.name = new_type.join(" ");
1413 }
1414 }
1415 for constraint in &cd.constraints {
1416 if let ColumnConstraint::ForeignKey {
1417 clause:
1418 ForeignKeyClause {
1419 tbl_name, columns, ..
1420 },
1421 ..
1422 } = &constraint.constraint
1423 {
1424 if columns.as_ref().map_or(0, Vec::len) > 1 {
1426 return Err(custom_err!(
1427 "foreign key on {} should reference only one column of table {}",
1428 col_name,
1429 tbl_name
1430 ));
1431 }
1432 }
1433 }
1434 columns.insert(col_name.clone(), cd);
1435 Ok(())
1436 }
1437}
1438
1439#[derive(Clone, Debug, PartialEq, Eq)]
1442#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1443pub struct NamedColumnConstraint {
1444 pub name: Option<Name>,
1446 pub constraint: ColumnConstraint,
1448}
1449
1450#[derive(Clone, Debug, PartialEq, Eq)]
1453#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1454pub enum ColumnConstraint {
1455 PrimaryKey {
1457 order: Option<SortOrder>,
1459 conflict_clause: Option<ResolveType>,
1461 auto_increment: bool,
1463 },
1464 NotNull {
1466 nullable: bool,
1468 conflict_clause: Option<ResolveType>,
1470 },
1471 Unique(Option<ResolveType>),
1473 Check(Expr),
1475 Default(Expr),
1477 Defer(DeferSubclause), Collate {
1481 collation_name: Name, },
1484 ForeignKey {
1486 clause: ForeignKeyClause,
1488 deref_clause: Option<DeferSubclause>,
1490 },
1491 Generated {
1493 expr: Expr,
1495 typ: Option<Id>,
1497 },
1498}
1499
1500#[derive(Clone, Debug, PartialEq, Eq)]
1503#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1504pub struct NamedTableConstraint {
1505 pub name: Option<Name>,
1507 pub constraint: TableConstraint,
1509}
1510
1511#[derive(Clone, Debug, PartialEq, Eq)]
1514#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1515pub enum TableConstraint {
1516 PrimaryKey {
1518 columns: Vec<SortedColumn>,
1520 auto_increment: bool,
1522 conflict_clause: Option<ResolveType>,
1524 },
1525 Unique {
1527 columns: Vec<SortedColumn>,
1529 conflict_clause: Option<ResolveType>,
1531 },
1532 Check(Expr),
1534 ForeignKey {
1536 columns: Vec<IndexedColumn>,
1538 clause: ForeignKeyClause,
1540 deref_clause: Option<DeferSubclause>,
1542 },
1543}
1544
1545bitflags::bitflags! {
1546 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1548 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1549 pub struct TableOptions: u8 {
1550 const NONE = 0;
1552 const WITHOUT_ROWID = 1;
1554 const STRICT = 2;
1556 }
1557}
1558
1559#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1561#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1562pub enum SortOrder {
1563 Asc,
1565 Desc,
1567}
1568
1569#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1571#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1572pub enum NullsOrder {
1573 First,
1575 Last,
1577}
1578
1579#[derive(Clone, Debug, PartialEq, Eq)]
1582#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1583pub struct ForeignKeyClause {
1584 pub tbl_name: Name,
1586 pub columns: Option<Vec<IndexedColumn>>,
1588 pub args: Vec<RefArg>,
1590}
1591
1592#[derive(Clone, Debug, PartialEq, Eq)]
1594#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1595pub enum RefArg {
1596 OnDelete(RefAct),
1598 OnInsert(RefAct),
1600 OnUpdate(RefAct),
1602 Match(Name),
1604}
1605
1606#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1608#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1609pub enum RefAct {
1610 SetNull,
1612 SetDefault,
1614 Cascade,
1616 Restrict,
1618 NoAction,
1620}
1621
1622#[derive(Clone, Debug, PartialEq, Eq)]
1624#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1625pub struct DeferSubclause {
1626 pub deferrable: bool,
1628 pub init_deferred: Option<InitDeferredPred>,
1630}
1631
1632#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1634#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1635pub enum InitDeferredPred {
1636 InitiallyDeferred,
1638 InitiallyImmediate, }
1641
1642#[derive(Clone, Debug, PartialEq, Eq)]
1645#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1646pub struct IndexedColumn {
1647 pub col_name: Name,
1649 pub collation_name: Option<Name>, pub order: Option<SortOrder>,
1653}
1654
1655#[derive(Clone, Debug, PartialEq, Eq)]
1657#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1658pub enum Indexed {
1659 IndexedBy(Name),
1661 NotIndexed,
1663}
1664
1665#[derive(Clone, Debug, PartialEq, Eq)]
1667#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1668pub struct SortedColumn {
1669 pub expr: Expr,
1671 pub order: Option<SortOrder>,
1673 pub nulls: Option<NullsOrder>,
1675}
1676
1677#[derive(Clone, Debug, PartialEq, Eq)]
1679#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1680pub struct Limit {
1681 pub expr: Expr,
1683 pub offset: Option<Expr>, }
1686
1687#[derive(Clone, Debug, PartialEq, Eq)]
1691#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1692pub enum InsertBody {
1693 Select(Box<Select>, Option<Upsert>),
1695 DefaultValues,
1697}
1698
1699#[derive(Clone, Debug, PartialEq, Eq)]
1701#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1702pub struct Set {
1703 pub col_names: DistinctNames,
1705 pub expr: Expr,
1707}
1708
1709#[derive(Clone, Debug, PartialEq, Eq)]
1712#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1713pub enum PragmaBody {
1714 Equals(PragmaValue),
1716 Call(PragmaValue),
1718}
1719pub type PragmaValue = Expr; #[derive(Clone, Debug, PartialEq, Eq, EnumIter, EnumString, strum::Display)]
1726#[strum(serialize_all = "snake_case")]
1727#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1728pub enum PragmaName {
1729 AutoVacuum,
1731 CacheSize,
1733 ForeignKeyList,
1735 IntegrityCheck,
1737 JournalMode,
1739 LegacyFileFormat,
1741 PageCount,
1743 PageSize,
1745 SchemaVersion,
1747 TableInfo,
1749 UserVersion,
1751 WalCheckpoint,
1753}
1754
1755#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1757#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1758pub enum TriggerTime {
1759 Before, After,
1763 InsteadOf,
1765}
1766
1767#[derive(Clone, Debug, PartialEq, Eq)]
1769#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1770pub enum TriggerEvent {
1771 Delete,
1773 Insert,
1775 Update,
1777 UpdateOf(DistinctNames),
1779}
1780
1781#[derive(Clone, Debug, PartialEq, Eq)]
1785#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1786pub enum TriggerCmd {
1787 Update(Box<TriggerCmdUpdate>),
1789 Insert(Box<TriggerCmdInsert>),
1791 Delete(Box<TriggerCmdDelete>),
1793 Select(Box<Select>),
1795}
1796
1797#[derive(Clone, Debug, PartialEq, Eq)]
1799#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1800pub struct TriggerCmdUpdate {
1801 pub or_conflict: Option<ResolveType>,
1803 pub tbl_name: Name,
1805 pub sets: Vec<Set>,
1807 pub from: Option<FromClause>,
1809 pub where_clause: Option<Expr>,
1811}
1812
1813#[derive(Clone, Debug, PartialEq, Eq)]
1815#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1816pub struct TriggerCmdInsert {
1817 pub or_conflict: Option<ResolveType>,
1819 pub tbl_name: Name,
1821 pub col_names: Option<DistinctNames>,
1823 pub select: Box<Select>,
1825 pub upsert: Option<Upsert>,
1827 pub returning: Option<Vec<ResultColumn>>,
1829}
1830
1831#[derive(Clone, Debug, PartialEq, Eq)]
1833#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1834pub struct TriggerCmdDelete {
1835 pub tbl_name: Name,
1837 pub where_clause: Option<Expr>,
1839}
1840
1841#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1843#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1844pub enum ResolveType {
1845 Rollback,
1847 Abort, Fail,
1851 Ignore,
1853 Replace,
1855}
1856impl ResolveType {
1857 pub fn bit_value(&self) -> usize {
1859 match self {
1860 ResolveType::Rollback => 1,
1861 ResolveType::Abort => 2,
1862 ResolveType::Fail => 3,
1863 ResolveType::Ignore => 4,
1864 ResolveType::Replace => 5,
1865 }
1866 }
1867}
1868
1869#[derive(Clone, Debug, PartialEq, Eq)]
1873#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1874pub struct With {
1875 pub recursive: bool,
1877 pub ctes: Vec<CommonTableExpr>,
1879}
1880
1881#[derive(Clone, Debug, PartialEq, Eq)]
1883#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1884pub enum Materialized {
1885 Any,
1887 Yes,
1889 No,
1891}
1892
1893#[derive(Clone, Debug, PartialEq, Eq)]
1896#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1897pub struct CommonTableExpr {
1898 pub tbl_name: Name,
1900 pub columns: Option<Vec<IndexedColumn>>, pub materialized: Materialized,
1904 pub select: Box<Select>,
1906}
1907
1908impl CommonTableExpr {
1909 pub fn add_cte(ctes: &mut Vec<Self>, cte: Self) -> Result<(), ParserError> {
1911 if ctes.iter().any(|c| c.tbl_name == cte.tbl_name) {
1912 return Err(custom_err!("duplicate WITH table name: {}", cte.tbl_name));
1913 }
1914 ctes.push(cte);
1915 Ok(())
1916 }
1917}
1918
1919#[derive(Clone, Debug, PartialEq, Eq)]
1922#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1923pub struct Type {
1924 pub name: String, pub size: Option<TypeSize>,
1928}
1929
1930#[derive(Clone, Debug, PartialEq, Eq)]
1933#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1934pub enum TypeSize {
1935 MaxSize(Box<Expr>),
1937 TypeSize(Box<Expr>, Box<Expr>),
1939}
1940
1941#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1943#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1944pub enum TransactionType {
1945 Deferred, Immediate,
1949 Exclusive,
1951}
1952
1953#[derive(Clone, Debug, PartialEq, Eq)]
1957#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1958pub struct Upsert {
1959 pub index: Option<Box<UpsertIndex>>,
1961 pub do_clause: Box<UpsertDo>,
1963 pub next: Option<Box<Upsert>>,
1965}
1966
1967#[derive(Clone, Debug, PartialEq, Eq)]
1969#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1970pub struct UpsertIndex {
1971 pub targets: Vec<SortedColumn>,
1973 pub where_clause: Option<Expr>,
1975}
1976
1977#[derive(Clone, Debug, PartialEq, Eq)]
1979#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1980pub enum UpsertDo {
1981 Set {
1983 sets: Vec<Set>,
1985 where_clause: Option<Expr>,
1987 },
1988 Nothing,
1990}
1991
1992#[derive(Clone, Debug, PartialEq, Eq)]
1994#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1995pub struct FunctionTail {
1996 pub filter_clause: Option<Box<Expr>>,
1998 pub over_clause: Option<Box<Over>>,
2000}
2001
2002#[derive(Clone, Debug, PartialEq, Eq)]
2005#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2006pub enum Over {
2007 Window(Window),
2009 Name(Name),
2011}
2012
2013#[derive(Clone, Debug, PartialEq, Eq)]
2015#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2016pub struct WindowDef {
2017 pub name: Name,
2019 pub window: Window,
2021}
2022
2023#[derive(Clone, Debug, PartialEq, Eq)]
2026#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2027pub struct Window {
2028 pub base: Option<Name>,
2030 pub partition_by: Option<Vec<Expr>>,
2032 pub order_by: Option<Vec<SortedColumn>>,
2034 pub frame_clause: Option<FrameClause>,
2036}
2037
2038#[derive(Clone, Debug, PartialEq, Eq)]
2041#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2042pub struct FrameClause {
2043 pub mode: FrameMode,
2045 pub start: FrameBound,
2047 pub end: Option<FrameBound>,
2049 pub exclude: Option<FrameExclude>,
2051}
2052
2053#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2055#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2056pub enum FrameMode {
2057 Groups,
2059 Range,
2061 Rows,
2063}
2064
2065#[derive(Clone, Debug, PartialEq, Eq)]
2067#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2068pub enum FrameBound {
2069 CurrentRow,
2071 Following(Box<Expr>),
2073 Preceding(Box<Expr>),
2075 UnboundedFollowing,
2077 UnboundedPreceding,
2079}
2080
2081#[derive(Clone, Debug, PartialEq, Eq)]
2083#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2084pub enum FrameExclude {
2085 NoOthers,
2087 CurrentRow,
2089 Group,
2091 Ties,
2093}
2094
2095#[cfg(test)]
2096mod test {
2097 use super::{Name, PragmaName};
2098 use strum::IntoEnumIterator;
2099
2100 #[test]
2101 fn test_dequote() {
2102 assert_eq!(name("x"), "x");
2103 assert_eq!(name("`x`"), "x");
2104 assert_eq!(name("`x``y`"), "x`y");
2105 assert_eq!(name(r#""x""#), "x");
2106 assert_eq!(name(r#""x""y""#), "x\"y");
2107 assert_eq!(name("[x]"), "x");
2108 }
2109
2110 #[test]
2111 fn pragma_list_sorted() {
2114 let pragma_strings: Vec<String> = PragmaName::iter().map(|x| x.to_string()).collect();
2115 let mut pragma_strings_sorted = pragma_strings.clone();
2116 pragma_strings_sorted.sort();
2117 assert_eq!(pragma_strings, pragma_strings_sorted);
2118 }
2119
2120 fn name(s: &'static str) -> Name {
2121 Name(s.to_owned())
2122 }
2123}