Skip to main content

powdb_query/
token.rs

1#[derive(Debug, Clone, PartialEq)]
2pub enum Token {
3    // Identifiers and literals
4    Ident(String),     // User, name, email
5    DotIdent(String),  // .name, .age (field access)
6    IntLit(i64),       // 42
7    FloatLit(f64),     // 3.14
8    StringLit(String), // "hello"
9    BoolLit(bool),     // true, false
10    Param(String),     // $age, $name (query parameter)
11
12    // Keywords
13    Type,         // type
14    Filter,       // filter
15    Order,        // order
16    Limit,        // limit
17    Offset,       // offset
18    Insert,       // insert
19    Update,       // update
20    Delete,       // delete
21    Upsert,       // upsert
22    Returning,    // returning
23    Select,       // select (alias for projection)
24    Required,     // required
25    Default,      // default (column default value)
26    Auto,         // auto (auto-incrementing column)
27    Multi,        // multi
28    Link,         // link
29    Index,        // index
30    Unique,       // unique
31    On,           // on
32    Conflict,     // conflict
33    Asc,          // asc
34    Desc,         // desc
35    And,          // and
36    Or,           // or
37    Not,          // not
38    Exists,       // exists
39    Let,          // let
40    As,           // as
41    Match,        // match
42    Group,        // group
43    Join,         // join
44    Inner,        // inner
45    LeftKw,       // left  (keyword — avoids clashing with ast::JoinKind::LeftOuter naming)
46    RightKw,      // right
47    Outer,        // outer
48    Cross,        // cross
49    Transaction,  // transaction
50    Begin,        // begin
51    Commit,       // commit
52    Rollback,     // rollback
53    View,         // view
54    Materialized, // materialized
55    Refresh,      // refresh
56    Union,        // union
57    Having,       // having
58    Distinct,     // distinct
59    In,           // in
60    Between,      // between
61    Like,         // like
62    Count,        // count
63    Avg,          // avg
64    Sum,          // sum
65    Min,          // min
66    Max,          // max
67    Is,           // is
68    Null,         // null
69
70    // String functions
71    Upper,     // upper
72    Lower,     // lower
73    Length,    // length
74    Trim,      // trim
75    Substring, // substring
76    Concat,    // concat
77
78    // Math functions
79    Abs,   // abs
80    Round, // round
81    Ceil,  // ceil
82    Floor, // floor
83    Sqrt,  // sqrt
84    Pow,   // pow
85
86    // Date/time functions
87    Now,      // now
88    Extract,  // extract
89    DateAdd,  // date_add
90    DateDiff, // date_diff
91
92    // JSON functions
93    JsonType, // json_type
94
95    // Type conversion
96    Cast, // cast
97
98    // CASE WHEN
99    Case, // case
100    When, // when
101    Then, // then
102    Else, // else
103    End,  // end
104
105    // Window functions
106    Over,      // over
107    Partition, // partition
108    RowNumber, // row_number
109    Rank,      // rank
110    DenseRank, // dense_rank
111
112    // DDL
113    Alter,    // alter
114    Drop,     // drop
115    Add,      // add
116    Column,   // column
117    Explain,  // explain
118    Schema,   // schema   (introspection: list types / describe one)
119    Describe, // describe (introspection: describe one type)
120
121    // Operators
122    Eq,       // =
123    Neq,      // !=
124    Lt,       // <
125    Gt,       // >
126    Lte,      // <=
127    Gte,      // >=
128    Assign,   // :=
129    Arrow,    // ->
130    Pipe,     // |
131    Coalesce, // ??
132    Plus,     // +
133    Minus,    // -
134    Star,     // *
135    Slash,    // /
136
137    // Delimiters
138    LBrace, // {
139    RBrace, // }
140    LParen, // (
141    RParen, // )
142    Comma,  // ,
143    Colon,  // :
144    Dot,    // .
145
146    // Special
147    Eof,
148}
149
150impl Token {
151    /// Human-readable name for error messages. Avoids exposing raw Rust Debug
152    /// format like `IntLit(42)` to end users.
153    pub fn display_name(&self) -> String {
154        match self {
155            // Literals
156            Token::Ident(s) => format!("identifier '{s}'"),
157            Token::DotIdent(s) => format!("field '.{s}'"),
158            Token::IntLit(v) => format!("number {v}"),
159            Token::FloatLit(v) => format!("decimal number {v}"),
160            Token::StringLit(s) => {
161                let preview = if s.len() > 20 {
162                    let end = s.floor_char_boundary(20);
163                    format!("{}...", &s[..end])
164                } else {
165                    s.clone()
166                };
167                format!("string \"{preview}\"")
168            }
169            Token::BoolLit(v) => format!("{v}"),
170            Token::Param(s) => format!("parameter '${s}'"),
171
172            // Keywords
173            Token::Type => "'type'".into(),
174            Token::Filter => "'filter'".into(),
175            Token::Order => "'order'".into(),
176            Token::Limit => "'limit'".into(),
177            Token::Offset => "'offset'".into(),
178            Token::Insert => "'insert'".into(),
179            Token::Update => "'update'".into(),
180            Token::Delete => "'delete'".into(),
181            Token::Upsert => "'upsert'".into(),
182            Token::Returning => "'returning'".into(),
183            Token::Select => "'select'".into(),
184            Token::Required => "'required'".into(),
185            Token::Default => "'default'".into(),
186            Token::Auto => "'auto'".into(),
187            Token::Multi => "'multi'".into(),
188            Token::Link => "'link'".into(),
189            Token::Index => "'index'".into(),
190            Token::Unique => "'unique'".into(),
191            Token::On => "'on'".into(),
192            Token::Conflict => "'conflict'".into(),
193            Token::Asc => "'asc'".into(),
194            Token::Desc => "'desc'".into(),
195            Token::And => "'and'".into(),
196            Token::Or => "'or'".into(),
197            Token::Not => "'not'".into(),
198            Token::Exists => "'exists'".into(),
199            Token::Let => "'let'".into(),
200            Token::As => "'as'".into(),
201            Token::Match => "'match'".into(),
202            Token::Group => "'group'".into(),
203            Token::Join => "'join'".into(),
204            Token::Inner => "'inner'".into(),
205            Token::LeftKw => "'left'".into(),
206            Token::RightKw => "'right'".into(),
207            Token::Outer => "'outer'".into(),
208            Token::Cross => "'cross'".into(),
209            Token::Transaction => "'transaction'".into(),
210            Token::Begin => "'begin'".into(),
211            Token::Commit => "'commit'".into(),
212            Token::Rollback => "'rollback'".into(),
213            Token::View => "'view'".into(),
214            Token::Materialized => "'materialized'".into(),
215            Token::Refresh => "'refresh'".into(),
216            Token::Union => "'union'".into(),
217            Token::Having => "'having'".into(),
218            Token::Distinct => "'distinct'".into(),
219            Token::In => "'in'".into(),
220            Token::Between => "'between'".into(),
221            Token::Like => "'like'".into(),
222            Token::Count => "'count'".into(),
223            Token::Avg => "'avg'".into(),
224            Token::Sum => "'sum'".into(),
225            Token::Min => "'min'".into(),
226            Token::Max => "'max'".into(),
227            Token::Is => "'is'".into(),
228            Token::Null => "'null'".into(),
229
230            // Functions
231            Token::Upper => "'upper'".into(),
232            Token::Lower => "'lower'".into(),
233            Token::Length => "'length'".into(),
234            Token::Trim => "'trim'".into(),
235            Token::Substring => "'substring'".into(),
236            Token::Concat => "'concat'".into(),
237            Token::Abs => "'abs'".into(),
238            Token::Round => "'round'".into(),
239            Token::Ceil => "'ceil'".into(),
240            Token::Floor => "'floor'".into(),
241            Token::Sqrt => "'sqrt'".into(),
242            Token::Pow => "'pow'".into(),
243            Token::Now => "'now'".into(),
244            Token::Extract => "'extract'".into(),
245            Token::DateAdd => "'date_add'".into(),
246            Token::DateDiff => "'date_diff'".into(),
247            Token::JsonType => "'json_type'".into(),
248            Token::Cast => "'cast'".into(),
249            Token::Case => "'case'".into(),
250            Token::When => "'when'".into(),
251            Token::Then => "'then'".into(),
252            Token::Else => "'else'".into(),
253            Token::End => "'end'".into(),
254
255            // Window
256            Token::Over => "'over'".into(),
257            Token::Partition => "'partition'".into(),
258            Token::RowNumber => "'row_number'".into(),
259            Token::Rank => "'rank'".into(),
260            Token::DenseRank => "'dense_rank'".into(),
261
262            // DDL
263            Token::Alter => "'alter'".into(),
264            Token::Drop => "'drop'".into(),
265            Token::Add => "'add'".into(),
266            Token::Column => "'column'".into(),
267            Token::Explain => "'explain'".into(),
268            Token::Schema => "'schema'".into(),
269            Token::Describe => "'describe'".into(),
270
271            // Operators
272            Token::Eq => "'='".into(),
273            Token::Neq => "'!='".into(),
274            Token::Lt => "'<'".into(),
275            Token::Gt => "'>'".into(),
276            Token::Lte => "'<='".into(),
277            Token::Gte => "'>='".into(),
278            Token::Assign => "':='".into(),
279            Token::Arrow => "'->'".into(),
280            Token::Pipe => "'|'".into(),
281            Token::Coalesce => "'??'".into(),
282            Token::Plus => "'+'".into(),
283            Token::Minus => "'-'".into(),
284            Token::Star => "'*'".into(),
285            Token::Slash => "'/'".into(),
286
287            // Delimiters
288            Token::LBrace => "'{'".into(),
289            Token::RBrace => "'}'".into(),
290            Token::LParen => "'('".into(),
291            Token::RParen => "')'".into(),
292            Token::Comma => "','".into(),
293            Token::Colon => "':'".into(),
294            Token::Dot => "'.'".into(),
295
296            Token::Eof => "end of input".into(),
297        }
298    }
299
300    /// The lowercase source spelling of this token when it is a reserved
301    /// keyword (or built-in literal word), or `None` for identifiers,
302    /// literals, operators, and delimiters. Inverts the lexer's word→token
303    /// table so the parser can tell a caller *which* reserved word collided
304    /// with an identifier position and how to quote it (`` `type` ``).
305    pub fn keyword_str(&self) -> Option<&'static str> {
306        Some(match self {
307            Token::Type => "type",
308            Token::Filter => "filter",
309            Token::Order => "order",
310            Token::Limit => "limit",
311            Token::Offset => "offset",
312            Token::Insert => "insert",
313            Token::Update => "update",
314            Token::Delete => "delete",
315            Token::Upsert => "upsert",
316            Token::Returning => "returning",
317            Token::Select => "select",
318            Token::Required => "required",
319            Token::Default => "default",
320            Token::Auto => "auto",
321            Token::Multi => "multi",
322            Token::Link => "link",
323            Token::Index => "index",
324            Token::Unique => "unique",
325            Token::On => "on",
326            Token::Conflict => "conflict",
327            Token::Asc => "asc",
328            Token::Desc => "desc",
329            Token::And => "and",
330            Token::Or => "or",
331            Token::Not => "not",
332            Token::Exists => "exists",
333            Token::Let => "let",
334            Token::As => "as",
335            Token::Match => "match",
336            Token::Group => "group",
337            Token::Join => "join",
338            Token::Inner => "inner",
339            Token::LeftKw => "left",
340            Token::RightKw => "right",
341            Token::Outer => "outer",
342            Token::Cross => "cross",
343            Token::Transaction => "transaction",
344            Token::Begin => "begin",
345            Token::Commit => "commit",
346            Token::Rollback => "rollback",
347            Token::View => "view",
348            Token::Materialized => "materialized",
349            Token::Refresh => "refresh",
350            Token::Union => "union",
351            Token::Having => "having",
352            Token::Distinct => "distinct",
353            Token::In => "in",
354            Token::Between => "between",
355            Token::Like => "like",
356            Token::Count => "count",
357            Token::Avg => "avg",
358            Token::Sum => "sum",
359            Token::Min => "min",
360            Token::Max => "max",
361            Token::Is => "is",
362            Token::Null => "null",
363            Token::Upper => "upper",
364            Token::Lower => "lower",
365            Token::Length => "length",
366            Token::Trim => "trim",
367            Token::Substring => "substring",
368            Token::Concat => "concat",
369            Token::Abs => "abs",
370            Token::Round => "round",
371            Token::Ceil => "ceil",
372            Token::Floor => "floor",
373            Token::Sqrt => "sqrt",
374            Token::Pow => "pow",
375            Token::Now => "now",
376            Token::Extract => "extract",
377            Token::DateAdd => "date_add",
378            Token::DateDiff => "date_diff",
379            Token::JsonType => "json_type",
380            Token::Cast => "cast",
381            Token::Case => "case",
382            Token::When => "when",
383            Token::Then => "then",
384            Token::Else => "else",
385            Token::End => "end",
386            Token::Over => "over",
387            Token::Partition => "partition",
388            Token::RowNumber => "row_number",
389            Token::Rank => "rank",
390            Token::DenseRank => "dense_rank",
391            Token::Alter => "alter",
392            Token::Drop => "drop",
393            Token::Add => "add",
394            Token::Column => "column",
395            Token::Explain => "explain",
396            Token::Schema => "schema",
397            Token::Describe => "describe",
398            _ => return None,
399        })
400    }
401}