spacetimedb_sql_parser/ast/
mod.rs

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
use std::fmt::{Display, Formatter};

use sqlparser::ast::Ident;

pub mod sql;
pub mod sub;

/// The FROM clause is either a relvar or a JOIN
#[derive(Debug)]
pub enum SqlFrom {
    Expr(SqlIdent, SqlIdent),
    Join(SqlIdent, SqlIdent, Vec<SqlJoin>),
}

impl SqlFrom {
    pub fn has_unqualified_vars(&self) -> bool {
        match self {
            Self::Join(_, _, joins) => joins.iter().any(|join| join.has_unqualified_vars()),
            _ => false,
        }
    }
}

/// An inner join in a FROM clause
#[derive(Debug)]
pub struct SqlJoin {
    pub var: SqlIdent,
    pub alias: SqlIdent,
    pub on: Option<SqlExpr>,
}

impl SqlJoin {
    pub fn has_unqualified_vars(&self) -> bool {
        self.on.as_ref().is_some_and(|expr| expr.has_unqualified_vars())
    }
}

/// A projection expression in a SELECT clause
#[derive(Debug)]
pub struct ProjectElem(pub ProjectExpr, pub SqlIdent);

impl ProjectElem {
    pub fn qualify_vars(self, with: SqlIdent) -> Self {
        let Self(expr, alias) = self;
        Self(expr.qualify_vars(with), alias)
    }
}

/// A column projection in a SELECT clause
#[derive(Debug)]
pub enum ProjectExpr {
    Var(SqlIdent),
    Field(SqlIdent, SqlIdent),
}

impl From<ProjectExpr> for SqlExpr {
    fn from(value: ProjectExpr) -> Self {
        match value {
            ProjectExpr::Var(name) => Self::Var(name),
            ProjectExpr::Field(table, field) => Self::Field(table, field),
        }
    }
}

impl ProjectExpr {
    pub fn qualify_vars(self, with: SqlIdent) -> Self {
        match self {
            Self::Var(name) => Self::Field(with, name),
            Self::Field(_, _) => self,
        }
    }
}

/// A SQL SELECT clause
#[derive(Debug)]
pub enum Project {
    /// SELECT *
    /// SELECT a.*
    Star(Option<SqlIdent>),
    /// SELECT a, b
    Exprs(Vec<ProjectElem>),
}

impl Project {
    pub fn qualify_vars(self, with: SqlIdent) -> Self {
        match self {
            Self::Star(..) => self,
            Self::Exprs(elems) => Self::Exprs(elems.into_iter().map(|elem| elem.qualify_vars(with.clone())).collect()),
        }
    }

    pub fn has_unqualified_vars(&self) -> bool {
        match self {
            Self::Exprs(exprs) => exprs
                .iter()
                .any(|ProjectElem(expr, _)| matches!(expr, ProjectExpr::Var(_))),
            _ => false,
        }
    }
}

/// A scalar SQL expression
#[derive(Debug)]
pub enum SqlExpr {
    /// A constant expression
    Lit(SqlLiteral),
    /// Unqualified column ref
    Var(SqlIdent),
    /// Qualified column ref
    Field(SqlIdent, SqlIdent),
    /// A binary infix expression
    Bin(Box<SqlExpr>, Box<SqlExpr>, BinOp),
    /// A binary logic expression
    Log(Box<SqlExpr>, Box<SqlExpr>, LogOp),
}

impl SqlExpr {
    pub fn qualify_vars(self, with: SqlIdent) -> Self {
        match self {
            Self::Var(name) => Self::Field(with, name),
            Self::Lit(..) | Self::Field(..) => self,
            Self::Bin(a, b, op) => Self::Bin(
                Box::new(a.qualify_vars(with.clone())),
                Box::new(b.qualify_vars(with)),
                op,
            ),
            Self::Log(a, b, op) => Self::Log(
                Box::new(a.qualify_vars(with.clone())),
                Box::new(b.qualify_vars(with)),
                op,
            ),
        }
    }

    pub fn has_unqualified_vars(&self) -> bool {
        match self {
            Self::Var(_) => true,
            Self::Bin(a, b, _) | Self::Log(a, b, _) => a.has_unqualified_vars() || b.has_unqualified_vars(),
            _ => false,
        }
    }
}

/// A SQL identifier or named reference.
/// Currently case sensitive.
#[derive(Debug, Clone)]
pub struct SqlIdent(pub Box<str>);

/// Case insensitivity should be implemented here if at all
impl From<Ident> for SqlIdent {
    fn from(Ident { value, .. }: Ident) -> Self {
        SqlIdent(value.into_boxed_str())
    }
}

/// A SQL constant expression
#[derive(Debug)]
pub enum SqlLiteral {
    /// A boolean constant
    Bool(bool),
    /// A hex value like 0xFF or x'FF'
    Hex(Box<str>),
    /// An integer or float value
    Num(Box<str>),
    /// A string value
    Str(Box<str>),
}

/// Binary infix operators
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Eq,
    Ne,
    Lt,
    Gt,
    Lte,
    Gte,
}

impl Display for BinOp {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Eq => write!(f, "="),
            Self::Ne => write!(f, "<>"),
            Self::Lt => write!(f, "<"),
            Self::Gt => write!(f, ">"),
            Self::Lte => write!(f, "<="),
            Self::Gte => write!(f, ">="),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogOp {
    And,
    Or,
}

impl Display for LogOp {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::And => write!(f, "AND"),
            Self::Or => write!(f, "OR"),
        }
    }
}