Skip to main content

sqlparser/
tokenizer.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! SQL Tokenizer
19//!
20//! The tokenizer (a.k.a. lexer) converts a string into a sequence of tokens.
21//!
22//! The tokens then form the input for the parser, which outputs an Abstract Syntax Tree (AST).
23
24#[cfg(not(feature = "std"))]
25use alloc::{
26    borrow::ToOwned,
27    format,
28    string::{String, ToString},
29    vec,
30    vec::Vec,
31};
32use core::num::NonZeroU8;
33use core::str::Chars;
34use core::{cmp, fmt};
35use core::{iter::Peekable, str};
36
37#[cfg(feature = "serde")]
38use serde::{Deserialize, Serialize};
39
40#[cfg(feature = "visitor")]
41use sqlparser_derive::{Visit, VisitMut};
42
43use crate::ast::{DollarQuotedString, QuoteDelimitedString};
44use crate::dialect::Dialect;
45use crate::dialect::{
46    BigQueryDialect, DuckDbDialect, GenericDialect, MySqlDialect, PostgreSqlDialect,
47    SnowflakeDialect,
48};
49use crate::keywords::{Keyword, ALL_KEYWORDS, ALL_KEYWORDS_INDEX};
50
51/// Chars that may join a preceding `-` or `!` into one token.
52pub(crate) const OPERATOR_CHARS: &str = "+-*/<>=~!@%#^&|";
53
54/// SQL Token enumeration
55#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
56#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
57#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
58pub enum Token {
59    /// An end-of-file marker, not a real token
60    EOF,
61    /// A keyword (like SELECT) or an optionally quoted SQL identifier
62    Word(Word),
63    /// An unsigned numeric literal
64    Number(String, bool),
65    /// A character that could not be tokenized
66    Char(char),
67    /// Single quoted string: i.e: 'string'
68    SingleQuotedString(String),
69    /// Double quoted string: i.e: "string"
70    DoubleQuotedString(String),
71    /// Triple single quoted strings: Example '''abc'''
72    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
73    TripleSingleQuotedString(String),
74    /// Triple double quoted strings: Example """abc"""
75    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
76    TripleDoubleQuotedString(String),
77    /// Dollar quoted string: i.e: $$string$$ or $tag_name$string$tag_name$
78    DollarQuotedString(DollarQuotedString),
79    /// Byte string literal: i.e: b'string' or B'string' (note that some backends, such as
80    /// PostgreSQL, may treat this syntax as a bit string literal instead, i.e: b'10010101')
81    SingleQuotedByteStringLiteral(String),
82    /// Byte string literal: i.e: b"string" or B"string"
83    DoubleQuotedByteStringLiteral(String),
84    /// Triple single quoted literal with byte string prefix. Example `B'''abc'''`
85    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
86    TripleSingleQuotedByteStringLiteral(String),
87    /// Triple double quoted literal with byte string prefix. Example `B"""abc"""`
88    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
89    TripleDoubleQuotedByteStringLiteral(String),
90    /// Single quoted literal with raw string prefix. Example `R'abc'`
91    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
92    SingleQuotedRawStringLiteral(String),
93    /// Double quoted literal with raw string prefix. Example `R"abc"`
94    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
95    DoubleQuotedRawStringLiteral(String),
96    /// Triple single quoted literal with raw string prefix. Example `R'''abc'''`
97    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
98    TripleSingleQuotedRawStringLiteral(String),
99    /// Triple double quoted literal with raw string prefix. Example `R"""abc"""`
100    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
101    TripleDoubleQuotedRawStringLiteral(String),
102    /// "National" string literal: i.e: N'string'
103    NationalStringLiteral(String),
104    /// Quote delimited literal. Examples `Q'{ab'c}'`, `Q'|ab'c|'`, `Q'|ab|c|'`
105    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Literals.html#GUID-1824CBAA-6E16-4921-B2A6-112FB02248DA)
106    QuoteDelimitedStringLiteral(QuoteDelimitedString),
107    /// "Nationa" quote delimited literal. Examples `NQ'{ab'c}'`, `NQ'|ab'c|'`, `NQ'|ab|c|'`
108    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Literals.html#GUID-1824CBAA-6E16-4921-B2A6-112FB02248DA)
109    NationalQuoteDelimitedStringLiteral(QuoteDelimitedString),
110    /// "escaped" string literal, which are an extension to the SQL standard: i.e: e'first \n second' or E 'first \n second'
111    EscapedStringLiteral(String),
112    /// Unicode string literal: i.e: U&'first \000A second'
113    UnicodeStringLiteral(String),
114    /// Hexadecimal string literal: i.e.: X'deadbeef'
115    HexStringLiteral(String),
116    /// Comma
117    Comma,
118    /// Whitespace (space, tab, etc)
119    Whitespace(Whitespace),
120    /// Double equals sign `==`
121    DoubleEq,
122    /// Equality operator `=`
123    Eq,
124    /// Not Equals operator `<>` (or `!=` in some dialects)
125    Neq,
126    /// Less Than operator `<`
127    Lt,
128    /// Greater Than operator `>`
129    Gt,
130    /// Less Than Or Equals operator `<=`
131    LtEq,
132    /// Greater Than Or Equals operator `>=`
133    GtEq,
134    /// Spaceship operator <=>
135    Spaceship,
136    /// Plus operator `+`
137    Plus,
138    /// Minus operator `-`
139    Minus,
140    /// Multiplication operator `*`
141    Mul,
142    /// Division operator `/`
143    Div,
144    /// Integer division operator `//` in DuckDB
145    DuckIntDiv,
146    /// Modulo Operator `%`
147    Mod,
148    /// String concatenation `||`
149    StringConcat,
150    /// Left parenthesis `(`
151    LParen,
152    /// Right parenthesis `)`
153    RParen,
154    /// Period (used for compound identifiers or projections into nested types)
155    Period,
156    /// Colon `:`
157    Colon,
158    /// DoubleColon `::` (used for casting in PostgreSQL)
159    DoubleColon,
160    /// Assignment `:=` (used for keyword argument in DuckDB macros and some functions, and for variable declarations in DuckDB and Snowflake)
161    Assignment,
162    /// SemiColon `;` used as separator for COPY and payload
163    SemiColon,
164    /// Backslash `\` used in terminating the COPY payload with `\.`
165    Backslash,
166    /// The verbatim inline payload of a `COPY ... FROM STDIN` statement,
167    /// captured raw by the tokenizer. `terminated` records whether the `\.`
168    /// terminator line was present.
169    CopyData {
170        /// The payload text, without the terminator line.
171        data: String,
172        /// Whether the `\.` terminator line was present.
173        terminated: bool,
174    },
175    /// Left bracket `[`
176    LBracket,
177    /// Right bracket `]`
178    RBracket,
179    /// Ampersand `&`
180    Ampersand,
181    /// Pipe `|`
182    Pipe,
183    /// Caret `^`
184    Caret,
185    /// Left brace `{`
186    LBrace,
187    /// Right brace `}`
188    RBrace,
189    /// Right Arrow `=>`
190    RArrow,
191    /// Sharp `#` used for PostgreSQL Bitwise XOR operator, also PostgreSQL/Redshift geometrical unary/binary operator (Number of points in path or polygon/Intersection)
192    Sharp,
193    /// `##` PostgreSQL/Redshift geometrical binary operator (Point of closest proximity)
194    DoubleSharp,
195    /// Tilde `~` used for PostgreSQL Bitwise NOT operator or case sensitive match regular expression operator
196    Tilde,
197    /// `~*` , a case insensitive match regular expression operator in PostgreSQL
198    TildeAsterisk,
199    /// `!~` , a case sensitive not match regular expression operator in PostgreSQL
200    ExclamationMarkTilde,
201    /// `!~*` , a case insensitive not match regular expression operator in PostgreSQL
202    ExclamationMarkTildeAsterisk,
203    /// `~~`, a case sensitive match pattern operator in PostgreSQL
204    DoubleTilde,
205    /// `~~*`, a case insensitive match pattern operator in PostgreSQL
206    DoubleTildeAsterisk,
207    /// `!~~`, a case sensitive not match pattern operator in PostgreSQL
208    ExclamationMarkDoubleTilde,
209    /// `!~~*`, a case insensitive not match pattern operator in PostgreSQL
210    ExclamationMarkDoubleTildeAsterisk,
211    /// `<<`, a bitwise shift left operator in PostgreSQL
212    ShiftLeft,
213    /// `>>`, a bitwise shift right operator in PostgreSQL
214    ShiftRight,
215    /// `&&`, an overlap operator in PostgreSQL
216    Overlap,
217    /// Exclamation Mark `!` used for PostgreSQL factorial operator
218    ExclamationMark,
219    /// Double Exclamation Mark `!!` used for PostgreSQL prefix factorial operator
220    DoubleExclamationMark,
221    /// AtSign `@` used for PostgreSQL abs operator, also PostgreSQL/Redshift geometrical unary/binary operator (Center, Contained or on)
222    AtSign,
223    /// `^@`, a "starts with" string operator in PostgreSQL
224    CaretAt,
225    /// `|/`, a square root math operator in PostgreSQL
226    PGSquareRoot,
227    /// `||/`, a cube root math operator in PostgreSQL
228    PGCubeRoot,
229    /// `?` or `$` , a prepared statement arg placeholder
230    Placeholder(String),
231    /// `->`, used as a operator to extract json field in PostgreSQL
232    Arrow,
233    /// `->>`, used as a operator to extract json field as text in PostgreSQL
234    LongArrow,
235    /// `#>`, extracts JSON sub-object at the specified path
236    HashArrow,
237    /// `@-@` PostgreSQL/Redshift geometrical unary operator (Length or circumference)
238    AtDashAt,
239    /// `?-` PostgreSQL/Redshift geometrical unary/binary operator (Is horizontal?/Are horizontally aligned?)
240    QuestionMarkDash,
241    /// `&<` PostgreSQL/Redshift geometrical binary operator (Overlaps to left?)
242    AmpersandLeftAngleBracket,
243    /// `&>` PostgreSQL/Redshift geometrical binary operator (Overlaps to right?)`
244    AmpersandRightAngleBracket,
245    /// `&<|` PostgreSQL/Redshift geometrical binary operator (Does not extend above?)`
246    AmpersandLeftAngleBracketVerticalBar,
247    /// `|&>` PostgreSQL/Redshift geometrical binary operator (Does not extend below?)`
248    VerticalBarAmpersandRightAngleBracket,
249    /// `<->` PostgreSQL/Redshift geometrical binary operator (Distance between)
250    TwoWayArrow,
251    /// `<^` PostgreSQL/Redshift geometrical binary operator (Is below?)
252    LeftAngleBracketCaret,
253    /// `>^` PostgreSQL/Redshift geometrical binary operator (Is above?)
254    RightAngleBracketCaret,
255    /// `?#` PostgreSQL/Redshift geometrical binary operator (Intersects or overlaps)
256    QuestionMarkSharp,
257    /// `?-|` PostgreSQL/Redshift geometrical binary operator (Is perpendicular?)
258    QuestionMarkDashVerticalBar,
259    /// `?||` PostgreSQL/Redshift geometrical binary operator (Are parallel?)
260    QuestionMarkDoubleVerticalBar,
261    /// `~=` PostgreSQL/Redshift geometrical binary operator (Same as)
262    TildeEqual,
263    /// `<<| PostgreSQL/Redshift geometrical binary operator (Is strictly below?)
264    ShiftLeftVerticalBar,
265    /// `|>> PostgreSQL/Redshift geometrical binary operator (Is strictly above?)
266    VerticalBarShiftRight,
267    /// `|> BigQuery pipe operator
268    VerticalBarRightAngleBracket,
269    /// `#>>`, extracts JSON sub-object at the specified path as text
270    HashLongArrow,
271    /// jsonb @> jsonb -> boolean: Test whether left json contains the right json
272    AtArrow,
273    /// jsonb <@ jsonb -> boolean: Test whether right json contains the left json
274    ArrowAt,
275    /// jsonb #- text[] -> jsonb: Deletes the field or array element at the specified
276    /// path, where path elements can be either field keys or array indexes.
277    HashMinus,
278    /// jsonb @? jsonpath -> boolean: Does JSON path return any item for the specified
279    /// JSON value?
280    AtQuestion,
281    /// jsonb @@ jsonpath → boolean: Returns the result of a JSON path predicate check
282    /// for the specified JSON value. Only the first item of the result is taken into
283    /// account. If the result is not Boolean, then NULL is returned.
284    AtAt,
285    /// jsonb ? text -> boolean: Checks whether the string exists as a top-level key within the
286    /// jsonb object
287    Question,
288    /// jsonb ?& text[] -> boolean: Check whether all members of the text array exist as top-level
289    /// keys within the jsonb object
290    QuestionAnd,
291    /// jsonb ?| text[] -> boolean: Check whether any member of the text array exists as top-level
292    /// keys within the jsonb object
293    QuestionPipe,
294    /// Custom binary operator
295    /// This is used to represent any custom binary operator that is not part of the SQL standard.
296    /// PostgreSQL allows defining custom binary operators using CREATE OPERATOR.
297    CustomBinaryOperator(String),
298}
299
300impl fmt::Display for Token {
301    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302        match self {
303            Token::EOF => f.write_str("EOF"),
304            Token::Word(ref w) => write!(f, "{w}"),
305            Token::Number(ref n, l) => write!(f, "{}{long}", n, long = if *l { "L" } else { "" }),
306            Token::Char(ref c) => write!(f, "{c}"),
307            Token::SingleQuotedString(ref s) => write!(f, "'{s}'"),
308            Token::TripleSingleQuotedString(ref s) => write!(f, "'''{s}'''"),
309            Token::DoubleQuotedString(ref s) => write!(f, "\"{s}\""),
310            Token::TripleDoubleQuotedString(ref s) => write!(f, "\"\"\"{s}\"\"\""),
311            Token::DollarQuotedString(ref s) => write!(f, "{s}"),
312            Token::NationalStringLiteral(ref s) => write!(f, "N'{s}'"),
313            Token::QuoteDelimitedStringLiteral(ref s) => s.fmt(f),
314            Token::NationalQuoteDelimitedStringLiteral(ref s) => write!(f, "N{s}"),
315            Token::EscapedStringLiteral(ref s) => write!(f, "E'{s}'"),
316            Token::UnicodeStringLiteral(ref s) => write!(f, "U&'{s}'"),
317            Token::HexStringLiteral(ref s) => write!(f, "X'{s}'"),
318            Token::SingleQuotedByteStringLiteral(ref s) => write!(f, "B'{s}'"),
319            Token::TripleSingleQuotedByteStringLiteral(ref s) => write!(f, "B'''{s}'''"),
320            Token::DoubleQuotedByteStringLiteral(ref s) => write!(f, "B\"{s}\""),
321            Token::TripleDoubleQuotedByteStringLiteral(ref s) => write!(f, "B\"\"\"{s}\"\"\""),
322            Token::SingleQuotedRawStringLiteral(ref s) => write!(f, "R'{s}'"),
323            Token::DoubleQuotedRawStringLiteral(ref s) => write!(f, "R\"{s}\""),
324            Token::TripleSingleQuotedRawStringLiteral(ref s) => write!(f, "R'''{s}'''"),
325            Token::TripleDoubleQuotedRawStringLiteral(ref s) => write!(f, "R\"\"\"{s}\"\"\""),
326            Token::Comma => f.write_str(","),
327            Token::Whitespace(ws) => write!(f, "{ws}"),
328            Token::DoubleEq => f.write_str("=="),
329            Token::Spaceship => f.write_str("<=>"),
330            Token::Eq => f.write_str("="),
331            Token::Neq => f.write_str("<>"),
332            Token::Lt => f.write_str("<"),
333            Token::Gt => f.write_str(">"),
334            Token::LtEq => f.write_str("<="),
335            Token::GtEq => f.write_str(">="),
336            Token::Plus => f.write_str("+"),
337            Token::Minus => f.write_str("-"),
338            Token::Mul => f.write_str("*"),
339            Token::Div => f.write_str("/"),
340            Token::DuckIntDiv => f.write_str("//"),
341            Token::StringConcat => f.write_str("||"),
342            Token::Mod => f.write_str("%"),
343            Token::LParen => f.write_str("("),
344            Token::RParen => f.write_str(")"),
345            Token::Period => f.write_str("."),
346            Token::Colon => f.write_str(":"),
347            Token::DoubleColon => f.write_str("::"),
348            Token::Assignment => f.write_str(":="),
349            Token::SemiColon => f.write_str(";"),
350            Token::Backslash => f.write_str("\\"),
351            Token::CopyData { data, .. } => f.write_str(data),
352            Token::LBracket => f.write_str("["),
353            Token::RBracket => f.write_str("]"),
354            Token::Ampersand => f.write_str("&"),
355            Token::Caret => f.write_str("^"),
356            Token::Pipe => f.write_str("|"),
357            Token::LBrace => f.write_str("{"),
358            Token::RBrace => f.write_str("}"),
359            Token::RArrow => f.write_str("=>"),
360            Token::Sharp => f.write_str("#"),
361            Token::DoubleSharp => f.write_str("##"),
362            Token::ExclamationMark => f.write_str("!"),
363            Token::DoubleExclamationMark => f.write_str("!!"),
364            Token::Tilde => f.write_str("~"),
365            Token::TildeAsterisk => f.write_str("~*"),
366            Token::ExclamationMarkTilde => f.write_str("!~"),
367            Token::ExclamationMarkTildeAsterisk => f.write_str("!~*"),
368            Token::DoubleTilde => f.write_str("~~"),
369            Token::DoubleTildeAsterisk => f.write_str("~~*"),
370            Token::ExclamationMarkDoubleTilde => f.write_str("!~~"),
371            Token::ExclamationMarkDoubleTildeAsterisk => f.write_str("!~~*"),
372            Token::AtSign => f.write_str("@"),
373            Token::CaretAt => f.write_str("^@"),
374            Token::ShiftLeft => f.write_str("<<"),
375            Token::ShiftRight => f.write_str(">>"),
376            Token::Overlap => f.write_str("&&"),
377            Token::PGSquareRoot => f.write_str("|/"),
378            Token::PGCubeRoot => f.write_str("||/"),
379            Token::AtDashAt => f.write_str("@-@"),
380            Token::QuestionMarkDash => f.write_str("?-"),
381            Token::AmpersandLeftAngleBracket => f.write_str("&<"),
382            Token::AmpersandRightAngleBracket => f.write_str("&>"),
383            Token::AmpersandLeftAngleBracketVerticalBar => f.write_str("&<|"),
384            Token::VerticalBarAmpersandRightAngleBracket => f.write_str("|&>"),
385            Token::VerticalBarRightAngleBracket => f.write_str("|>"),
386            Token::TwoWayArrow => f.write_str("<->"),
387            Token::LeftAngleBracketCaret => f.write_str("<^"),
388            Token::RightAngleBracketCaret => f.write_str(">^"),
389            Token::QuestionMarkSharp => f.write_str("?#"),
390            Token::QuestionMarkDashVerticalBar => f.write_str("?-|"),
391            Token::QuestionMarkDoubleVerticalBar => f.write_str("?||"),
392            Token::TildeEqual => f.write_str("~="),
393            Token::ShiftLeftVerticalBar => f.write_str("<<|"),
394            Token::VerticalBarShiftRight => f.write_str("|>>"),
395            Token::Placeholder(ref s) => write!(f, "{s}"),
396            Token::Arrow => write!(f, "->"),
397            Token::LongArrow => write!(f, "->>"),
398            Token::HashArrow => write!(f, "#>"),
399            Token::HashLongArrow => write!(f, "#>>"),
400            Token::AtArrow => write!(f, "@>"),
401            Token::ArrowAt => write!(f, "<@"),
402            Token::HashMinus => write!(f, "#-"),
403            Token::AtQuestion => write!(f, "@?"),
404            Token::AtAt => write!(f, "@@"),
405            Token::Question => write!(f, "?"),
406            Token::QuestionAnd => write!(f, "?&"),
407            Token::QuestionPipe => write!(f, "?|"),
408            Token::CustomBinaryOperator(s) => f.write_str(s),
409        }
410    }
411}
412
413impl Token {
414    /// Create a `Token::Word` from an unquoted `keyword`.
415    ///
416    /// The lookup is case-insensitive; unknown values become `Keyword::NoKeyword`.
417    pub fn make_keyword(keyword: &str) -> Self {
418        Token::make_word(keyword, None)
419    }
420
421    /// Create a `Token::Word` from `word` with an optional `quote_style`.
422    ///
423    /// When `quote_style` is `None`, the parser attempts a case-insensitive keyword
424    /// lookup and sets the `Word::keyword` accordingly.
425    pub fn make_word(word: &str, quote_style: Option<char>) -> Self {
426        Token::Word(Word {
427            keyword: keyword_lookup(word, quote_style),
428            value: word.to_string(),
429            quote_style,
430        })
431    }
432
433    /// Like [`Self::make_word`] but takes ownership of the word `String`,
434    /// avoiding an extra allocation when the caller already has an owned value.
435    fn make_word_owned(word: String, quote_style: Option<char>) -> Self {
436        Token::Word(Word {
437            keyword: keyword_lookup(&word, quote_style),
438            value: word,
439            quote_style,
440        })
441    }
442}
443
444/// Case-insensitive keyword lookup using binary search over [`ALL_KEYWORDS`].
445fn keyword_lookup(word: &str, quote_style: Option<char>) -> Keyword {
446    if quote_style.is_some() {
447        return Keyword::NoKeyword;
448    }
449    ALL_KEYWORDS
450        .binary_search_by(|probe| {
451            let probe = probe.as_bytes();
452            let word = word.as_bytes();
453            for (p, w) in probe.iter().zip(word.iter()) {
454                let cmp = p.cmp(&w.to_ascii_uppercase());
455                if cmp != core::cmp::Ordering::Equal {
456                    return cmp;
457                }
458            }
459            probe.len().cmp(&word.len())
460        })
461        .map_or(Keyword::NoKeyword, |x| ALL_KEYWORDS_INDEX[x])
462}
463
464/// A keyword (like SELECT) or an optionally quoted SQL identifier
465#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
466#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
467#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
468pub struct Word {
469    /// The value of the token, without the enclosing quotes, and with the
470    /// escape sequences (if any) processed (TODO: escapes are not handled)
471    pub value: String,
472    /// An identifier can be "quoted" (&lt;delimited identifier> in ANSI parlance).
473    /// The standard and most implementations allow using double quotes for this,
474    /// but some implementations support other quoting styles as well (e.g. \[MS SQL])
475    pub quote_style: Option<char>,
476    /// If the word was not quoted and it matched one of the known keywords,
477    /// this will have one of the values from dialect::keywords, otherwise empty
478    pub keyword: Keyword,
479}
480
481impl fmt::Display for Word {
482    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
483        crate::ast::fmt_ident(f, &self.value, self.quote_style)
484    }
485}
486
487impl Word {
488    fn matching_end_quote(ch: char) -> char {
489        match ch {
490            '"' => '"', // ANSI and most dialects
491            '[' => ']', // MS SQL
492            '`' => '`', // MySQL
493            _ => panic!("unexpected quoting style!"),
494        }
495    }
496}
497
498/// Represents whitespace in the input: spaces, newlines, tabs and comments.
499#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
502pub enum Whitespace {
503    /// A single space character.
504    Space,
505    /// A newline character.
506    Newline,
507    /// A tab character.
508    Tab,
509    /// A single-line comment (e.g. `-- comment` or `# comment`).
510    /// The `comment` field contains the text, and `prefix` contains the comment prefix.
511    SingleLineComment {
512        /// The content of the comment (without the prefix).
513        comment: String,
514        /// The prefix used for the comment (for example `--` or `#`).
515        prefix: String,
516    },
517
518    /// A multi-line comment (without the `/* ... */` delimiters).
519    MultiLineComment(String),
520}
521
522impl fmt::Display for Whitespace {
523    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
524        match self {
525            Whitespace::Space => f.write_str(" "),
526            Whitespace::Newline => f.write_str("\n"),
527            Whitespace::Tab => f.write_str("\t"),
528            Whitespace::SingleLineComment { prefix, comment } => writeln!(f, "{prefix}{comment}"),
529            Whitespace::MultiLineComment(s) => write!(f, "/*{s}*/"),
530        }
531    }
532}
533
534/// Location in input string
535///
536/// # Create an "empty" (unknown) `Location`
537/// ```
538/// # use sqlparser::tokenizer::Location;
539/// let location = Location::empty();
540/// ```
541///
542/// # Create a `Location` from a line and column
543/// ```
544/// # use sqlparser::tokenizer::Location;
545/// let location = Location::new(1, 1);
546/// ```
547///
548/// # Create a `Location` from a pair
549/// ```
550/// # use sqlparser::tokenizer::Location;
551/// let location = Location::from((1, 1));
552/// ```
553#[derive(Eq, PartialEq, Hash, Clone, Copy, Ord, PartialOrd)]
554#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
555#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
556pub struct Location {
557    /// Line number, starting from 1.
558    ///
559    /// Note: Line 0 is used for empty spans
560    pub line: u64,
561    /// Line column, starting from 1.
562    ///
563    /// Note: Column 0 is used for empty spans
564    pub column: u64,
565}
566
567impl fmt::Display for Location {
568    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
569        if self.line == 0 {
570            return Ok(());
571        }
572        write!(f, " at Line: {}, Column: {}", self.line, self.column)
573    }
574}
575
576impl fmt::Debug for Location {
577    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
578        write!(f, "Location({},{})", self.line, self.column)
579    }
580}
581
582impl Location {
583    /// Return an "empty" / unknown location
584    pub fn empty() -> Self {
585        Self { line: 0, column: 0 }
586    }
587
588    /// Create a new `Location` for a given line and column
589    pub fn new(line: u64, column: u64) -> Self {
590        Self { line, column }
591    }
592
593    /// Create a new location for a given line and column
594    ///
595    /// Alias for [`Self::new`]
596    // TODO: remove / deprecate in favor of` `new` for consistency?
597    pub fn of(line: u64, column: u64) -> Self {
598        Self::new(line, column)
599    }
600
601    /// Combine self and `end` into a new `Span`
602    pub fn span_to(self, end: Self) -> Span {
603        Span { start: self, end }
604    }
605}
606
607impl From<(u64, u64)> for Location {
608    fn from((line, column): (u64, u64)) -> Self {
609        Self { line, column }
610    }
611}
612
613/// A span represents a linear portion of the input string (start, end)
614///
615/// See [Spanned](crate::ast::Spanned) for more information.
616#[derive(Eq, PartialEq, Hash, Clone, PartialOrd, Ord, Copy)]
617#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
618#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
619pub struct Span {
620    /// Start `Location` (inclusive).
621    pub start: Location,
622    /// End `Location` (inclusive).
623    pub end: Location,
624}
625
626impl fmt::Debug for Span {
627    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
628        write!(f, "Span({:?}..{:?})", self.start, self.end)
629    }
630}
631
632impl Span {
633    // An empty span (0, 0) -> (0, 0)
634    // We need a const instance for pattern matching
635    const EMPTY: Span = Self::empty();
636
637    /// Create a new span from a start and end [`Location`]
638    pub fn new(start: Location, end: Location) -> Span {
639        Span { start, end }
640    }
641
642    /// Returns an empty span `(0, 0) -> (0, 0)`
643    ///
644    /// Empty spans represent no knowledge of source location
645    /// See [Spanned](crate::ast::Spanned) for more information.
646    pub const fn empty() -> Span {
647        Span {
648            start: Location { line: 0, column: 0 },
649            end: Location { line: 0, column: 0 },
650        }
651    }
652
653    /// Returns the smallest Span that contains both `self` and `other`
654    /// If either span is [Span::empty], the other span is returned
655    ///
656    /// # Examples
657    /// ```
658    /// # use sqlparser::tokenizer::{Span, Location};
659    /// // line 1, column1 -> line 2, column 5
660    /// let span1 = Span::new(Location::new(1, 1), Location::new(2, 5));
661    /// // line 2, column 3 -> line 3, column 7
662    /// let span2 = Span::new(Location::new(2, 3), Location::new(3, 7));
663    /// // Union of the two is the min/max of the two spans
664    /// // line 1, column 1 -> line 3, column 7
665    /// let union = span1.union(&span2);
666    /// assert_eq!(union, Span::new(Location::new(1, 1), Location::new(3, 7)));
667    /// ```
668    pub fn union(&self, other: &Span) -> Span {
669        // If either span is empty, return the other
670        // this prevents propagating (0, 0) through the tree
671        match (self, other) {
672            (&Span::EMPTY, _) => *other,
673            (_, &Span::EMPTY) => *self,
674            _ => Span {
675                start: cmp::min(self.start, other.start),
676                end: cmp::max(self.end, other.end),
677            },
678        }
679    }
680
681    /// Same as [Span::union] for `Option<Span>`
682    ///
683    /// If `other` is `None`, `self` is returned
684    pub fn union_opt(&self, other: &Option<Span>) -> Span {
685        match other {
686            Some(other) => self.union(other),
687            None => *self,
688        }
689    }
690
691    /// Return the [Span::union] of all spans in the iterator
692    ///
693    /// If the iterator is empty, an empty span is returned
694    ///
695    /// # Example
696    /// ```
697    /// # use sqlparser::tokenizer::{Span, Location};
698    /// let spans = vec![
699    ///     Span::new(Location::new(1, 1), Location::new(2, 5)),
700    ///     Span::new(Location::new(2, 3), Location::new(3, 7)),
701    ///     Span::new(Location::new(3, 1), Location::new(4, 2)),
702    /// ];
703    /// // line 1, column 1 -> line 4, column 2
704    /// assert_eq!(
705    ///   Span::union_iter(spans),
706    ///   Span::new(Location::new(1, 1), Location::new(4, 2))
707    /// );
708    pub fn union_iter<I: IntoIterator<Item = Span>>(iter: I) -> Span {
709        iter.into_iter()
710            .reduce(|acc, item| acc.union(&item))
711            .unwrap_or(Span::empty())
712    }
713}
714
715/// Backwards compatibility struct for [`TokenWithSpan`]
716#[deprecated(since = "0.53.0", note = "please use `TokenWithSpan` instead")]
717pub type TokenWithLocation = TokenWithSpan;
718
719/// A [Token] with [Span] attached to it
720///
721/// This is used to track the location of a token in the input string
722///
723/// # Examples
724/// ```
725/// # use sqlparser::tokenizer::{Location, Span, Token, TokenWithSpan};
726/// // commas @ line 1, column 10
727/// let tok1 = TokenWithSpan::new(
728///   Token::Comma,
729///   Span::new(Location::new(1, 10), Location::new(1, 11)),
730/// );
731/// assert_eq!(tok1, Token::Comma); // can compare the token
732///
733/// // commas @ line 2, column 20
734/// let tok2 = TokenWithSpan::new(
735///   Token::Comma,
736///   Span::new(Location::new(2, 20), Location::new(2, 21)),
737/// );
738/// // same token but different locations are not equal
739/// assert_ne!(tok1, tok2);
740/// ```
741#[derive(Debug, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
742#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
743#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
744/// A `Token` together with its `Span` (location in the source).
745pub struct TokenWithSpan {
746    /// The token value.
747    pub token: Token,
748    /// The span covering the token in the input.
749    pub span: Span,
750}
751
752impl TokenWithSpan {
753    /// Create a new [`TokenWithSpan`] from a [`Token`] and a [`Span`]
754    pub fn new(token: Token, span: Span) -> Self {
755        Self { token, span }
756    }
757
758    /// Wrap a token with an empty span
759    pub fn wrap(token: Token) -> Self {
760        Self::new(token, Span::empty())
761    }
762
763    /// Wrap a token with a location from `start` to `end`
764    pub fn at(token: Token, start: Location, end: Location) -> Self {
765        Self::new(token, Span::new(start, end))
766    }
767
768    /// Return an EOF token with no location
769    pub fn new_eof() -> Self {
770        Self::wrap(Token::EOF)
771    }
772}
773
774impl PartialEq<Token> for TokenWithSpan {
775    fn eq(&self, other: &Token) -> bool {
776        &self.token == other
777    }
778}
779
780impl PartialEq<TokenWithSpan> for Token {
781    fn eq(&self, other: &TokenWithSpan) -> bool {
782        self == &other.token
783    }
784}
785
786impl fmt::Display for TokenWithSpan {
787    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788        self.token.fmt(f)
789    }
790}
791
792/// An error reported by the tokenizer, with a human-readable `message` and a `location`.
793#[derive(Debug, PartialEq, Eq)]
794pub struct TokenizerError {
795    /// A descriptive error message.
796    pub message: String,
797    /// The `Location` where the error was detected.
798    pub location: Location,
799}
800
801impl fmt::Display for TokenizerError {
802    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803        write!(f, "{}{}", self.message, self.location,)
804    }
805}
806
807impl core::error::Error for TokenizerError {}
808
809struct State<'a> {
810    peekable: Peekable<Chars<'a>>,
811    line: u64,
812    col: u64,
813}
814
815impl State<'_> {
816    /// return the next character and advance the stream
817    pub fn next(&mut self) -> Option<char> {
818        match self.peekable.next() {
819            None => None,
820            Some(s) => {
821                if s == '\n' {
822                    self.line += 1;
823                    self.col = 1;
824                } else {
825                    self.col += 1;
826                }
827                Some(s)
828            }
829        }
830    }
831
832    /// return the next character but do not advance the stream
833    pub fn peek(&mut self) -> Option<&char> {
834        self.peekable.peek()
835    }
836
837    /// Return the current `Location` (line and column)
838    pub fn location(&self) -> Location {
839        Location {
840            line: self.line,
841            column: self.col,
842        }
843    }
844}
845
846/// Tracks whether the statement being tokenized is a `COPY ... FROM STDIN` statement.
847struct CopyStatementTracker {
848    enabled: bool,
849    first_token_seen: bool,
850    starts_with_copy: bool,
851    prev_was_from: bool,
852    from_stdin: bool,
853    paren_depth: u32,
854}
855
856impl CopyStatementTracker {
857    fn new(enabled: bool) -> Self {
858        Self {
859            enabled,
860            first_token_seen: false,
861            starts_with_copy: false,
862            prev_was_from: false,
863            from_stdin: false,
864            paren_depth: 0,
865        }
866    }
867
868    /// Whether the `;` closing the current statement captures the raw payload.
869    fn captures_payload(&self) -> bool {
870        self.enabled && self.starts_with_copy && self.from_stdin
871    }
872
873    /// Record a token, ignoring whitespace, and reset the statement on `;`.
874    fn note(&mut self, token: &Token) {
875        if !self.enabled {
876            return;
877        }
878        match token {
879            Token::SemiColon => {
880                self.first_token_seen = false;
881                self.starts_with_copy = false;
882                self.prev_was_from = false;
883                self.from_stdin = false;
884                self.paren_depth = 0;
885            }
886            Token::LParen => {
887                self.paren_depth += 1;
888                self.first_token_seen = true;
889                self.prev_was_from = false;
890            }
891            Token::RParen => {
892                self.paren_depth = self.paren_depth.saturating_sub(1);
893                self.first_token_seen = true;
894                self.prev_was_from = false;
895            }
896            Token::Whitespace(_) => {}
897            Token::Word(word) => {
898                if !self.first_token_seen {
899                    self.first_token_seen = true;
900                    self.starts_with_copy = word.keyword == Keyword::COPY;
901                }
902                if self.prev_was_from && word.keyword == Keyword::STDIN && self.paren_depth == 0 {
903                    self.from_stdin = true;
904                }
905                self.prev_was_from = word.keyword == Keyword::FROM;
906            }
907            _ => {
908                self.first_token_seen = true;
909                self.prev_was_from = false;
910            }
911        }
912    }
913}
914
915/// The captured `COPY ... FROM STDIN` payload and the rest of the `;` line.
916/// The `Option` is the payload token, absent when the data is empty and
917/// unterminated, followed by the tokens of the rest of the line.
918type CopyCapture = (Option<(String, bool, Span)>, Vec<TokenWithSpan>);
919
920/// Represents how many quote characters enclose a string literal.
921#[derive(Copy, Clone)]
922enum NumStringQuoteChars {
923    /// e.g. `"abc"`, `'abc'`, `r'abc'`
924    One,
925    /// e.g. `"""abc"""`, `'''abc'''`, `r'''abc'''`
926    Many(NonZeroU8),
927}
928
929/// Settings for tokenizing a quoted string literal.
930struct TokenizeQuotedStringSettings {
931    /// The character used to quote the string.
932    quote_style: char,
933    /// Represents how many quotes characters enclose the string literal.
934    num_quote_chars: NumStringQuoteChars,
935    /// The number of opening quotes left to consume, before parsing
936    /// the remaining string literal.
937    /// For example: given initial string `"""abc"""`. If the caller has
938    /// already parsed the first quote for some reason, then this value
939    /// is set to 1, flagging to look to consume only 2 leading quotes.
940    num_opening_quotes_to_consume: u8,
941    /// True if the string uses backslash escaping of special characters
942    /// e.g `'abc\ndef\'ghi'
943    backslash_escape: bool,
944}
945
946/// SQL Tokenizer
947pub struct Tokenizer<'a> {
948    dialect: &'a dyn Dialect,
949    query: &'a str,
950    /// If true (the default), the tokenizer will un-escape literal
951    /// SQL strings See [`Tokenizer::with_unescape`] for more details.
952    unescape: bool,
953}
954
955impl<'a> Tokenizer<'a> {
956    /// Create a new SQL tokenizer for the specified SQL statement
957    ///
958    /// ```
959    /// # use sqlparser::tokenizer::{Token, Whitespace, Tokenizer};
960    /// # use sqlparser::dialect::GenericDialect;
961    /// # let dialect = GenericDialect{};
962    /// let query = r#"SELECT 'foo'"#;
963    ///
964    /// // Parsing the query
965    /// let tokens = Tokenizer::new(&dialect, &query).tokenize().unwrap();
966    ///
967    /// assert_eq!(tokens, vec![
968    ///   Token::make_word("SELECT", None),
969    ///   Token::Whitespace(Whitespace::Space),
970    ///   Token::SingleQuotedString("foo".to_string()),
971    /// ]);
972    pub fn new(dialect: &'a dyn Dialect, query: &'a str) -> Self {
973        Self {
974            dialect,
975            query,
976            unescape: true,
977        }
978    }
979
980    /// Set unescape mode
981    ///
982    /// When true (default) the tokenizer unescapes literal values
983    /// (for example, `""` in SQL is unescaped to the literal `"`).
984    ///
985    /// When false, the tokenizer provides the raw strings as provided
986    /// in the query.  This can be helpful for programs that wish to
987    /// recover the *exact* original query text without normalizing
988    /// the escaping
989    ///
990    /// # Example
991    ///
992    /// ```
993    /// # use sqlparser::tokenizer::{Token, Tokenizer};
994    /// # use sqlparser::dialect::GenericDialect;
995    /// # let dialect = GenericDialect{};
996    /// let query = r#""Foo "" Bar""#;
997    /// let unescaped = Token::make_word(r#"Foo " Bar"#, Some('"'));
998    /// let original  = Token::make_word(r#"Foo "" Bar"#, Some('"'));
999    ///
1000    /// // Parsing with unescaping (default)
1001    /// let tokens = Tokenizer::new(&dialect, &query).tokenize().unwrap();
1002    /// assert_eq!(tokens, vec![unescaped]);
1003    ///
1004    /// // Parsing with unescape = false
1005    /// let tokens = Tokenizer::new(&dialect, &query)
1006    ///    .with_unescape(false)
1007    ///    .tokenize().unwrap();
1008    /// assert_eq!(tokens, vec![original]);
1009    /// ```
1010    pub fn with_unescape(mut self, unescape: bool) -> Self {
1011        self.unescape = unescape;
1012        self
1013    }
1014
1015    /// Tokenize the statement and produce a vector of tokens
1016    pub fn tokenize(&mut self) -> Result<Vec<Token>, TokenizerError> {
1017        let twl = self.tokenize_with_location()?;
1018        Ok(twl.into_iter().map(|t| t.token).collect())
1019    }
1020
1021    /// Tokenize the statement and produce a vector of tokens with location information
1022    pub fn tokenize_with_location(&mut self) -> Result<Vec<TokenWithSpan>, TokenizerError> {
1023        let mut tokens: Vec<TokenWithSpan> = vec![];
1024        self.tokenize_with_location_into_buf(&mut tokens)
1025            .map(|_| tokens)
1026    }
1027
1028    /// Tokenize the statement and append tokens with location information into the provided buffer.
1029    /// If an error is thrown, the buffer will contain all tokens that were successfully parsed before the error.
1030    pub fn tokenize_with_location_into_buf(
1031        &mut self,
1032        buf: &mut Vec<TokenWithSpan>,
1033    ) -> Result<(), TokenizerError> {
1034        self.tokenize_with_location_into_buf_with_mapper(buf, |token| token)
1035    }
1036
1037    /// Tokenize into the provided buffer, using existing and mapped tokens as context for subsequent tokens.
1038    pub fn tokenize_with_location_into_buf_with_mapper(
1039        &mut self,
1040        buf: &mut Vec<TokenWithSpan>,
1041        mut mapper: impl FnMut(TokenWithSpan) -> TokenWithSpan,
1042    ) -> Result<(), TokenizerError> {
1043        let mut state = State {
1044            peekable: self.query.chars().peekable(),
1045            line: 1,
1046            col: 1,
1047        };
1048
1049        let mut prev_non_ws = buf
1050            .iter()
1051            .rposition(|t| !matches!(t.token, Token::Whitespace(_)));
1052        let mut location = state.location();
1053        let mut copy = CopyStatementTracker::new(self.dialect.supports_copy_from_stdin_data());
1054        while let Some(token) = self.next_token(
1055            &mut state,
1056            buf.last().map(|t| &t.token),
1057            prev_non_ws.map(|index| &buf[index].token),
1058        )? {
1059            let span = location.span_to(state.location());
1060
1061            // Capture before tokenizing the rest of the line so both keep their source locations.
1062            let mut payload: Option<CopyCapture> = None;
1063            if let Token::SemiColon = &token {
1064                if copy.captures_payload() {
1065                    payload = Some(self.capture_copy_data(&mut state, Some(&token))?);
1066                }
1067            }
1068            copy.note(&token);
1069
1070            let (copy_data, rest) = match payload {
1071                Some((copy_data, rest)) => (copy_data, Some(rest)),
1072                None => (None, None),
1073            };
1074
1075            // The payload token precedes the `;` so the statement loop owns the delimiter.
1076            if let Some((data, terminated, data_span)) = copy_data {
1077                let token = mapper(TokenWithSpan {
1078                    token: Token::CopyData { data, terminated },
1079                    span: data_span,
1080                });
1081                if !matches!(token.token, Token::Whitespace(_)) {
1082                    prev_non_ws = Some(buf.len());
1083                }
1084                buf.push(token);
1085            }
1086
1087            // Check if this is a multiline comment hint that should be expanded
1088            match &token {
1089                Token::Whitespace(Whitespace::MultiLineComment(comment))
1090                    if self.dialect.supports_multiline_comment_hints()
1091                        && comment.starts_with('!') =>
1092                {
1093                    // Re-tokenize the hints and add them to the buffer
1094                    self.tokenize_comment_hints(comment, span, buf, &mut prev_non_ws, &mut mapper)?;
1095                }
1096                _ => {
1097                    let token = mapper(TokenWithSpan { token, span });
1098                    if !matches!(token.token, Token::Whitespace(_)) {
1099                        prev_non_ws = Some(buf.len());
1100                    }
1101                    buf.push(token);
1102                }
1103            }
1104
1105            if let Some(rest_tokens) = rest {
1106                for rest_token in rest_tokens {
1107                    copy.note(&rest_token.token);
1108                    let rest_token = mapper(rest_token);
1109                    if !matches!(rest_token.token, Token::Whitespace(_)) {
1110                        prev_non_ws = Some(buf.len());
1111                    }
1112                    buf.push(rest_token);
1113                }
1114            }
1115            location = state.location();
1116        }
1117        Ok(())
1118    }
1119
1120    /// Re-tokenize optimizer hints from a multiline comment and add them to the buffer.
1121    /// For example, `/*!50110 KEY_BLOCK_SIZE = 1024*/` becomes tokens for `KEY_BLOCK_SIZE = 1024`
1122    fn tokenize_comment_hints(
1123        &self,
1124        comment: &str,
1125        span: Span,
1126        buf: &mut Vec<TokenWithSpan>,
1127        prev_non_ws: &mut Option<usize>,
1128        mut mapper: impl FnMut(TokenWithSpan) -> TokenWithSpan,
1129    ) -> Result<(), TokenizerError> {
1130        // Strip the leading '!' and any version digits (e.g., "50110")
1131        let hint_content = comment
1132            .strip_prefix('!')
1133            .unwrap_or(comment)
1134            .trim_start_matches(|c: char| c.is_ascii_digit());
1135
1136        // If there's no content after stripping, nothing to tokenize
1137        if hint_content.is_empty() {
1138            return Ok(());
1139        }
1140
1141        // Create a new tokenizer for the hint content
1142        let inner = Tokenizer::new(self.dialect, hint_content).with_unescape(self.unescape);
1143
1144        // Create a state for tracking position within the hint
1145        let mut state = State {
1146            peekable: hint_content.chars().peekable(),
1147            line: span.start.line,
1148            col: span.start.column,
1149        };
1150
1151        // Tokenize the hint content and add tokens to the buffer
1152        let mut location = state.location();
1153        while let Some(token) = inner.next_token(
1154            &mut state,
1155            buf.last().map(|t| &t.token),
1156            prev_non_ws.map(|index| &buf[index].token),
1157        )? {
1158            let token_span = location.span_to(state.location());
1159            let token = mapper(TokenWithSpan {
1160                token,
1161                span: token_span,
1162            });
1163            if !matches!(token.token, Token::Whitespace(_)) {
1164                *prev_non_ws = Some(buf.len());
1165            }
1166            buf.push(token);
1167            location = state.location();
1168        }
1169
1170        Ok(())
1171    }
1172
1173    /// Capture the raw payload after the `;` of a `COPY ... FROM STDIN` statement, returning the rest
1174    /// of that line as tokens to emit after the `;`. The payload token is absent when the data is
1175    /// empty and unterminated, e.g. a bare `COPY t FROM STDIN;` at end of input.
1176    fn capture_copy_data(
1177        &self,
1178        state: &mut State,
1179        prev: Option<&Token>,
1180    ) -> Result<CopyCapture, TokenizerError> {
1181        let mut rest: Vec<TokenWithSpan> = Vec::new();
1182        let mut location = state.location();
1183        let mut prev_non_ws = None;
1184        while let Some(token) = self.next_token(
1185            state,
1186            rest.last().map(|t| &t.token).or(prev),
1187            prev_non_ws.map(|index: usize| &rest[index].token).or(prev),
1188        )? {
1189            let span = location.span_to(state.location());
1190            if !matches!(token, Token::Whitespace(_)) {
1191                prev_non_ws = Some(rest.len());
1192            }
1193            rest.push(TokenWithSpan { token, span });
1194            location = state.location();
1195            if matches!(
1196                rest.last().map(|t| &t.token),
1197                Some(&Token::Whitespace(Whitespace::Newline))
1198            ) {
1199                break;
1200            }
1201        }
1202        let data_start = state.location();
1203        let (data, terminated) = self.read_copy_data(state);
1204        let payload = if data.is_empty() && !terminated {
1205            None
1206        } else {
1207            Some((data, terminated, data_start.span_to(state.location())))
1208        };
1209        Ok((payload, rest))
1210    }
1211
1212    /// Read the raw payload from `state` (at the start of a line) up to a
1213    /// line holding only `\.` (the terminator, which is consumed) or end of
1214    /// input.
1215    fn read_copy_data(&self, state: &mut State) -> (String, bool) {
1216        let mut data = String::new();
1217        loop {
1218            let mut line = String::new();
1219            while let Some(&ch) = state.peek() {
1220                if ch == '\n' || ch == '\r' {
1221                    break;
1222                }
1223                line.push(ch);
1224                state.next();
1225            }
1226            if line == "\\." {
1227                // A final terminator without a line end still terminates.
1228                if state.peek() == Some(&'\r') {
1229                    state.next();
1230                }
1231                if state.peek() == Some(&'\n') {
1232                    state.next();
1233                }
1234                return (data, true);
1235            }
1236            data.push_str(&line);
1237            if state.peek() == Some(&'\n') {
1238                data.push('\n');
1239                state.next();
1240            } else if state.peek() == Some(&'\r') {
1241                data.push('\r');
1242                state.next();
1243                if state.peek() == Some(&'\n') {
1244                    data.push('\n');
1245                    state.next();
1246                }
1247            } else {
1248                return (data, false);
1249            }
1250        }
1251    }
1252
1253    // Tokenize the identifier or keywords in `ch`
1254    fn tokenize_identifier_or_keyword(
1255        &self,
1256        ch: impl IntoIterator<Item = char>,
1257        chars: &mut State,
1258    ) -> Result<Option<Token>, TokenizerError> {
1259        chars.next(); // consume the first char
1260        let ch: String = ch.into_iter().collect();
1261        let word = self.tokenize_word(ch, chars);
1262
1263        // TODO: implement parsing of exponent here
1264        if word.chars().all(|x| x.is_ascii_digit() || x == '.') {
1265            let mut inner_state = State {
1266                peekable: word.chars().peekable(),
1267                line: 0,
1268                col: 0,
1269            };
1270            let mut s = peeking_take_while(&mut inner_state, |ch| matches!(ch, '0'..='9' | '.'));
1271            let s2 = peeking_take_while(chars, |ch| matches!(ch, '0'..='9' | '.'));
1272            s += s2.as_str();
1273            return Ok(Some(Token::Number(s, false)));
1274        }
1275
1276        Ok(Some(Token::make_word_owned(word, None)))
1277    }
1278
1279    /// Get the next token or return None
1280    fn next_token(
1281        &self,
1282        chars: &mut State,
1283        prev_token: Option<&Token>,
1284        prev_non_ws_token: Option<&Token>,
1285    ) -> Result<Option<Token>, TokenizerError> {
1286        match chars.peek() {
1287            Some(&ch) => match ch {
1288                ch if prev_token == Some(&Token::Period)
1289                    && ch.is_ascii_alphabetic()
1290                    && self.dialect.supports_literal_prefix_in_qualified_name() =>
1291                {
1292                    self.tokenize_identifier_or_keyword([ch], chars)
1293                }
1294                ' ' => self.consume_and_return(chars, Token::Whitespace(Whitespace::Space)),
1295                '\t' => self.consume_and_return(chars, Token::Whitespace(Whitespace::Tab)),
1296                '\n' => self.consume_and_return(chars, Token::Whitespace(Whitespace::Newline)),
1297                '\r' => {
1298                    // Emit a single Whitespace::Newline token for \r and \r\n
1299                    chars.next();
1300                    if let Some('\n') = chars.peek() {
1301                        chars.next();
1302                    }
1303                    Ok(Some(Token::Whitespace(Whitespace::Newline)))
1304                }
1305                // BigQuery and MySQL use b or B for byte string literal, Postgres for bit strings
1306                b @ 'B' | b @ 'b' if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | MySqlDialect | GenericDialect) =>
1307                {
1308                    chars.next(); // consume
1309                    match chars.peek() {
1310                        Some('\'') => {
1311                            if self.dialect.supports_triple_quoted_string() {
1312                                return self
1313                                    .tokenize_single_or_triple_quoted_string::<fn(String) -> Token>(
1314                                        chars,
1315                                        '\'',
1316                                        false,
1317                                        Token::SingleQuotedByteStringLiteral,
1318                                        Token::TripleSingleQuotedByteStringLiteral,
1319                                    );
1320                            }
1321                            let s = self.tokenize_single_quoted_string(chars, '\'', false)?;
1322                            Ok(Some(Token::SingleQuotedByteStringLiteral(s)))
1323                        }
1324                        Some('\"') => {
1325                            if self.dialect.supports_triple_quoted_string() {
1326                                return self
1327                                    .tokenize_single_or_triple_quoted_string::<fn(String) -> Token>(
1328                                        chars,
1329                                        '"',
1330                                        false,
1331                                        Token::DoubleQuotedByteStringLiteral,
1332                                        Token::TripleDoubleQuotedByteStringLiteral,
1333                                    );
1334                            }
1335                            let s = self.tokenize_single_quoted_string(chars, '\"', false)?;
1336                            Ok(Some(Token::DoubleQuotedByteStringLiteral(s)))
1337                        }
1338                        _ => {
1339                            // regular identifier starting with an "b" or "B"
1340                            let s = self.tokenize_word(b, chars);
1341                            Ok(Some(Token::make_word_owned(s, None)))
1342                        }
1343                    }
1344                }
1345                // BigQuery uses r or R for raw string literal
1346                b @ 'R' | b @ 'r' if dialect_of!(self is BigQueryDialect | GenericDialect) => {
1347                    chars.next(); // consume
1348                    match chars.peek() {
1349                        Some('\'') => self
1350                            .tokenize_single_or_triple_quoted_string::<fn(String) -> Token>(
1351                                chars,
1352                                '\'',
1353                                false,
1354                                Token::SingleQuotedRawStringLiteral,
1355                                Token::TripleSingleQuotedRawStringLiteral,
1356                            ),
1357                        Some('\"') => self
1358                            .tokenize_single_or_triple_quoted_string::<fn(String) -> Token>(
1359                                chars,
1360                                '"',
1361                                false,
1362                                Token::DoubleQuotedRawStringLiteral,
1363                                Token::TripleDoubleQuotedRawStringLiteral,
1364                            ),
1365                        _ => {
1366                            // regular identifier starting with an "r" or "R"
1367                            let s = self.tokenize_word(b, chars);
1368                            Ok(Some(Token::make_word_owned(s, None)))
1369                        }
1370                    }
1371                }
1372                // Redshift uses lower case n for national string literal
1373                n @ 'N' | n @ 'n' => {
1374                    chars.next(); // consume, to check the next char
1375                    match chars.peek() {
1376                        Some('\'') if self.dialect.supports_national_string_literal() => {
1377                            // N'...' - a <national character string literal>
1378                            let backslash_escape =
1379                                self.dialect.supports_string_literal_backslash_escape();
1380                            let s =
1381                                self.tokenize_single_quoted_string(chars, '\'', backslash_escape)?;
1382                            Ok(Some(Token::NationalStringLiteral(s)))
1383                        }
1384                        Some(&q @ 'q') | Some(&q @ 'Q')
1385                            if self.dialect.supports_quote_delimited_string() =>
1386                        {
1387                            chars.next(); // consume and check the next char
1388                            if let Some('\'') = chars.peek() {
1389                                self.tokenize_quote_delimited_string(chars, &[n, q])
1390                                    .map(|s| Some(Token::NationalQuoteDelimitedStringLiteral(s)))
1391                            } else {
1392                                let s = self.tokenize_word(String::from_iter([n, q]), chars);
1393                                Ok(Some(Token::make_word_owned(s, None)))
1394                            }
1395                        }
1396                        _ => {
1397                            // regular identifier starting with an "N"
1398                            let s = self.tokenize_word(n, chars);
1399                            Ok(Some(Token::make_word_owned(s, None)))
1400                        }
1401                    }
1402                }
1403                q @ 'Q' | q @ 'q' if self.dialect.supports_quote_delimited_string() => {
1404                    chars.next(); // consume and check the next char
1405                    if let Some('\'') = chars.peek() {
1406                        self.tokenize_quote_delimited_string(chars, &[q])
1407                            .map(|s| Some(Token::QuoteDelimitedStringLiteral(s)))
1408                    } else {
1409                        let s = self.tokenize_word(q, chars);
1410                        Ok(Some(Token::make_word_owned(s, None)))
1411                    }
1412                }
1413                // PostgreSQL accepts "escape" string constants, which are an extension to the SQL standard.
1414                x @ 'e' | x @ 'E' if self.dialect.supports_string_escape_constant() => {
1415                    let starting_loc = chars.location();
1416                    chars.next(); // consume, to check the next char
1417                    match chars.peek() {
1418                        Some('\'') => {
1419                            let s =
1420                                self.tokenize_escaped_single_quoted_string(starting_loc, chars)?;
1421                            Ok(Some(Token::EscapedStringLiteral(s)))
1422                        }
1423                        _ => {
1424                            // regular identifier starting with an "E" or "e"
1425                            let s = self.tokenize_word(x, chars);
1426                            Ok(Some(Token::make_word_owned(s, None)))
1427                        }
1428                    }
1429                }
1430                // Unicode string literals like U&'first \000A second' are supported in some dialects, including PostgreSQL
1431                x @ 'u' | x @ 'U' if self.dialect.supports_unicode_string_literal() => {
1432                    chars.next(); // consume, to check the next char
1433                    if chars.peek() == Some(&'&') {
1434                        // we cannot advance the iterator here, as we need to consume the '&' later if the 'u' was an identifier
1435                        let mut chars_clone = chars.peekable.clone();
1436                        chars_clone.next(); // consume the '&' in the clone
1437                        if chars_clone.peek() == Some(&'\'') {
1438                            chars.next(); // consume the '&' in the original iterator
1439                            let s = unescape_unicode_single_quoted_string(chars)?;
1440                            return Ok(Some(Token::UnicodeStringLiteral(s)));
1441                        }
1442                    }
1443                    // regular identifier starting with an "U" or "u"
1444                    let s = self.tokenize_word(x, chars);
1445                    Ok(Some(Token::make_word_owned(s, None)))
1446                }
1447                // The spec only allows an uppercase 'X' to introduce a hex
1448                // string, but PostgreSQL, at least, allows a lowercase 'x' too.
1449                x @ 'x' | x @ 'X' => {
1450                    chars.next(); // consume, to check the next char
1451                    match chars.peek() {
1452                        Some('\'') => {
1453                            // X'...' - a <binary string literal>
1454                            let s = self.tokenize_single_quoted_string(chars, '\'', true)?;
1455                            Ok(Some(Token::HexStringLiteral(s)))
1456                        }
1457                        _ => {
1458                            // regular identifier starting with an "X"
1459                            let s = self.tokenize_word(x, chars);
1460                            Ok(Some(Token::make_word_owned(s, None)))
1461                        }
1462                    }
1463                }
1464                // single quoted string
1465                '\'' => {
1466                    if self.dialect.supports_triple_quoted_string() {
1467                        return self
1468                            .tokenize_single_or_triple_quoted_string::<fn(String) -> Token>(
1469                                chars,
1470                                '\'',
1471                                self.dialect.supports_string_literal_backslash_escape(),
1472                                Token::SingleQuotedString,
1473                                Token::TripleSingleQuotedString,
1474                            );
1475                    }
1476                    let s = self.tokenize_single_quoted_string(
1477                        chars,
1478                        '\'',
1479                        self.dialect.supports_string_literal_backslash_escape(),
1480                    )?;
1481
1482                    Ok(Some(Token::SingleQuotedString(s)))
1483                }
1484                // double quoted string
1485                '\"' if !self.dialect.is_delimited_identifier_start(ch)
1486                    && !self.dialect.is_identifier_start(ch) =>
1487                {
1488                    if self.dialect.supports_triple_quoted_string() {
1489                        return self
1490                            .tokenize_single_or_triple_quoted_string::<fn(String) -> Token>(
1491                                chars,
1492                                '"',
1493                                self.dialect.supports_string_literal_backslash_escape(),
1494                                Token::DoubleQuotedString,
1495                                Token::TripleDoubleQuotedString,
1496                            );
1497                    }
1498                    let s = self.tokenize_single_quoted_string(
1499                        chars,
1500                        '"',
1501                        self.dialect.supports_string_literal_backslash_escape(),
1502                    )?;
1503
1504                    Ok(Some(Token::DoubleQuotedString(s)))
1505                }
1506                // delimited (quoted) identifier
1507                quote_start if self.dialect.is_delimited_identifier_start(ch) => {
1508                    let word = self.tokenize_quoted_identifier(quote_start, chars)?;
1509                    Ok(Some(Token::make_word_owned(word, Some(quote_start))))
1510                }
1511                // Potentially nested delimited (quoted) identifier
1512                quote_start
1513                    if self
1514                        .dialect
1515                        .is_nested_delimited_identifier_start(quote_start)
1516                        && self
1517                            .dialect
1518                            .peek_nested_delimited_identifier_quotes(chars.peekable.clone())
1519                            .is_some() =>
1520                {
1521                    let Some((quote_start, nested_quote_start)) = self
1522                        .dialect
1523                        .peek_nested_delimited_identifier_quotes(chars.peekable.clone())
1524                    else {
1525                        return self.tokenizer_error(
1526                            chars.location(),
1527                            format!("Expected nested delimiter '{quote_start}' before EOF."),
1528                        );
1529                    };
1530
1531                    let Some(nested_quote_start) = nested_quote_start else {
1532                        let word = self.tokenize_quoted_identifier(quote_start, chars)?;
1533                        return Ok(Some(Token::make_word_owned(word, Some(quote_start))));
1534                    };
1535
1536                    let mut word = vec![];
1537                    let quote_end = Word::matching_end_quote(quote_start);
1538                    let nested_quote_end = Word::matching_end_quote(nested_quote_start);
1539                    let error_loc = chars.location();
1540
1541                    chars.next(); // skip the first delimiter
1542                    peeking_take_while(chars, |ch| ch.is_whitespace());
1543                    if chars.peek() != Some(&nested_quote_start) {
1544                        return self.tokenizer_error(
1545                            error_loc,
1546                            format!("Expected nested delimiter '{nested_quote_start}' before EOF."),
1547                        );
1548                    }
1549                    word.push(nested_quote_start.into());
1550                    word.push(self.tokenize_quoted_identifier(nested_quote_end, chars)?);
1551                    word.push(nested_quote_end.into());
1552                    peeking_take_while(chars, |ch| ch.is_whitespace());
1553                    if chars.peek() != Some(&quote_end) {
1554                        return self.tokenizer_error(
1555                            error_loc,
1556                            format!("Expected close delimiter '{quote_end}' before EOF."),
1557                        );
1558                    }
1559                    chars.next(); // skip close delimiter
1560
1561                    Ok(Some(Token::make_word_owned(
1562                        word.concat(),
1563                        Some(quote_start),
1564                    )))
1565                }
1566                // numbers and period
1567                '0'..='9' | '.' => {
1568                    // ._ after a word is a field access, not a decimal point
1569                    if ch == '.' && chars.peekable.clone().nth(1) == Some('_') {
1570                        if let Some(Token::Word(_)) = prev_non_ws_token {
1571                            chars.next();
1572                            return Ok(Some(Token::Period));
1573                        }
1574
1575                        return self.tokenizer_error(
1576                            chars.location(),
1577                            "Unexpected character '_'".to_string(),
1578                        );
1579                    }
1580
1581                    // A period directly after an identifier, `)`, `]` or a tuple index
1582                    // starts a field access such as `t.1`, `(1, 2).1` or `t.1.2`, never a float.
1583                    if ch == '.'
1584                        && self.dialect.supports_tuple_element_access()
1585                        && matches!(
1586                            prev_token,
1587                            Some(
1588                                Token::Word(_)
1589                                    | Token::RParen
1590                                    | Token::RBracket
1591                                    | Token::Number(..)
1592                            )
1593                        )
1594                    {
1595                        chars.next();
1596                        return Ok(Some(Token::Period));
1597                    }
1598
1599                    let mut s = self.tokenize_number_part(chars, |ch| ch.is_ascii_digit())?;
1600
1601                    // A tuple index is an integer, so `t.1.2` is `(t.1).2`.
1602                    if !s.is_empty()
1603                        && self.dialect.supports_tuple_element_access()
1604                        && prev_token == Some(&Token::Period)
1605                    {
1606                        return Ok(Some(Token::Number(s, false)));
1607                    }
1608
1609                    if s == "0" && self.dialect.supports_non_decimal_integer_literals() {
1610                        let radix = match chars.peek() {
1611                            Some('x' | 'X') => Some((16, "a hexadecimal")),
1612                            Some('o' | 'O') => Some((8, "an octal")),
1613                            Some('b' | 'B') => Some((2, "a binary")),
1614                            _ => None,
1615                        };
1616                        if let Some((radix, name)) = radix {
1617                            return self
1618                                .tokenize_non_decimal_integer(chars, radix, name)
1619                                .map(Some);
1620                        }
1621                    }
1622
1623                    // match binary literal that starts with 0x
1624                    if s == "0" && chars.peek() == Some(&'x') {
1625                        chars.next();
1626                        let s2 = self.tokenize_number_part(chars, |ch| ch.is_ascii_hexdigit())?;
1627                        return Ok(Some(Token::HexStringLiteral(s2)));
1628                    }
1629
1630                    // match one period
1631                    if let Some('.') = chars.peek() {
1632                        s.push('.');
1633                        chars.next();
1634                    }
1635
1636                    // If the dialect supports identifiers that start with a numeric prefix
1637                    // and we have now consumed a dot, check if the previous token was a Word.
1638                    // If so, what follows is definitely not part of a decimal number and
1639                    // we should yield the dot as a dedicated token so compound identifiers
1640                    // starting with digits can be parsed correctly.
1641                    if s == "." && self.dialect.supports_numeric_prefix() {
1642                        if let Some(Token::Word(_)) = prev_token {
1643                            return Ok(Some(Token::Period));
1644                        }
1645                    }
1646
1647                    // Consume fractional digits.
1648                    s += &self.tokenize_number_part(chars, |ch| ch.is_ascii_digit())?;
1649
1650                    // No fraction -> Token::Period
1651                    if s == "." {
1652                        return Ok(Some(Token::Period));
1653                    }
1654
1655                    // Parse exponent as number
1656                    let mut exponent_part = String::new();
1657                    if chars.peek() == Some(&'e') || chars.peek() == Some(&'E') {
1658                        let mut char_clone = chars.peekable.clone();
1659                        exponent_part.push(char_clone.next().unwrap());
1660
1661                        // Optional sign
1662                        match char_clone.peek() {
1663                            Some(&c) if matches!(c, '+' | '-') => {
1664                                exponent_part.push(c);
1665                                char_clone.next();
1666                            }
1667                            _ => (),
1668                        }
1669
1670                        match char_clone.peek() {
1671                            // Definitely an exponent, get original iterator up to speed and use it
1672                            Some(&c)
1673                                if c.is_ascii_digit()
1674                                    || (c == '_'
1675                                        && self.dialect.supports_numeric_literal_underscores()) =>
1676                            {
1677                                for _ in 0..exponent_part.len() {
1678                                    chars.next();
1679                                }
1680                                exponent_part +=
1681                                    &self.tokenize_number_part(chars, |ch| ch.is_ascii_digit())?;
1682                                s += exponent_part.as_str();
1683                            }
1684                            // Not an exponent, discard the work done
1685                            _ => (),
1686                        }
1687                    }
1688
1689                    // If the dialect supports identifiers that start with a numeric prefix,
1690                    // we need to check if the value is in fact an identifier and must thus
1691                    // be tokenized as a word.
1692                    if self.dialect.supports_numeric_prefix() {
1693                        if exponent_part.is_empty() {
1694                            // If it is not a number with an exponent, it may be
1695                            // an identifier starting with digits.
1696                            let word =
1697                                peeking_take_while(chars, |ch| self.dialect.is_identifier_part(ch));
1698
1699                            if !word.is_empty() {
1700                                s += word.as_str();
1701                                return Ok(Some(Token::make_word_owned(s, None)));
1702                            }
1703                        } else if prev_token == Some(&Token::Period) {
1704                            // If the previous token was a period, thus not belonging to a number,
1705                            // the value we have is part of an identifier.
1706                            return Ok(Some(Token::make_word_owned(s, None)));
1707                        }
1708                    }
1709
1710                    let long = if chars.peek() == Some(&'L') {
1711                        chars.next();
1712                        true
1713                    } else {
1714                        false
1715                    };
1716                    Ok(Some(Token::Number(s, long)))
1717                }
1718                // punctuation
1719                '(' => self.consume_and_return(chars, Token::LParen),
1720                ')' => self.consume_and_return(chars, Token::RParen),
1721                ',' => self.consume_and_return(chars, Token::Comma),
1722                // operators
1723                '-' => {
1724                    chars.next(); // consume the '-'
1725
1726                    match chars.peek() {
1727                        Some('-') => {
1728                            let mut is_comment = true;
1729                            if self.dialect.requires_single_line_comment_whitespace() {
1730                                is_comment = chars
1731                                    .peekable
1732                                    .clone()
1733                                    .nth(1)
1734                                    .is_some_and(char::is_whitespace);
1735                            }
1736
1737                            if is_comment {
1738                                chars.next(); // consume second '-'
1739                                let comment = self.tokenize_single_line_comment(chars);
1740                                return Ok(Some(Token::Whitespace(
1741                                    Whitespace::SingleLineComment {
1742                                        prefix: "--".to_owned(),
1743                                        comment,
1744                                    },
1745                                )));
1746                            }
1747
1748                            self.start_binop(chars, "-", Token::Minus)
1749                        }
1750                        Some('>') => {
1751                            chars.next();
1752                            match chars.peek() {
1753                                Some('>') => self.consume_for_binop(chars, "->>", Token::LongArrow),
1754                                _ => self.start_binop(chars, "->", Token::Arrow),
1755                            }
1756                        }
1757                        // a regular '-' operator
1758                        _ => self.start_binop(chars, "-", Token::Minus),
1759                    }
1760                }
1761                '/' => {
1762                    chars.next(); // consume the '/'
1763                    match chars.peek() {
1764                        Some('*') => {
1765                            chars.next(); // consume the '*', starting a multi-line comment
1766                            self.tokenize_multiline_comment(chars)
1767                        }
1768                        Some('/') if dialect_of!(self is SnowflakeDialect) => {
1769                            chars.next(); // consume the second '/', starting a snowflake single-line comment
1770                            let comment = self.tokenize_single_line_comment(chars);
1771                            Ok(Some(Token::Whitespace(Whitespace::SingleLineComment {
1772                                prefix: "//".to_owned(),
1773                                comment,
1774                            })))
1775                        }
1776                        Some('/') if dialect_of!(self is DuckDbDialect | GenericDialect) => {
1777                            self.consume_and_return(chars, Token::DuckIntDiv)
1778                        }
1779                        // a regular '/' operator
1780                        _ => Ok(Some(Token::Div)),
1781                    }
1782                }
1783                '+' => self.consume_and_return(chars, Token::Plus),
1784                '*' => self.consume_and_return(chars, Token::Mul),
1785                '%' => {
1786                    chars.next(); // advance past '%'
1787                    match chars.peek() {
1788                        Some(s) if s.is_whitespace() => Ok(Some(Token::Mod)),
1789                        Some(sch) if self.dialect.is_identifier_start('%') => {
1790                            self.tokenize_identifier_or_keyword([ch, *sch], chars)
1791                        }
1792                        _ => self.start_binop(chars, "%", Token::Mod),
1793                    }
1794                }
1795                '|' => {
1796                    chars.next(); // consume the '|'
1797                    match chars.peek() {
1798                        Some('/') => self.consume_for_binop(chars, "|/", Token::PGSquareRoot),
1799                        Some('|') => {
1800                            chars.next(); // consume the second '|'
1801                            match chars.peek() {
1802                                Some('/') => {
1803                                    self.consume_for_binop(chars, "||/", Token::PGCubeRoot)
1804                                }
1805                                _ => self.start_binop(chars, "||", Token::StringConcat),
1806                            }
1807                        }
1808                        Some('&') if self.dialect.supports_geometric_types() => {
1809                            chars.next(); // consume
1810                            match chars.peek() {
1811                                Some('>') => self.consume_for_binop(
1812                                    chars,
1813                                    "|&>",
1814                                    Token::VerticalBarAmpersandRightAngleBracket,
1815                                ),
1816                                _ => self.start_binop_opt(chars, "|&", None),
1817                            }
1818                        }
1819                        Some('>') if self.dialect.supports_geometric_types() => {
1820                            chars.next(); // consume
1821                            match chars.peek() {
1822                                Some('>') => self.consume_for_binop(
1823                                    chars,
1824                                    "|>>",
1825                                    Token::VerticalBarShiftRight,
1826                                ),
1827                                _ => self.start_binop_opt(chars, "|>", None),
1828                            }
1829                        }
1830                        Some('>') if self.dialect.supports_pipe_operator() => {
1831                            self.consume_for_binop(chars, "|>", Token::VerticalBarRightAngleBracket)
1832                        }
1833                        // Bitshift '|' operator
1834                        _ => self.start_binop(chars, "|", Token::Pipe),
1835                    }
1836                }
1837                '=' => {
1838                    chars.next(); // consume
1839                    match chars.peek() {
1840                        Some('>') => self.consume_and_return(chars, Token::RArrow),
1841                        Some('=') => self.consume_and_return(chars, Token::DoubleEq),
1842                        _ => Ok(Some(Token::Eq)),
1843                    }
1844                }
1845                '!' => {
1846                    chars.next(); // consume
1847                    match chars.peek() {
1848                        Some('=') => self.consume_and_return(chars, Token::Neq),
1849                        Some('!') => self.consume_and_return(chars, Token::DoubleExclamationMark),
1850                        Some('~') => {
1851                            chars.next();
1852                            match chars.peek() {
1853                                Some('*') => self
1854                                    .consume_and_return(chars, Token::ExclamationMarkTildeAsterisk),
1855                                Some('~') if self.dialect.supports_tilde_like_match_operator() => {
1856                                    chars.next();
1857                                    match chars.peek() {
1858                                        Some('*') => self.consume_and_return(
1859                                            chars,
1860                                            Token::ExclamationMarkDoubleTildeAsterisk,
1861                                        ),
1862                                        _ => Ok(Some(Token::ExclamationMarkDoubleTilde)),
1863                                    }
1864                                }
1865                                _ => Ok(Some(Token::ExclamationMarkTilde)),
1866                            }
1867                        }
1868                        _ => Ok(Some(Token::ExclamationMark)),
1869                    }
1870                }
1871                '<' => {
1872                    chars.next(); // consume
1873                    match chars.peek() {
1874                        Some('=') => {
1875                            chars.next();
1876                            match chars.peek() {
1877                                Some('>') => self.consume_for_binop(chars, "<=>", Token::Spaceship),
1878                                // `<=+` and `<=-` are not valid combined operators; treat `<=` as
1879                                // the operator and leave `+`/`-` to be tokenized separately.
1880                                Some('+') | Some('-') => Ok(Some(Token::LtEq)),
1881                                _ => self.start_binop(chars, "<=", Token::LtEq),
1882                            }
1883                        }
1884                        Some('|') if self.dialect.supports_geometric_types() => {
1885                            self.consume_for_binop(chars, "<<|", Token::ShiftLeftVerticalBar)
1886                        }
1887                        Some('>') => self.consume_for_binop(chars, "<>", Token::Neq),
1888                        Some('<') if self.dialect.supports_geometric_types() => {
1889                            chars.next(); // consume
1890                            match chars.peek() {
1891                                Some('|') => self.consume_for_binop(
1892                                    chars,
1893                                    "<<|",
1894                                    Token::ShiftLeftVerticalBar,
1895                                ),
1896                                _ => self.start_binop(chars, "<<", Token::ShiftLeft),
1897                            }
1898                        }
1899                        Some('<') => self.consume_for_binop(chars, "<<", Token::ShiftLeft),
1900                        // `<+` is not a valid combined operator; treat `<` as the operator
1901                        // and leave `+` to be tokenized separately.
1902                        Some('+') => Ok(Some(Token::Lt)),
1903                        Some('-') if self.dialect.supports_geometric_types() => {
1904                            if chars.peekable.clone().nth(1) == Some('>') {
1905                                chars.next(); // consume `-`
1906                                self.consume_for_binop(chars, "<->", Token::TwoWayArrow)
1907                            } else {
1908                                Ok(Some(Token::Lt))
1909                            }
1910                        }
1911                        Some('^') if self.dialect.supports_geometric_types() => {
1912                            self.consume_for_binop(chars, "<^", Token::LeftAngleBracketCaret)
1913                        }
1914                        Some('@') => self.consume_for_binop(chars, "<@", Token::ArrowAt),
1915                        _ => self.start_binop(chars, "<", Token::Lt),
1916                    }
1917                }
1918                '>' => {
1919                    chars.next(); // consume
1920                    match chars.peek() {
1921                        Some('=') => self.consume_for_binop(chars, ">=", Token::GtEq),
1922                        Some('>') => self.consume_for_binop(chars, ">>", Token::ShiftRight),
1923                        Some('^') if self.dialect.supports_geometric_types() => {
1924                            self.consume_for_binop(chars, ">^", Token::RightAngleBracketCaret)
1925                        }
1926                        _ => self.start_binop(chars, ">", Token::Gt),
1927                    }
1928                }
1929                ':' => {
1930                    chars.next();
1931                    match chars.peek() {
1932                        Some(':') => self.consume_and_return(chars, Token::DoubleColon),
1933                        Some('=') => self.consume_and_return(chars, Token::Assignment),
1934                        _ => Ok(Some(Token::Colon)),
1935                    }
1936                }
1937                ';' => self.consume_and_return(chars, Token::SemiColon),
1938                '\\' => self.consume_and_return(chars, Token::Backslash),
1939                '[' => self.consume_and_return(chars, Token::LBracket),
1940                ']' => self.consume_and_return(chars, Token::RBracket),
1941                '&' => {
1942                    chars.next(); // consume the '&'
1943                    match chars.peek() {
1944                        Some('>') if self.dialect.supports_geometric_types() => {
1945                            chars.next();
1946                            self.consume_and_return(chars, Token::AmpersandRightAngleBracket)
1947                        }
1948                        Some('<') if self.dialect.supports_geometric_types() => {
1949                            chars.next(); // consume
1950                            match chars.peek() {
1951                                Some('|') => self.consume_and_return(
1952                                    chars,
1953                                    Token::AmpersandLeftAngleBracketVerticalBar,
1954                                ),
1955                                _ => {
1956                                    self.start_binop(chars, "&<", Token::AmpersandLeftAngleBracket)
1957                                }
1958                            }
1959                        }
1960                        Some('&') => {
1961                            chars.next(); // consume the second '&'
1962                            self.start_binop(chars, "&&", Token::Overlap)
1963                        }
1964                        // Bitshift '&' operator
1965                        _ => self.start_binop(chars, "&", Token::Ampersand),
1966                    }
1967                }
1968                '^' => {
1969                    chars.next(); // consume the '^'
1970                    match chars.peek() {
1971                        Some('@') => self.consume_and_return(chars, Token::CaretAt),
1972                        _ => Ok(Some(Token::Caret)),
1973                    }
1974                }
1975                '{' => self.consume_and_return(chars, Token::LBrace),
1976                '}' => self.consume_and_return(chars, Token::RBrace),
1977                '#' if self.dialect.supports_hash_comment()
1978                    && (!self.dialect.requires_hash_comment_space()
1979                        || chars
1980                            .peekable
1981                            .clone()
1982                            .nth(1)
1983                            .is_some_and(|c| c == ' ' || c == '!')) =>
1984                {
1985                    chars.next(); // consume the '#', starting a single-line comment
1986                    let comment = self.tokenize_single_line_comment(chars);
1987                    Ok(Some(Token::Whitespace(Whitespace::SingleLineComment {
1988                        prefix: "#".to_owned(),
1989                        comment,
1990                    })))
1991                }
1992                '~' => {
1993                    chars.next(); // consume
1994                    match chars.peek() {
1995                        Some('*') => self.consume_for_binop(chars, "~*", Token::TildeAsterisk),
1996                        Some('=') if self.dialect.supports_geometric_types() => {
1997                            self.consume_for_binop(chars, "~=", Token::TildeEqual)
1998                        }
1999                        Some('~') if self.dialect.supports_tilde_like_match_operator() => {
2000                            chars.next();
2001                            match chars.peek() {
2002                                Some('*') => {
2003                                    self.consume_for_binop(chars, "~~*", Token::DoubleTildeAsterisk)
2004                                }
2005                                _ => self.start_binop(chars, "~~", Token::DoubleTilde),
2006                            }
2007                        }
2008                        _ => self.start_binop(chars, "~", Token::Tilde),
2009                    }
2010                }
2011                '#' => {
2012                    chars.next();
2013                    match chars.peek() {
2014                        Some('-') => self.consume_for_binop(chars, "#-", Token::HashMinus),
2015                        Some('>') => {
2016                            chars.next();
2017                            match chars.peek() {
2018                                Some('>') => {
2019                                    self.consume_for_binop(chars, "#>>", Token::HashLongArrow)
2020                                }
2021                                _ => self.start_binop(chars, "#>", Token::HashArrow),
2022                            }
2023                        }
2024                        Some(' ') => Ok(Some(Token::Sharp)),
2025                        Some('#') if self.dialect.supports_geometric_types() => {
2026                            self.consume_for_binop(chars, "##", Token::DoubleSharp)
2027                        }
2028                        Some(sch) if self.dialect.is_identifier_start('#') => {
2029                            self.tokenize_identifier_or_keyword([ch, *sch], chars)
2030                        }
2031                        _ => self.start_binop(chars, "#", Token::Sharp),
2032                    }
2033                }
2034                '@' => {
2035                    chars.next();
2036                    match chars.peek() {
2037                        Some('@') if self.dialect.supports_geometric_types() => {
2038                            self.consume_and_return(chars, Token::AtAt)
2039                        }
2040                        Some('-') if self.dialect.supports_geometric_types() => {
2041                            chars.next();
2042                            match chars.peek() {
2043                                Some('@') => self.consume_and_return(chars, Token::AtDashAt),
2044                                _ => self.start_binop_opt(chars, "@-", None),
2045                            }
2046                        }
2047                        Some('>') => self.consume_and_return(chars, Token::AtArrow),
2048                        Some('?') => self.consume_and_return(chars, Token::AtQuestion),
2049                        Some('@') => {
2050                            chars.next();
2051                            match chars.peek() {
2052                                Some(' ') => Ok(Some(Token::AtAt)),
2053                                Some(tch) if self.dialect.is_identifier_start('@') => {
2054                                    self.tokenize_identifier_or_keyword([ch, '@', *tch], chars)
2055                                }
2056                                _ => Ok(Some(Token::AtAt)),
2057                            }
2058                        }
2059                        Some(' ') => Ok(Some(Token::AtSign)),
2060                        // We break on quotes here, because no dialect allows identifiers starting
2061                        // with @ and containing quotation marks (e.g. `@'foo'`) unless they are
2062                        // quoted, which is tokenized as a quoted string, not here (e.g.
2063                        // `"@'foo'"`). Further, at least two dialects parse `@` followed by a
2064                        // quoted string as two separate tokens, which this allows. For example,
2065                        // Postgres parses `@'1'` as the absolute value of '1' which is implicitly
2066                        // cast to a numeric type. And when parsing MySQL-style grantees (e.g.
2067                        // `GRANT ALL ON *.* to 'root'@'localhost'`), we also want separate tokens
2068                        // for the user, the `@`, and the host.
2069                        Some('\'') => Ok(Some(Token::AtSign)),
2070                        Some('\"') => Ok(Some(Token::AtSign)),
2071                        Some('`') => Ok(Some(Token::AtSign)),
2072                        Some(sch) if self.dialect.is_identifier_start('@') => {
2073                            self.tokenize_identifier_or_keyword([ch, *sch], chars)
2074                        }
2075                        _ => Ok(Some(Token::AtSign)),
2076                    }
2077                }
2078                // Postgres uses ? for jsonb operators, not prepared statements
2079                '?' if self.dialect.supports_geometric_types() => {
2080                    chars.next(); // consume
2081                    match chars.peek() {
2082                        Some('|') => {
2083                            chars.next();
2084                            match chars.peek() {
2085                                Some('|') => self.consume_and_return(
2086                                    chars,
2087                                    Token::QuestionMarkDoubleVerticalBar,
2088                                ),
2089                                _ => Ok(Some(Token::QuestionPipe)),
2090                            }
2091                        }
2092
2093                        Some('&') => self.consume_and_return(chars, Token::QuestionAnd),
2094                        Some('-') => {
2095                            chars.next(); // consume
2096                            match chars.peek() {
2097                                Some('|') => self
2098                                    .consume_and_return(chars, Token::QuestionMarkDashVerticalBar),
2099                                _ => Ok(Some(Token::QuestionMarkDash)),
2100                            }
2101                        }
2102                        Some('#') => self.consume_and_return(chars, Token::QuestionMarkSharp),
2103                        _ => Ok(Some(Token::Question)),
2104                    }
2105                }
2106                '?' => {
2107                    chars.next();
2108                    let s = peeking_take_while(chars, |ch| ch.is_numeric());
2109                    Ok(Some(Token::Placeholder(format!("?{s}"))))
2110                }
2111
2112                // identifier or keyword
2113                ch if self.dialect.is_identifier_start(ch) => {
2114                    self.tokenize_identifier_or_keyword([ch], chars)
2115                }
2116                '$' => Ok(Some(self.tokenize_dollar_preceded_value(chars)?)),
2117
2118                // whitespace check (including unicode chars) should be last as it covers some of the chars above
2119                ch if ch.is_whitespace() => {
2120                    self.consume_and_return(chars, Token::Whitespace(Whitespace::Space))
2121                }
2122                other => self.consume_and_return(chars, Token::Char(other)),
2123            },
2124            None => Ok(None),
2125        }
2126    }
2127
2128    /// Consume the next character, then parse a custom binary operator. The next character should be included in the prefix
2129    fn consume_for_binop(
2130        &self,
2131        chars: &mut State,
2132        prefix: &str,
2133        default: Token,
2134    ) -> Result<Option<Token>, TokenizerError> {
2135        chars.next(); // consume the first char
2136        self.start_binop_opt(chars, prefix, Some(default))
2137    }
2138
2139    /// parse a custom binary operator
2140    fn start_binop(
2141        &self,
2142        chars: &mut State,
2143        prefix: &str,
2144        default: Token,
2145    ) -> Result<Option<Token>, TokenizerError> {
2146        self.start_binop_opt(chars, prefix, Some(default))
2147    }
2148
2149    /// parse a custom binary operator
2150    fn start_binop_opt(
2151        &self,
2152        chars: &mut State,
2153        prefix: &str,
2154        default: Option<Token>,
2155    ) -> Result<Option<Token>, TokenizerError> {
2156        let mut custom = None;
2157        while let Some(&ch) = chars.peek() {
2158            if !self.dialect.is_custom_operator_part(ch) {
2159                break;
2160            }
2161
2162            custom.get_or_insert_with(|| prefix.to_string()).push(ch);
2163            chars.next();
2164        }
2165        match (custom, default) {
2166            (Some(custom), _) => Ok(Token::CustomBinaryOperator(custom).into()),
2167            (None, Some(tok)) => Ok(Some(tok)),
2168            (None, None) => self.tokenizer_error(
2169                chars.location(),
2170                format!("Expected a valid binary operator after '{prefix}'"),
2171            ),
2172        }
2173    }
2174
2175    /// Tokenize dollar preceded value (i.e: a string/placeholder)
2176    fn tokenize_dollar_preceded_value(&self, chars: &mut State) -> Result<Token, TokenizerError> {
2177        let mut s = String::new();
2178        let mut value = String::new();
2179
2180        chars.next();
2181
2182        // If the dialect does not support dollar-quoted strings, then `$$` is rather a placeholder.
2183        if matches!(chars.peek(), Some('$')) && !self.dialect.supports_dollar_placeholder() {
2184            chars.next();
2185
2186            let mut is_terminated = false;
2187            let mut prev: Option<char> = None;
2188
2189            while let Some(&ch) = chars.peek() {
2190                if prev == Some('$') {
2191                    if ch == '$' {
2192                        chars.next();
2193                        is_terminated = true;
2194                        break;
2195                    } else {
2196                        s.push('$');
2197                        s.push(ch);
2198                    }
2199                } else if ch != '$' {
2200                    s.push(ch);
2201                }
2202
2203                prev = Some(ch);
2204                chars.next();
2205            }
2206
2207            return if chars.peek().is_none() && !is_terminated {
2208                self.tokenizer_error(chars.location(), "Unterminated dollar-quoted string")
2209            } else {
2210                Ok(Token::DollarQuotedString(DollarQuotedString {
2211                    value: s,
2212                    tag: None,
2213                }))
2214            };
2215        } else {
2216            value.push_str(&peeking_take_while(chars, |ch| {
2217                ch.is_alphanumeric()
2218                    || ch == '_'
2219                    // Allow $ as a placeholder character if the dialect supports it
2220                    || matches!(ch, '$' if self.dialect.supports_dollar_placeholder())
2221            }));
2222
2223            // If the dialect supports a dollar sign as a money prefix (e.g. SQL Server),
2224            // and the value so far is all digits, check for a decimal part, e.g. `$123.45`
2225            if matches!(chars.peek(), Some('.'))
2226                && self.dialect.supports_dollar_as_money_prefix()
2227                && !value.is_empty()
2228                && value.chars().all(|c| c.is_ascii_digit())
2229            {
2230                value.push('.');
2231                chars.next();
2232                value.push_str(&peeking_take_while(chars, |ch| ch.is_ascii_digit()));
2233                return Ok(Token::Placeholder(format!("${value}")));
2234            }
2235
2236            // If the dialect does not support dollar-quoted strings, don't look for the end delimiter.
2237            if matches!(chars.peek(), Some('$')) && !self.dialect.supports_dollar_placeholder() {
2238                chars.next();
2239
2240                let mut temp = String::new();
2241                let end_delimiter = format!("${value}$");
2242
2243                loop {
2244                    match chars.next() {
2245                        Some(ch) => {
2246                            temp.push(ch);
2247
2248                            if temp.ends_with(&end_delimiter) {
2249                                if let Some(temp) = temp.strip_suffix(&end_delimiter) {
2250                                    s.push_str(temp);
2251                                }
2252                                break;
2253                            }
2254                        }
2255                        None => {
2256                            if temp.ends_with(&end_delimiter) {
2257                                if let Some(temp) = temp.strip_suffix(&end_delimiter) {
2258                                    s.push_str(temp);
2259                                }
2260                                break;
2261                            }
2262
2263                            return self.tokenizer_error(
2264                                chars.location(),
2265                                "Unterminated dollar-quoted, expected $",
2266                            );
2267                        }
2268                    }
2269                }
2270            } else {
2271                return Ok(Token::Placeholder(format!("${value}")));
2272            }
2273        }
2274
2275        Ok(Token::DollarQuotedString(DollarQuotedString {
2276            value: s,
2277            tag: if value.is_empty() { None } else { Some(value) },
2278        }))
2279    }
2280
2281    fn tokenizer_error<R>(
2282        &self,
2283        loc: Location,
2284        message: impl Into<String>,
2285    ) -> Result<R, TokenizerError> {
2286        Err(TokenizerError {
2287            message: message.into(),
2288            location: loc,
2289        })
2290    }
2291
2292    fn tokenize_number_part(
2293        &self,
2294        chars: &mut State,
2295        is_digit: impl Fn(char) -> bool,
2296    ) -> Result<String, TokenizerError> {
2297        let supports_separator = self.dialect.supports_numeric_literal_underscores();
2298        let mut s = String::new();
2299
2300        while let Some(&ch) = chars.peek() {
2301            if is_digit(ch) {
2302                chars.next();
2303                s.push(ch);
2304            } else if supports_separator && ch == '_' {
2305                let next_char = chars.peekable.clone().nth(1);
2306                if s.is_empty() || !next_char.is_some_and(&is_digit) {
2307                    return self.tokenizer_error(chars.location(), "Unexpected character '_'");
2308                }
2309                chars.next();
2310                s.push(ch);
2311            } else {
2312                break;
2313            }
2314        }
2315
2316        Ok(s)
2317    }
2318
2319    /// Tokenizes an integer literal such as `0x1F` after its leading `0`,
2320    /// keeping the spelling as written.
2321    fn tokenize_non_decimal_integer(
2322        &self,
2323        chars: &mut State,
2324        radix: u32,
2325        name: &str,
2326    ) -> Result<Token, TokenizerError> {
2327        let mut s = String::from('0');
2328        s.extend(chars.next());
2329        // An underscore may directly follow the prefix, as in `0x_1F`.
2330        if chars.peek() == Some(&'_') && self.dialect.supports_numeric_literal_underscores() {
2331            chars.next();
2332            s.push('_');
2333        }
2334        let digits = self.tokenize_number_part(chars, |ch| ch.is_digit(radix))?;
2335        if digits.is_empty() {
2336            return self.tokenizer_error(
2337                chars.location(),
2338                format!("Expected {name} digit after '{}'", &s[..2]),
2339            );
2340        }
2341        s.push_str(&digits);
2342        Ok(Token::Number(s, false))
2343    }
2344
2345    // Consume characters until newline
2346    fn tokenize_single_line_comment(&self, chars: &mut State) -> String {
2347        peeking_take_while(chars, |ch| match ch {
2348            '\n' => false,                                           // Always stop at \n
2349            '\r' if dialect_of!(self is PostgreSqlDialect) => false, // Stop at \r for Postgres
2350            _ => true, // Keep consuming for other characters
2351        })
2352    }
2353
2354    /// Tokenize an identifier or keyword, after the first char is already consumed.
2355    fn tokenize_word(&self, first_chars: impl Into<String>, chars: &mut State) -> String {
2356        let mut s = first_chars.into();
2357        s.push_str(&peeking_take_while(chars, |ch| {
2358            self.dialect.is_identifier_part(ch)
2359        }));
2360        s
2361    }
2362
2363    /// Read a quoted identifier
2364    fn tokenize_quoted_identifier(
2365        &self,
2366        quote_start: char,
2367        chars: &mut State,
2368    ) -> Result<String, TokenizerError> {
2369        let error_loc = chars.location();
2370        chars.next(); // consume the opening quote
2371        let quote_end = Word::matching_end_quote(quote_start);
2372        let (s, last_char) = self.parse_quoted_ident(chars, quote_end);
2373
2374        if last_char == Some(quote_end) {
2375            Ok(s)
2376        } else {
2377            self.tokenizer_error(
2378                error_loc,
2379                format!("Expected close delimiter '{quote_end}' before EOF."),
2380            )
2381        }
2382    }
2383
2384    /// Read a single quoted string, starting with the opening quote.
2385    fn tokenize_escaped_single_quoted_string(
2386        &self,
2387        starting_loc: Location,
2388        chars: &mut State,
2389    ) -> Result<String, TokenizerError> {
2390        if let Some(s) = unescape_single_quoted_string(chars) {
2391            return Ok(s);
2392        }
2393
2394        self.tokenizer_error(starting_loc, "Unterminated encoded string literal")
2395    }
2396
2397    /// Reads a string literal quoted by a single or triple quote characters.
2398    /// Examples: `'abc'`, `'''abc'''`, `"""abc"""`.
2399    fn tokenize_single_or_triple_quoted_string<F>(
2400        &self,
2401        chars: &mut State,
2402        quote_style: char,
2403        backslash_escape: bool,
2404        single_quote_token: F,
2405        triple_quote_token: F,
2406    ) -> Result<Option<Token>, TokenizerError>
2407    where
2408        F: Fn(String) -> Token,
2409    {
2410        let error_loc = chars.location();
2411
2412        let mut num_opening_quotes = 0u8;
2413        for _ in 0..3 {
2414            if Some(&quote_style) == chars.peek() {
2415                chars.next(); // Consume quote.
2416                num_opening_quotes += 1;
2417            } else {
2418                break;
2419            }
2420        }
2421
2422        let (token_fn, num_quote_chars) = match num_opening_quotes {
2423            1 => (single_quote_token, NumStringQuoteChars::One),
2424            2 => {
2425                // If we matched double quotes, then this is an empty string.
2426                return Ok(Some(single_quote_token("".into())));
2427            }
2428            3 => {
2429                let Some(num_quote_chars) = NonZeroU8::new(3) else {
2430                    return self.tokenizer_error(error_loc, "invalid number of opening quotes");
2431                };
2432                (
2433                    triple_quote_token,
2434                    NumStringQuoteChars::Many(num_quote_chars),
2435                )
2436            }
2437            _ => {
2438                return self.tokenizer_error(error_loc, "invalid string literal opening");
2439            }
2440        };
2441
2442        let settings = TokenizeQuotedStringSettings {
2443            quote_style,
2444            num_quote_chars,
2445            num_opening_quotes_to_consume: 0,
2446            backslash_escape,
2447        };
2448
2449        self.tokenize_quoted_string(chars, settings)
2450            .map(token_fn)
2451            .map(Some)
2452    }
2453
2454    /// Reads a string literal quoted by a single quote character.
2455    fn tokenize_single_quoted_string(
2456        &self,
2457        chars: &mut State,
2458        quote_style: char,
2459        backslash_escape: bool,
2460    ) -> Result<String, TokenizerError> {
2461        self.tokenize_quoted_string(
2462            chars,
2463            TokenizeQuotedStringSettings {
2464                quote_style,
2465                num_quote_chars: NumStringQuoteChars::One,
2466                num_opening_quotes_to_consume: 1,
2467                backslash_escape,
2468            },
2469        )
2470    }
2471
2472    /// Reads a quote delimited string expecting `chars.next()` to deliver a quote.
2473    ///
2474    /// See <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Literals.html#GUID-1824CBAA-6E16-4921-B2A6-112FB02248DA>
2475    fn tokenize_quote_delimited_string(
2476        &self,
2477        chars: &mut State,
2478        // the prefix that introduced the possible literal or word,
2479        // e.g. "Q" or "nq"
2480        literal_prefix: &[char],
2481    ) -> Result<QuoteDelimitedString, TokenizerError> {
2482        let literal_start_loc = chars.location();
2483        chars.next();
2484
2485        let start_quote_loc = chars.location();
2486        let (start_quote, end_quote) = match chars.next() {
2487            None | Some(' ') | Some('\t') | Some('\r') | Some('\n') => {
2488                return self.tokenizer_error(
2489                    start_quote_loc,
2490                    format!(
2491                        "Invalid space, tab, newline, or EOF after '{}''",
2492                        String::from_iter(literal_prefix)
2493                    ),
2494                );
2495            }
2496            Some(c) => (
2497                c,
2498                match c {
2499                    '[' => ']',
2500                    '{' => '}',
2501                    '<' => '>',
2502                    '(' => ')',
2503                    c => c,
2504                },
2505            ),
2506        };
2507
2508        // read the string literal until the "quote character" following a by literal quote
2509        let mut value = String::new();
2510        while let Some(ch) = chars.next() {
2511            if ch == end_quote {
2512                if let Some('\'') = chars.peek() {
2513                    chars.next(); // ~ consume the quote
2514                    return Ok(QuoteDelimitedString {
2515                        start_quote,
2516                        value,
2517                        end_quote,
2518                    });
2519                }
2520            }
2521            value.push(ch);
2522        }
2523
2524        self.tokenizer_error(literal_start_loc, "Unterminated string literal")
2525    }
2526
2527    /// Read a quoted string.
2528    fn tokenize_quoted_string(
2529        &self,
2530        chars: &mut State,
2531        settings: TokenizeQuotedStringSettings,
2532    ) -> Result<String, TokenizerError> {
2533        let mut s = String::new();
2534        let error_loc = chars.location();
2535
2536        // Consume any opening quotes.
2537        for _ in 0..settings.num_opening_quotes_to_consume {
2538            if Some(settings.quote_style) != chars.next() {
2539                return self.tokenizer_error(error_loc, "invalid string literal opening");
2540            }
2541        }
2542
2543        let mut num_consecutive_quotes = 0;
2544        while let Some(&ch) = chars.peek() {
2545            let pending_final_quote = match settings.num_quote_chars {
2546                NumStringQuoteChars::One => Some(NumStringQuoteChars::One),
2547                n @ NumStringQuoteChars::Many(count)
2548                    if num_consecutive_quotes + 1 == count.get() =>
2549                {
2550                    Some(n)
2551                }
2552                NumStringQuoteChars::Many(_) => None,
2553            };
2554
2555            match ch {
2556                char if char == settings.quote_style && pending_final_quote.is_some() => {
2557                    chars.next(); // consume
2558
2559                    if let Some(NumStringQuoteChars::Many(count)) = pending_final_quote {
2560                        // For an initial string like `"""abc"""`, at this point we have
2561                        // `abc""` in the buffer and have now matched the final `"`.
2562                        // However, the string to return is simply `abc`, so we strip off
2563                        // the trailing quotes before returning.
2564                        let mut buf = s.chars();
2565                        for _ in 1..count.get() {
2566                            buf.next_back();
2567                        }
2568                        return Ok(buf.as_str().to_string());
2569                    } else if chars
2570                        .peek()
2571                        .map(|c| *c == settings.quote_style)
2572                        .unwrap_or(false)
2573                    {
2574                        s.push(ch);
2575                        if !self.unescape {
2576                            // In no-escape mode, the given query has to be saved completely
2577                            s.push(ch);
2578                        }
2579                        chars.next();
2580                    } else {
2581                        return Ok(s);
2582                    }
2583                }
2584                '\\' if settings.backslash_escape => {
2585                    // consume backslash
2586                    chars.next();
2587
2588                    num_consecutive_quotes = 0;
2589
2590                    if let Some(next) = chars.peek() {
2591                        if !self.unescape
2592                            || (self.dialect.ignores_wildcard_escapes()
2593                                && (*next == '%' || *next == '_'))
2594                        {
2595                            // In no-escape mode, the given query has to be saved completely
2596                            // including backslashes. Similarly, with ignore_like_wildcard_escapes,
2597                            // the backslash is not stripped.
2598                            s.push(ch);
2599                            s.push(*next);
2600                            chars.next(); // consume next
2601                        } else {
2602                            let n = match next {
2603                                '0' => '\0',
2604                                'a' => '\u{7}',
2605                                'b' => '\u{8}',
2606                                'f' => '\u{c}',
2607                                'n' => '\n',
2608                                'r' => '\r',
2609                                't' => '\t',
2610                                'Z' => '\u{1a}',
2611                                _ => *next,
2612                            };
2613                            s.push(n);
2614                            chars.next(); // consume next
2615                        }
2616                    }
2617                }
2618                ch => {
2619                    chars.next(); // consume ch
2620
2621                    if ch == settings.quote_style {
2622                        num_consecutive_quotes += 1;
2623                    } else {
2624                        num_consecutive_quotes = 0;
2625                    }
2626
2627                    s.push(ch);
2628                }
2629            }
2630        }
2631        self.tokenizer_error(error_loc, "Unterminated string literal")
2632    }
2633
2634    fn tokenize_multiline_comment(
2635        &self,
2636        chars: &mut State,
2637    ) -> Result<Option<Token>, TokenizerError> {
2638        let mut s = String::new();
2639        let mut nested = 1;
2640        let supports_nested_comments = self.dialect.supports_nested_comments();
2641        loop {
2642            match chars.next() {
2643                Some('/') if matches!(chars.peek(), Some('*')) && supports_nested_comments => {
2644                    chars.next(); // consume the '*'
2645                    s.push('/');
2646                    s.push('*');
2647                    nested += 1;
2648                }
2649                Some('*') if matches!(chars.peek(), Some('/')) => {
2650                    chars.next(); // consume the '/'
2651                    nested -= 1;
2652                    if nested == 0 {
2653                        break Ok(Some(Token::Whitespace(Whitespace::MultiLineComment(s))));
2654                    }
2655                    s.push('*');
2656                    s.push('/');
2657                }
2658                Some(ch) => {
2659                    s.push(ch);
2660                }
2661                None => {
2662                    if self.dialect.supports_unterminated_block_comments() {
2663                        break Ok(Some(Token::Whitespace(Whitespace::MultiLineComment(s))));
2664                    }
2665                    break self.tokenizer_error(
2666                        chars.location(),
2667                        "Unexpected EOF while in a multi-line comment",
2668                    );
2669                }
2670            }
2671        }
2672    }
2673
2674    fn parse_quoted_ident(&self, chars: &mut State, quote_end: char) -> (String, Option<char>) {
2675        let mut last_char = None;
2676        let mut s = String::new();
2677        while let Some(ch) = chars.next() {
2678            if ch == quote_end {
2679                if chars.peek() == Some(&quote_end) {
2680                    chars.next();
2681                    s.push(ch);
2682                    if !self.unescape {
2683                        // In no-escape mode, the given query has to be saved completely
2684                        s.push(ch);
2685                    }
2686                } else {
2687                    last_char = Some(quote_end);
2688                    break;
2689                }
2690            } else {
2691                s.push(ch);
2692            }
2693        }
2694        (s, last_char)
2695    }
2696
2697    #[expect(
2698        clippy::unnecessary_wraps,
2699        reason = "the match arms in `next_token` return this value directly"
2700    )]
2701    fn consume_and_return(
2702        &self,
2703        chars: &mut State,
2704        t: Token,
2705    ) -> Result<Option<Token>, TokenizerError> {
2706        chars.next();
2707        Ok(Some(t))
2708    }
2709}
2710
2711/// Read from `chars` until `predicate` returns `false` or EOF is hit.
2712/// Return the characters read as String, and keep the first non-matching
2713/// char available as `chars.next()`.
2714fn peeking_take_while(chars: &mut State, mut predicate: impl FnMut(char) -> bool) -> String {
2715    let mut s = String::new();
2716    while let Some(&ch) = chars.peek() {
2717        if predicate(ch) {
2718            chars.next(); // consume
2719            s.push(ch);
2720        } else {
2721            break;
2722        }
2723    }
2724    s
2725}
2726
2727fn unescape_single_quoted_string(chars: &mut State<'_>) -> Option<String> {
2728    Unescape::new(chars).unescape()
2729}
2730
2731struct Unescape<'a: 'b, 'b> {
2732    chars: &'b mut State<'a>,
2733}
2734
2735impl<'a: 'b, 'b> Unescape<'a, 'b> {
2736    fn new(chars: &'b mut State<'a>) -> Self {
2737        Self { chars }
2738    }
2739    fn unescape(mut self) -> Option<String> {
2740        let mut unescaped = String::new();
2741
2742        self.chars.next();
2743
2744        while let Some(c) = self.chars.next() {
2745            if c == '\'' {
2746                // case: ''''
2747                if self.chars.peek().map(|c| *c == '\'').unwrap_or(false) {
2748                    self.chars.next();
2749                    unescaped.push('\'');
2750                    continue;
2751                }
2752                return Some(unescaped);
2753            }
2754
2755            if c != '\\' {
2756                unescaped.push(c);
2757                continue;
2758            }
2759
2760            let c = match self.chars.next()? {
2761                'b' => '\u{0008}',
2762                'f' => '\u{000C}',
2763                'n' => '\n',
2764                'r' => '\r',
2765                't' => '\t',
2766                'u' => self.unescape_unicode_16()?,
2767                'U' => self.unescape_unicode_32()?,
2768                'x' => self.unescape_hex()?,
2769                c if c.is_digit(8) => self.unescape_octal(c)?,
2770                c => c,
2771            };
2772
2773            unescaped.push(Self::check_null(c)?);
2774        }
2775
2776        None
2777    }
2778
2779    #[inline]
2780    fn check_null(c: char) -> Option<char> {
2781        if c == '\0' {
2782            None
2783        } else {
2784            Some(c)
2785        }
2786    }
2787
2788    #[inline]
2789    fn byte_to_char<const RADIX: u32>(s: &str) -> Option<char> {
2790        // u32 is used here because Pg has an overflow operation rather than throwing an exception directly.
2791        match u32::from_str_radix(s, RADIX) {
2792            Err(_) => None,
2793            Ok(n) => {
2794                let n = n & 0xFF;
2795                if n <= 127 {
2796                    char::from_u32(n)
2797                } else {
2798                    None
2799                }
2800            }
2801        }
2802    }
2803
2804    // Hexadecimal byte value. \xh, \xhh (h = 0–9, A–F)
2805    fn unescape_hex(&mut self) -> Option<char> {
2806        let mut s = String::new();
2807
2808        for _ in 0..2 {
2809            match self.next_hex_digit() {
2810                Some(c) => s.push(c),
2811                None => break,
2812            }
2813        }
2814
2815        if s.is_empty() {
2816            return Some('x');
2817        }
2818
2819        Self::byte_to_char::<16>(&s)
2820    }
2821
2822    #[inline]
2823    fn next_hex_digit(&mut self) -> Option<char> {
2824        match self.chars.peek() {
2825            Some(c) if c.is_ascii_hexdigit() => self.chars.next(),
2826            _ => None,
2827        }
2828    }
2829
2830    // Octal byte value. \o, \oo, \ooo (o = 0–7)
2831    fn unescape_octal(&mut self, c: char) -> Option<char> {
2832        let mut s = String::new();
2833
2834        s.push(c);
2835        for _ in 0..2 {
2836            match self.next_octal_digest() {
2837                Some(c) => s.push(c),
2838                None => break,
2839            }
2840        }
2841
2842        Self::byte_to_char::<8>(&s)
2843    }
2844
2845    #[inline]
2846    fn next_octal_digest(&mut self) -> Option<char> {
2847        match self.chars.peek() {
2848            Some(c) if c.is_digit(8) => self.chars.next(),
2849            _ => None,
2850        }
2851    }
2852
2853    // 16-bit hexadecimal Unicode character value. \uxxxx (x = 0–9, A–F)
2854    fn unescape_unicode_16(&mut self) -> Option<char> {
2855        self.unescape_unicode::<4>()
2856    }
2857
2858    // 32-bit hexadecimal Unicode character value. \Uxxxxxxxx (x = 0–9, A–F)
2859    fn unescape_unicode_32(&mut self) -> Option<char> {
2860        self.unescape_unicode::<8>()
2861    }
2862
2863    fn unescape_unicode<const NUM: usize>(&mut self) -> Option<char> {
2864        let mut s = String::new();
2865        for _ in 0..NUM {
2866            s.push(self.chars.next()?);
2867        }
2868        match u32::from_str_radix(&s, 16) {
2869            Err(_) => None,
2870            Ok(n) => char::from_u32(n),
2871        }
2872    }
2873}
2874
2875fn unescape_unicode_single_quoted_string(chars: &mut State<'_>) -> Result<String, TokenizerError> {
2876    let mut unescaped = String::new();
2877    chars.next(); // consume the opening quote
2878    while let Some(c) = chars.next() {
2879        match c {
2880            '\'' => {
2881                if chars.peek() == Some(&'\'') {
2882                    chars.next();
2883                    unescaped.push('\'');
2884                } else {
2885                    return Ok(unescaped);
2886                }
2887            }
2888            '\\' => match chars.peek() {
2889                Some('\\') => {
2890                    chars.next();
2891                    unescaped.push('\\');
2892                }
2893                Some('+') => {
2894                    chars.next();
2895                    unescaped.push(take_char_from_hex_digits(chars, 6)?);
2896                }
2897                _ => unescaped.push(take_char_from_hex_digits(chars, 4)?),
2898            },
2899            _ => {
2900                unescaped.push(c);
2901            }
2902        }
2903    }
2904    Err(TokenizerError {
2905        message: "Unterminated unicode encoded string literal".to_string(),
2906        location: chars.location(),
2907    })
2908}
2909
2910fn take_char_from_hex_digits(
2911    chars: &mut State<'_>,
2912    max_digits: usize,
2913) -> Result<char, TokenizerError> {
2914    let mut result = 0u32;
2915    for _ in 0..max_digits {
2916        let next_char = chars.next().ok_or_else(|| TokenizerError {
2917            message: "Unexpected EOF while parsing hex digit in escaped unicode string."
2918                .to_string(),
2919            location: chars.location(),
2920        })?;
2921        let digit = next_char.to_digit(16).ok_or_else(|| TokenizerError {
2922            message: format!("Invalid hex digit in escaped unicode string: {next_char}"),
2923            location: chars.location(),
2924        })?;
2925        result = result * 16 + digit;
2926    }
2927    char::from_u32(result).ok_or_else(|| TokenizerError {
2928        message: format!("Invalid unicode character: {result:x}"),
2929        location: chars.location(),
2930    })
2931}
2932
2933#[cfg(test)]
2934mod tests {
2935    use super::*;
2936    use crate::dialect::{
2937        BigQueryDialect, ClickHouseDialect, HiveDialect, MsSqlDialect, MySqlDialect,
2938        PostgreSqlDialect, SQLiteDialect,
2939    };
2940    use crate::test_utils::{all_dialects, all_dialects_except, all_dialects_where};
2941    use core::fmt::Debug;
2942
2943    #[test]
2944    fn tokenizer_error_impl() {
2945        let err = TokenizerError {
2946            message: "test".into(),
2947            location: Location { line: 1, column: 1 },
2948        };
2949        {
2950            use core::error::Error;
2951            assert!(err.source().is_none());
2952        }
2953        assert_eq!(err.to_string(), "test at Line: 1, Column: 1");
2954    }
2955
2956    #[test]
2957    fn tokenize_select_1() {
2958        let sql = String::from("SELECT 1");
2959        let dialect = GenericDialect {};
2960        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
2961
2962        let expected = vec![
2963            Token::make_keyword("SELECT"),
2964            Token::Whitespace(Whitespace::Space),
2965            Token::Number(String::from("1"), false),
2966        ];
2967
2968        compare(expected, tokens);
2969    }
2970
2971    #[test]
2972    fn tokenize_select_float() {
2973        let sql = String::from("SELECT .1");
2974        let dialect = GenericDialect {};
2975        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
2976
2977        let expected = vec![
2978            Token::make_keyword("SELECT"),
2979            Token::Whitespace(Whitespace::Space),
2980            Token::Number(String::from(".1"), false),
2981        ];
2982
2983        compare(expected, tokens);
2984    }
2985
2986    #[test]
2987    fn tokenize_with_mapper() {
2988        let sql = String::from("SELECT ?");
2989        let dialect = GenericDialect {};
2990        let mut param_num = 1;
2991
2992        let mut tokens = vec![];
2993        Tokenizer::new(&dialect, &sql)
2994            .tokenize_with_location_into_buf_with_mapper(&mut tokens, |mut token_span| {
2995                token_span.token = match token_span.token {
2996                    Token::Placeholder(n) => Token::Placeholder(if n == "?" {
2997                        let ret = format!("${}", param_num);
2998                        param_num += 1;
2999                        ret
3000                    } else {
3001                        n
3002                    }),
3003                    token => token,
3004                };
3005                token_span
3006            })
3007            .unwrap();
3008        let actual = tokens.into_iter().map(|t| t.token).collect();
3009        let expected = vec![
3010            Token::make_keyword("SELECT"),
3011            Token::Whitespace(Whitespace::Space),
3012            Token::Placeholder("$1".to_string()),
3013        ];
3014
3015        compare(expected, actual);
3016    }
3017
3018    #[test]
3019    fn tokenize_clickhouse_double_equal() {
3020        let sql = String::from("SELECT foo=='1'");
3021        let dialect = ClickHouseDialect {};
3022        let mut tokenizer = Tokenizer::new(&dialect, &sql);
3023        let tokens = tokenizer.tokenize().unwrap();
3024
3025        let expected = vec![
3026            Token::make_keyword("SELECT"),
3027            Token::Whitespace(Whitespace::Space),
3028            Token::Word(Word {
3029                value: "foo".to_string(),
3030                quote_style: None,
3031                keyword: Keyword::NoKeyword,
3032            }),
3033            Token::DoubleEq,
3034            Token::SingleQuotedString("1".to_string()),
3035        ];
3036
3037        compare(expected, tokens);
3038    }
3039
3040    #[test]
3041    fn tokenize_numeric_literal_underscore() {
3042        let dialect = GenericDialect {};
3043        let sql = String::from("SELECT 10_000");
3044        let mut tokenizer = Tokenizer::new(&dialect, &sql);
3045        let tokens = tokenizer.tokenize().unwrap();
3046        let expected = vec![
3047            Token::make_keyword("SELECT"),
3048            Token::Whitespace(Whitespace::Space),
3049            Token::Number("10".to_string(), false),
3050            Token::make_word("_000", None),
3051        ];
3052        compare(expected, tokens);
3053
3054        let numeric_underscore_dialects =
3055            all_dialects_where(|dialect| dialect.supports_numeric_literal_underscores());
3056
3057        numeric_underscore_dialects.tokenizes_to(
3058            "SELECT 10_000, _10_000, 1_000.123, 1_000.123_456, 1e1_0",
3059            vec![
3060                Token::make_keyword("SELECT"),
3061                Token::Whitespace(Whitespace::Space),
3062                Token::Number("10_000".to_string(), false),
3063                Token::Comma,
3064                Token::Whitespace(Whitespace::Space),
3065                Token::make_word("_10_000", None), // leading underscore tokenizes as a word (parsed as column identifier)
3066                Token::Comma,
3067                Token::Whitespace(Whitespace::Space),
3068                Token::Number("1_000.123".to_string(), false), // with decimal digits
3069                Token::Comma,
3070                Token::Whitespace(Whitespace::Space),
3071                Token::Number("1_000.123_456".to_string(), false), // with an underscore in the decimal digits
3072                Token::Comma,
3073                Token::Whitespace(Whitespace::Space),
3074                Token::Number("1e1_0".to_string(), false), // with an underscore in the exponent
3075            ],
3076        );
3077
3078        let hex_string_dialects = all_dialects_where(|dialect| {
3079            dialect.supports_numeric_literal_underscores()
3080                && !dialect.supports_non_decimal_integer_literals()
3081        });
3082        hex_string_dialects.tokenizes_to(
3083            "0xFF_FF",
3084            vec![Token::HexStringLiteral("FF_FF".to_string())],
3085        );
3086        for dialect in &hex_string_dialects.dialects {
3087            let err = Tokenizer::new(&**dialect, "SELECT 0x_1")
3088                .tokenize()
3089                .unwrap_err();
3090            assert_eq!("Unexpected character '_'", err.message);
3091        }
3092
3093        for dialect in &numeric_underscore_dialects.dialects {
3094            for sql in [
3095                "SELECT 10_00_",
3096                "SELECT 10___0",
3097                "SELECT 1_000.123_",
3098                "SELECT 1._000",
3099                "SELECT 1_a",
3100                "SELECT 1e_1",
3101                "SELECT 1e1_",
3102                "SELECT 1e1__0",
3103                "SELECT 0x1_",
3104            ] {
3105                let err = Tokenizer::new(&**dialect, sql).tokenize().unwrap_err();
3106                assert_eq!("Unexpected character '_'", err.message);
3107            }
3108        }
3109    }
3110
3111    #[test]
3112    fn tokenize_select_exponent() {
3113        let sql = String::from("SELECT 1e10, 1e-10, 1e+10, 1ea, 1e-10a, 1e-10-10");
3114        let dialect = GenericDialect {};
3115        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3116
3117        let expected = vec![
3118            Token::make_keyword("SELECT"),
3119            Token::Whitespace(Whitespace::Space),
3120            Token::Number(String::from("1e10"), false),
3121            Token::Comma,
3122            Token::Whitespace(Whitespace::Space),
3123            Token::Number(String::from("1e-10"), false),
3124            Token::Comma,
3125            Token::Whitespace(Whitespace::Space),
3126            Token::Number(String::from("1e+10"), false),
3127            Token::Comma,
3128            Token::Whitespace(Whitespace::Space),
3129            Token::Number(String::from("1"), false),
3130            Token::make_word("ea", None),
3131            Token::Comma,
3132            Token::Whitespace(Whitespace::Space),
3133            Token::Number(String::from("1e-10"), false),
3134            Token::make_word("a", None),
3135            Token::Comma,
3136            Token::Whitespace(Whitespace::Space),
3137            Token::Number(String::from("1e-10"), false),
3138            Token::Minus,
3139            Token::Number(String::from("10"), false),
3140        ];
3141
3142        compare(expected, tokens);
3143    }
3144
3145    #[test]
3146    fn tokenize_scalar_function() {
3147        let sql = String::from("SELECT sqrt(1)");
3148        let dialect = GenericDialect {};
3149        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3150
3151        let expected = vec![
3152            Token::make_keyword("SELECT"),
3153            Token::Whitespace(Whitespace::Space),
3154            Token::make_word("sqrt", None),
3155            Token::LParen,
3156            Token::Number(String::from("1"), false),
3157            Token::RParen,
3158        ];
3159
3160        compare(expected, tokens);
3161    }
3162
3163    #[test]
3164    fn tokenize_string_string_concat() {
3165        let sql = String::from("SELECT 'a' || 'b'");
3166        let dialect = GenericDialect {};
3167        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3168
3169        let expected = vec![
3170            Token::make_keyword("SELECT"),
3171            Token::Whitespace(Whitespace::Space),
3172            Token::SingleQuotedString(String::from("a")),
3173            Token::Whitespace(Whitespace::Space),
3174            Token::StringConcat,
3175            Token::Whitespace(Whitespace::Space),
3176            Token::SingleQuotedString(String::from("b")),
3177        ];
3178
3179        compare(expected, tokens);
3180    }
3181    #[test]
3182    fn tokenize_bitwise_op() {
3183        let sql = String::from("SELECT one | two ^ three");
3184        let dialect = GenericDialect {};
3185        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3186
3187        let expected = vec![
3188            Token::make_keyword("SELECT"),
3189            Token::Whitespace(Whitespace::Space),
3190            Token::make_word("one", None),
3191            Token::Whitespace(Whitespace::Space),
3192            Token::Pipe,
3193            Token::Whitespace(Whitespace::Space),
3194            Token::make_word("two", None),
3195            Token::Whitespace(Whitespace::Space),
3196            Token::Caret,
3197            Token::Whitespace(Whitespace::Space),
3198            Token::make_word("three", None),
3199        ];
3200        compare(expected, tokens);
3201    }
3202
3203    #[test]
3204    fn tokenize_logical_xor() {
3205        let sql =
3206            String::from("SELECT true XOR true, false XOR false, true XOR false, false XOR true");
3207        let dialect = GenericDialect {};
3208        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3209
3210        let expected = vec![
3211            Token::make_keyword("SELECT"),
3212            Token::Whitespace(Whitespace::Space),
3213            Token::make_keyword("true"),
3214            Token::Whitespace(Whitespace::Space),
3215            Token::make_keyword("XOR"),
3216            Token::Whitespace(Whitespace::Space),
3217            Token::make_keyword("true"),
3218            Token::Comma,
3219            Token::Whitespace(Whitespace::Space),
3220            Token::make_keyword("false"),
3221            Token::Whitespace(Whitespace::Space),
3222            Token::make_keyword("XOR"),
3223            Token::Whitespace(Whitespace::Space),
3224            Token::make_keyword("false"),
3225            Token::Comma,
3226            Token::Whitespace(Whitespace::Space),
3227            Token::make_keyword("true"),
3228            Token::Whitespace(Whitespace::Space),
3229            Token::make_keyword("XOR"),
3230            Token::Whitespace(Whitespace::Space),
3231            Token::make_keyword("false"),
3232            Token::Comma,
3233            Token::Whitespace(Whitespace::Space),
3234            Token::make_keyword("false"),
3235            Token::Whitespace(Whitespace::Space),
3236            Token::make_keyword("XOR"),
3237            Token::Whitespace(Whitespace::Space),
3238            Token::make_keyword("true"),
3239        ];
3240        compare(expected, tokens);
3241    }
3242
3243    #[test]
3244    fn tokenize_simple_select() {
3245        let sql = String::from("SELECT * FROM customer WHERE id = 1 LIMIT 5");
3246        let dialect = GenericDialect {};
3247        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3248
3249        let expected = vec![
3250            Token::make_keyword("SELECT"),
3251            Token::Whitespace(Whitespace::Space),
3252            Token::Mul,
3253            Token::Whitespace(Whitespace::Space),
3254            Token::make_keyword("FROM"),
3255            Token::Whitespace(Whitespace::Space),
3256            Token::make_word("customer", None),
3257            Token::Whitespace(Whitespace::Space),
3258            Token::make_keyword("WHERE"),
3259            Token::Whitespace(Whitespace::Space),
3260            Token::make_word("id", None),
3261            Token::Whitespace(Whitespace::Space),
3262            Token::Eq,
3263            Token::Whitespace(Whitespace::Space),
3264            Token::Number(String::from("1"), false),
3265            Token::Whitespace(Whitespace::Space),
3266            Token::make_keyword("LIMIT"),
3267            Token::Whitespace(Whitespace::Space),
3268            Token::Number(String::from("5"), false),
3269        ];
3270
3271        compare(expected, tokens);
3272    }
3273
3274    #[test]
3275    fn tokenize_explain_select() {
3276        let sql = String::from("EXPLAIN SELECT * FROM customer WHERE id = 1");
3277        let dialect = GenericDialect {};
3278        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3279
3280        let expected = vec![
3281            Token::make_keyword("EXPLAIN"),
3282            Token::Whitespace(Whitespace::Space),
3283            Token::make_keyword("SELECT"),
3284            Token::Whitespace(Whitespace::Space),
3285            Token::Mul,
3286            Token::Whitespace(Whitespace::Space),
3287            Token::make_keyword("FROM"),
3288            Token::Whitespace(Whitespace::Space),
3289            Token::make_word("customer", None),
3290            Token::Whitespace(Whitespace::Space),
3291            Token::make_keyword("WHERE"),
3292            Token::Whitespace(Whitespace::Space),
3293            Token::make_word("id", None),
3294            Token::Whitespace(Whitespace::Space),
3295            Token::Eq,
3296            Token::Whitespace(Whitespace::Space),
3297            Token::Number(String::from("1"), false),
3298        ];
3299
3300        compare(expected, tokens);
3301    }
3302
3303    #[test]
3304    fn tokenize_explain_analyze_select() {
3305        let sql = String::from("EXPLAIN ANALYZE SELECT * FROM customer WHERE id = 1");
3306        let dialect = GenericDialect {};
3307        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3308
3309        let expected = vec![
3310            Token::make_keyword("EXPLAIN"),
3311            Token::Whitespace(Whitespace::Space),
3312            Token::make_keyword("ANALYZE"),
3313            Token::Whitespace(Whitespace::Space),
3314            Token::make_keyword("SELECT"),
3315            Token::Whitespace(Whitespace::Space),
3316            Token::Mul,
3317            Token::Whitespace(Whitespace::Space),
3318            Token::make_keyword("FROM"),
3319            Token::Whitespace(Whitespace::Space),
3320            Token::make_word("customer", None),
3321            Token::Whitespace(Whitespace::Space),
3322            Token::make_keyword("WHERE"),
3323            Token::Whitespace(Whitespace::Space),
3324            Token::make_word("id", None),
3325            Token::Whitespace(Whitespace::Space),
3326            Token::Eq,
3327            Token::Whitespace(Whitespace::Space),
3328            Token::Number(String::from("1"), false),
3329        ];
3330
3331        compare(expected, tokens);
3332    }
3333
3334    #[test]
3335    fn tokenize_string_predicate() {
3336        let sql = String::from("SELECT * FROM customer WHERE salary != 'Not Provided'");
3337        let dialect = GenericDialect {};
3338        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3339
3340        let expected = vec![
3341            Token::make_keyword("SELECT"),
3342            Token::Whitespace(Whitespace::Space),
3343            Token::Mul,
3344            Token::Whitespace(Whitespace::Space),
3345            Token::make_keyword("FROM"),
3346            Token::Whitespace(Whitespace::Space),
3347            Token::make_word("customer", None),
3348            Token::Whitespace(Whitespace::Space),
3349            Token::make_keyword("WHERE"),
3350            Token::Whitespace(Whitespace::Space),
3351            Token::make_word("salary", None),
3352            Token::Whitespace(Whitespace::Space),
3353            Token::Neq,
3354            Token::Whitespace(Whitespace::Space),
3355            Token::SingleQuotedString(String::from("Not Provided")),
3356        ];
3357
3358        compare(expected, tokens);
3359    }
3360
3361    #[test]
3362    fn tokenize_invalid_string() {
3363        let sql = String::from("\n💝مصطفىh");
3364
3365        let dialect = GenericDialect {};
3366        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3367        // println!("tokens: {:#?}", tokens);
3368        let expected = vec![
3369            Token::Whitespace(Whitespace::Newline),
3370            Token::Char('💝'),
3371            Token::make_word("مصطفىh", None),
3372        ];
3373        compare(expected, tokens);
3374    }
3375
3376    #[test]
3377    fn tokenize_newline_in_string_literal() {
3378        let sql = String::from("'foo\r\nbar\nbaz'");
3379
3380        let dialect = GenericDialect {};
3381        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3382        let expected = vec![Token::SingleQuotedString("foo\r\nbar\nbaz".to_string())];
3383        compare(expected, tokens);
3384    }
3385
3386    #[test]
3387    fn tokenize_unterminated_string_literal() {
3388        let sql = String::from("select 'foo");
3389
3390        let dialect = GenericDialect {};
3391        let mut tokenizer = Tokenizer::new(&dialect, &sql);
3392        assert_eq!(
3393            tokenizer.tokenize(),
3394            Err(TokenizerError {
3395                message: "Unterminated string literal".to_string(),
3396                location: Location { line: 1, column: 8 },
3397            })
3398        );
3399    }
3400
3401    #[test]
3402    fn tokenize_unterminated_string_literal_utf8() {
3403        let sql = String::from("SELECT \"なにか\" FROM Y WHERE \"なにか\" = 'test;");
3404
3405        let dialect = GenericDialect {};
3406        let mut tokenizer = Tokenizer::new(&dialect, &sql);
3407        assert_eq!(
3408            tokenizer.tokenize(),
3409            Err(TokenizerError {
3410                message: "Unterminated string literal".to_string(),
3411                location: Location {
3412                    line: 1,
3413                    column: 35
3414                }
3415            })
3416        );
3417    }
3418
3419    #[test]
3420    fn tokenize_invalid_string_cols() {
3421        let sql = String::from("\n\nSELECT * FROM table\t💝مصطفىh");
3422
3423        let dialect = GenericDialect {};
3424        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3425        // println!("tokens: {:#?}", tokens);
3426        let expected = vec![
3427            Token::Whitespace(Whitespace::Newline),
3428            Token::Whitespace(Whitespace::Newline),
3429            Token::make_keyword("SELECT"),
3430            Token::Whitespace(Whitespace::Space),
3431            Token::Mul,
3432            Token::Whitespace(Whitespace::Space),
3433            Token::make_keyword("FROM"),
3434            Token::Whitespace(Whitespace::Space),
3435            Token::make_keyword("table"),
3436            Token::Whitespace(Whitespace::Tab),
3437            Token::Char('💝'),
3438            Token::make_word("مصطفىh", None),
3439        ];
3440        compare(expected, tokens);
3441    }
3442
3443    #[test]
3444    fn tokenize_dollar_quoted_string_tagged() {
3445        let test_cases = vec![
3446            (
3447                String::from("SELECT $tag$dollar '$' quoted strings have $tags like this$ or like this $$$tag$"),
3448                vec![
3449                    Token::make_keyword("SELECT"),
3450                    Token::Whitespace(Whitespace::Space),
3451                    Token::DollarQuotedString(DollarQuotedString {
3452                        value: "dollar '$' quoted strings have $tags like this$ or like this $$".into(),
3453                        tag: Some("tag".into()),
3454                    })
3455                ]
3456            ),
3457            (
3458                String::from("SELECT $abc$x$ab$abc$"),
3459                vec![
3460                    Token::make_keyword("SELECT"),
3461                    Token::Whitespace(Whitespace::Space),
3462                    Token::DollarQuotedString(DollarQuotedString {
3463                        value: "x$ab".into(),
3464                        tag: Some("abc".into()),
3465                    })
3466                ]
3467            ),
3468            (
3469                String::from("SELECT $abc$$abc$"),
3470                vec![
3471                    Token::make_keyword("SELECT"),
3472                    Token::Whitespace(Whitespace::Space),
3473                    Token::DollarQuotedString(DollarQuotedString {
3474                        value: "".into(),
3475                        tag: Some("abc".into()),
3476                    })
3477                ]
3478            ),
3479            (
3480                String::from("0$abc$$abc$1"),
3481                vec![
3482                    Token::Number("0".into(), false),
3483                    Token::DollarQuotedString(DollarQuotedString {
3484                        value: "".into(),
3485                        tag: Some("abc".into()),
3486                    }),
3487                    Token::Number("1".into(), false),
3488                ]
3489            ),
3490            (
3491                String::from("$function$abc$q$data$q$$function$"),
3492                vec![
3493                    Token::DollarQuotedString(DollarQuotedString {
3494                        value: "abc$q$data$q$".into(),
3495                        tag: Some("function".into()),
3496                    }),
3497                ]
3498            ),
3499        ];
3500
3501        let dialect = GenericDialect {};
3502        for (sql, expected) in test_cases {
3503            let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3504            compare(expected, tokens);
3505        }
3506    }
3507
3508    #[test]
3509    fn tokenize_dollar_quoted_string_tagged_unterminated() {
3510        let sql = String::from("SELECT $tag$dollar '$' quoted strings have $tags like this$ or like this $$$different tag$");
3511        let dialect = GenericDialect {};
3512        assert_eq!(
3513            Tokenizer::new(&dialect, &sql).tokenize(),
3514            Err(TokenizerError {
3515                message: "Unterminated dollar-quoted, expected $".into(),
3516                location: Location {
3517                    line: 1,
3518                    column: 91
3519                }
3520            })
3521        );
3522    }
3523
3524    #[test]
3525    fn tokenize_dollar_quoted_string_tagged_unterminated_mirror() {
3526        let sql = String::from("SELECT $abc$abc$");
3527        let dialect = GenericDialect {};
3528        assert_eq!(
3529            Tokenizer::new(&dialect, &sql).tokenize(),
3530            Err(TokenizerError {
3531                message: "Unterminated dollar-quoted, expected $".into(),
3532                location: Location {
3533                    line: 1,
3534                    column: 17
3535                }
3536            })
3537        );
3538    }
3539
3540    #[test]
3541    fn tokenize_dollar_placeholder() {
3542        let sql = String::from("SELECT $$, $$ABC$$, $ABC$, $ABC");
3543        let dialect = SQLiteDialect {};
3544        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3545        assert_eq!(
3546            tokens,
3547            vec![
3548                Token::make_keyword("SELECT"),
3549                Token::Whitespace(Whitespace::Space),
3550                Token::Placeholder("$$".into()),
3551                Token::Comma,
3552                Token::Whitespace(Whitespace::Space),
3553                Token::Placeholder("$$ABC$$".into()),
3554                Token::Comma,
3555                Token::Whitespace(Whitespace::Space),
3556                Token::Placeholder("$ABC$".into()),
3557                Token::Comma,
3558                Token::Whitespace(Whitespace::Space),
3559                Token::Placeholder("$ABC".into()),
3560            ]
3561        );
3562    }
3563
3564    #[test]
3565    fn tokenize_nested_dollar_quoted_strings() {
3566        let sql = String::from("SELECT $tag$dollar $nested$ string$tag$");
3567        let dialect = GenericDialect {};
3568        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3569        let expected = vec![
3570            Token::make_keyword("SELECT"),
3571            Token::Whitespace(Whitespace::Space),
3572            Token::DollarQuotedString(DollarQuotedString {
3573                value: "dollar $nested$ string".into(),
3574                tag: Some("tag".into()),
3575            }),
3576        ];
3577        compare(expected, tokens);
3578    }
3579
3580    #[test]
3581    fn tokenize_dollar_quoted_string_untagged_empty() {
3582        let sql = String::from("SELECT $$$$");
3583        let dialect = GenericDialect {};
3584        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3585        let expected = vec![
3586            Token::make_keyword("SELECT"),
3587            Token::Whitespace(Whitespace::Space),
3588            Token::DollarQuotedString(DollarQuotedString {
3589                value: "".into(),
3590                tag: None,
3591            }),
3592        ];
3593        compare(expected, tokens);
3594    }
3595
3596    #[test]
3597    fn tokenize_dollar_quoted_string_untagged() {
3598        let sql =
3599            String::from("SELECT $$within dollar '$' quoted strings have $tags like this$ $$");
3600        let dialect = GenericDialect {};
3601        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3602        let expected = vec![
3603            Token::make_keyword("SELECT"),
3604            Token::Whitespace(Whitespace::Space),
3605            Token::DollarQuotedString(DollarQuotedString {
3606                value: "within dollar '$' quoted strings have $tags like this$ ".into(),
3607                tag: None,
3608            }),
3609        ];
3610        compare(expected, tokens);
3611    }
3612
3613    #[test]
3614    fn tokenize_dollar_quoted_string_untagged_unterminated() {
3615        let sql = String::from(
3616            "SELECT $$dollar '$' quoted strings have $tags like this$ or like this $different tag$",
3617        );
3618        let dialect = GenericDialect {};
3619        assert_eq!(
3620            Tokenizer::new(&dialect, &sql).tokenize(),
3621            Err(TokenizerError {
3622                message: "Unterminated dollar-quoted string".into(),
3623                location: Location {
3624                    line: 1,
3625                    column: 86
3626                }
3627            })
3628        );
3629    }
3630
3631    #[test]
3632    fn tokenize_right_arrow() {
3633        let sql = String::from("FUNCTION(key=>value)");
3634        let dialect = GenericDialect {};
3635        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3636        let expected = vec![
3637            Token::make_word("FUNCTION", None),
3638            Token::LParen,
3639            Token::make_word("key", None),
3640            Token::RArrow,
3641            Token::make_word("value", None),
3642            Token::RParen,
3643        ];
3644        compare(expected, tokens);
3645    }
3646
3647    #[test]
3648    fn tokenize_is_null() {
3649        let sql = String::from("a IS NULL");
3650        let dialect = GenericDialect {};
3651        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3652
3653        let expected = vec![
3654            Token::make_word("a", None),
3655            Token::Whitespace(Whitespace::Space),
3656            Token::make_keyword("IS"),
3657            Token::Whitespace(Whitespace::Space),
3658            Token::make_keyword("NULL"),
3659        ];
3660
3661        compare(expected, tokens);
3662    }
3663
3664    #[test]
3665    fn tokenize_comment() {
3666        let test_cases = vec![
3667            (
3668                String::from("0--this is a comment\n1"),
3669                vec![
3670                    Token::Number("0".to_string(), false),
3671                    Token::Whitespace(Whitespace::SingleLineComment {
3672                        prefix: "--".to_string(),
3673                        comment: "this is a comment".to_string(),
3674                    }),
3675                    Token::Whitespace(Whitespace::Newline),
3676                    Token::Number("1".to_string(), false),
3677                ],
3678            ),
3679            (
3680                String::from("0--this is a comment\r1"),
3681                vec![
3682                    Token::Number("0".to_string(), false),
3683                    Token::Whitespace(Whitespace::SingleLineComment {
3684                        prefix: "--".to_string(),
3685                        comment: "this is a comment\r1".to_string(),
3686                    }),
3687                ],
3688            ),
3689            (
3690                String::from("0--this is a comment\r\n1"),
3691                vec![
3692                    Token::Number("0".to_string(), false),
3693                    Token::Whitespace(Whitespace::SingleLineComment {
3694                        prefix: "--".to_string(),
3695                        comment: "this is a comment\r".to_string(),
3696                    }),
3697                    Token::Whitespace(Whitespace::Newline),
3698                    Token::Number("1".to_string(), false),
3699                ],
3700            ),
3701        ];
3702
3703        let dialect = GenericDialect {};
3704
3705        for (sql, expected) in test_cases {
3706            let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3707            compare(expected, tokens);
3708        }
3709    }
3710
3711    #[test]
3712    fn tokenize_comment_postgres() {
3713        let sql = String::from("1--\r0");
3714
3715        let dialect = PostgreSqlDialect {};
3716        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3717        let expected = vec![
3718            Token::Number("1".to_string(), false),
3719            Token::Whitespace(Whitespace::SingleLineComment {
3720                prefix: "--".to_string(),
3721                comment: "".to_string(),
3722            }),
3723            Token::Whitespace(Whitespace::Newline), // Postgres treats \r as newline in single-line comments
3724            Token::Number("0".to_string(), false),
3725        ];
3726        compare(expected, tokens);
3727    }
3728
3729    #[test]
3730    fn tokenize_comment_at_eof() {
3731        let sql = String::from("--this is a comment");
3732
3733        let dialect = GenericDialect {};
3734        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3735        let expected = vec![Token::Whitespace(Whitespace::SingleLineComment {
3736            prefix: "--".to_string(),
3737            comment: "this is a comment".to_string(),
3738        })];
3739        compare(expected, tokens);
3740    }
3741
3742    #[test]
3743    fn tokenize_multiline_comment() {
3744        let sql = String::from("0/*multi-line\n* /comment*/1");
3745
3746        let dialect = GenericDialect {};
3747        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3748        let expected = vec![
3749            Token::Number("0".to_string(), false),
3750            Token::Whitespace(Whitespace::MultiLineComment(
3751                "multi-line\n* /comment".to_string(),
3752            )),
3753            Token::Number("1".to_string(), false),
3754        ];
3755        compare(expected, tokens);
3756    }
3757
3758    #[test]
3759    fn tokenize_nested_multiline_comment() {
3760        all_dialects_where(|d| d.supports_nested_comments()).tokenizes_to(
3761            "0/*multi-line\n* \n/* comment \n /*comment*/*/ */ /comment*/1",
3762            vec![
3763                Token::Number("0".to_string(), false),
3764                Token::Whitespace(Whitespace::MultiLineComment(
3765                    "multi-line\n* \n/* comment \n /*comment*/*/ ".into(),
3766                )),
3767                Token::Whitespace(Whitespace::Space),
3768                Token::Div,
3769                Token::Word(Word {
3770                    value: "comment".to_string(),
3771                    quote_style: None,
3772                    keyword: Keyword::COMMENT,
3773                }),
3774                Token::Mul,
3775                Token::Div,
3776                Token::Number("1".to_string(), false),
3777            ],
3778        );
3779
3780        all_dialects_where(|d| d.supports_nested_comments()).tokenizes_to(
3781            "0/*multi-line\n* \n/* comment \n /*comment/**/ */ /comment*/*/1",
3782            vec![
3783                Token::Number("0".to_string(), false),
3784                Token::Whitespace(Whitespace::MultiLineComment(
3785                    "multi-line\n* \n/* comment \n /*comment/**/ */ /comment*/".into(),
3786                )),
3787                Token::Number("1".to_string(), false),
3788            ],
3789        );
3790
3791        all_dialects_where(|d| d.supports_nested_comments()).tokenizes_to(
3792            "SELECT 1/* a /* b */ c */0",
3793            vec![
3794                Token::make_keyword("SELECT"),
3795                Token::Whitespace(Whitespace::Space),
3796                Token::Number("1".to_string(), false),
3797                Token::Whitespace(Whitespace::MultiLineComment(" a /* b */ c ".to_string())),
3798                Token::Number("0".to_string(), false),
3799            ],
3800        );
3801    }
3802
3803    #[test]
3804    fn tokenize_nested_multiline_comment_empty() {
3805        all_dialects_where(|d| d.supports_nested_comments()).tokenizes_to(
3806            "select 1/*/**/*/0",
3807            vec![
3808                Token::make_keyword("select"),
3809                Token::Whitespace(Whitespace::Space),
3810                Token::Number("1".to_string(), false),
3811                Token::Whitespace(Whitespace::MultiLineComment("/**/".to_string())),
3812                Token::Number("0".to_string(), false),
3813            ],
3814        );
3815    }
3816
3817    #[test]
3818    fn tokenize_nested_comments_if_not_supported() {
3819        all_dialects_except(|d| d.supports_nested_comments()).tokenizes_to(
3820            "SELECT 1/*/* nested comment */*/0",
3821            vec![
3822                Token::make_keyword("SELECT"),
3823                Token::Whitespace(Whitespace::Space),
3824                Token::Number("1".to_string(), false),
3825                Token::Whitespace(Whitespace::MultiLineComment(
3826                    "/* nested comment ".to_string(),
3827                )),
3828                Token::Mul,
3829                Token::Div,
3830                Token::Number("0".to_string(), false),
3831            ],
3832        );
3833    }
3834
3835    #[test]
3836    fn tokenize_multiline_comment_with_even_asterisks() {
3837        let sql = String::from("\n/** Comment **/\n");
3838
3839        let dialect = GenericDialect {};
3840        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3841        let expected = vec![
3842            Token::Whitespace(Whitespace::Newline),
3843            Token::Whitespace(Whitespace::MultiLineComment("* Comment *".to_string())),
3844            Token::Whitespace(Whitespace::Newline),
3845        ];
3846        compare(expected, tokens);
3847    }
3848
3849    #[test]
3850    fn tokenize_unicode_whitespace() {
3851        let sql = String::from(" \u{2003}\n");
3852
3853        let dialect = GenericDialect {};
3854        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3855        let expected = vec![
3856            Token::Whitespace(Whitespace::Space),
3857            Token::Whitespace(Whitespace::Space),
3858            Token::Whitespace(Whitespace::Newline),
3859        ];
3860        compare(expected, tokens);
3861    }
3862
3863    #[test]
3864    fn tokenize_mismatched_quotes() {
3865        let sql = String::from("\"foo");
3866
3867        let dialect = GenericDialect {};
3868        let mut tokenizer = Tokenizer::new(&dialect, &sql);
3869        assert_eq!(
3870            tokenizer.tokenize(),
3871            Err(TokenizerError {
3872                message: "Expected close delimiter '\"' before EOF.".to_string(),
3873                location: Location { line: 1, column: 1 },
3874            })
3875        );
3876    }
3877
3878    #[test]
3879    fn tokenize_newlines() {
3880        let sql = String::from("line1\nline2\rline3\r\nline4\r");
3881
3882        let dialect = GenericDialect {};
3883        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
3884        let expected = vec![
3885            Token::make_word("line1", None),
3886            Token::Whitespace(Whitespace::Newline),
3887            Token::make_word("line2", None),
3888            Token::Whitespace(Whitespace::Newline),
3889            Token::make_word("line3", None),
3890            Token::Whitespace(Whitespace::Newline),
3891            Token::make_word("line4", None),
3892            Token::Whitespace(Whitespace::Newline),
3893        ];
3894        compare(expected, tokens);
3895    }
3896
3897    #[test]
3898    fn tokenize_mssql_top() {
3899        let sql = "SELECT TOP 5 [bar] FROM foo";
3900        let dialect = MsSqlDialect {};
3901        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
3902        let expected = vec![
3903            Token::make_keyword("SELECT"),
3904            Token::Whitespace(Whitespace::Space),
3905            Token::make_keyword("TOP"),
3906            Token::Whitespace(Whitespace::Space),
3907            Token::Number(String::from("5"), false),
3908            Token::Whitespace(Whitespace::Space),
3909            Token::make_word("bar", Some('[')),
3910            Token::Whitespace(Whitespace::Space),
3911            Token::make_keyword("FROM"),
3912            Token::Whitespace(Whitespace::Space),
3913            Token::make_word("foo", None),
3914        ];
3915        compare(expected, tokens);
3916    }
3917
3918    #[test]
3919    fn tokenize_pg_regex_match() {
3920        let sql = "SELECT col ~ '^a', col ~* '^a', col !~ '^a', col !~* '^a'";
3921        let dialect = GenericDialect {};
3922        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
3923        let expected = vec![
3924            Token::make_keyword("SELECT"),
3925            Token::Whitespace(Whitespace::Space),
3926            Token::make_word("col", None),
3927            Token::Whitespace(Whitespace::Space),
3928            Token::Tilde,
3929            Token::Whitespace(Whitespace::Space),
3930            Token::SingleQuotedString("^a".into()),
3931            Token::Comma,
3932            Token::Whitespace(Whitespace::Space),
3933            Token::make_word("col", None),
3934            Token::Whitespace(Whitespace::Space),
3935            Token::TildeAsterisk,
3936            Token::Whitespace(Whitespace::Space),
3937            Token::SingleQuotedString("^a".into()),
3938            Token::Comma,
3939            Token::Whitespace(Whitespace::Space),
3940            Token::make_word("col", None),
3941            Token::Whitespace(Whitespace::Space),
3942            Token::ExclamationMarkTilde,
3943            Token::Whitespace(Whitespace::Space),
3944            Token::SingleQuotedString("^a".into()),
3945            Token::Comma,
3946            Token::Whitespace(Whitespace::Space),
3947            Token::make_word("col", None),
3948            Token::Whitespace(Whitespace::Space),
3949            Token::ExclamationMarkTildeAsterisk,
3950            Token::Whitespace(Whitespace::Space),
3951            Token::SingleQuotedString("^a".into()),
3952        ];
3953        compare(expected, tokens);
3954    }
3955
3956    #[test]
3957    fn tokenize_pg_like_match() {
3958        let sql = "SELECT col ~~ '_a%', col ~~* '_a%', col !~~ '_a%', col !~~* '_a%'";
3959        let dialect = GenericDialect {};
3960        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
3961        let expected = vec![
3962            Token::make_keyword("SELECT"),
3963            Token::Whitespace(Whitespace::Space),
3964            Token::make_word("col", None),
3965            Token::Whitespace(Whitespace::Space),
3966            Token::DoubleTilde,
3967            Token::Whitespace(Whitespace::Space),
3968            Token::SingleQuotedString("_a%".into()),
3969            Token::Comma,
3970            Token::Whitespace(Whitespace::Space),
3971            Token::make_word("col", None),
3972            Token::Whitespace(Whitespace::Space),
3973            Token::DoubleTildeAsterisk,
3974            Token::Whitespace(Whitespace::Space),
3975            Token::SingleQuotedString("_a%".into()),
3976            Token::Comma,
3977            Token::Whitespace(Whitespace::Space),
3978            Token::make_word("col", None),
3979            Token::Whitespace(Whitespace::Space),
3980            Token::ExclamationMarkDoubleTilde,
3981            Token::Whitespace(Whitespace::Space),
3982            Token::SingleQuotedString("_a%".into()),
3983            Token::Comma,
3984            Token::Whitespace(Whitespace::Space),
3985            Token::make_word("col", None),
3986            Token::Whitespace(Whitespace::Space),
3987            Token::ExclamationMarkDoubleTildeAsterisk,
3988            Token::Whitespace(Whitespace::Space),
3989            Token::SingleQuotedString("_a%".into()),
3990        ];
3991        compare(expected, tokens);
3992    }
3993
3994    #[test]
3995    fn tokenize_tilde_without_like_match_operators() {
3996        all_dialects_where(|d| !d.supports_tilde_like_match_operator()).tokenizes_to(
3997            "~~ ~~* !~~ !~~*",
3998            vec![
3999                Token::Tilde,
4000                Token::Tilde,
4001                Token::Whitespace(Whitespace::Space),
4002                Token::Tilde,
4003                Token::TildeAsterisk,
4004                Token::Whitespace(Whitespace::Space),
4005                Token::ExclamationMarkTilde,
4006                Token::Tilde,
4007                Token::Whitespace(Whitespace::Space),
4008                Token::ExclamationMarkTilde,
4009                Token::TildeAsterisk,
4010            ],
4011        );
4012    }
4013
4014    #[test]
4015    fn tokenize_quoted_identifier() {
4016        let sql = r#" "a "" b" "a """ "c """"" "#;
4017        let dialect = GenericDialect {};
4018        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4019        let expected = vec![
4020            Token::Whitespace(Whitespace::Space),
4021            Token::make_word(r#"a " b"#, Some('"')),
4022            Token::Whitespace(Whitespace::Space),
4023            Token::make_word(r#"a ""#, Some('"')),
4024            Token::Whitespace(Whitespace::Space),
4025            Token::make_word(r#"c """#, Some('"')),
4026            Token::Whitespace(Whitespace::Space),
4027        ];
4028        compare(expected, tokens);
4029    }
4030
4031    #[test]
4032    fn tokenize_snowflake_div() {
4033        let sql = r#"field/1000"#;
4034        let dialect = SnowflakeDialect {};
4035        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4036        let expected = vec![
4037            Token::make_word(r#"field"#, None),
4038            Token::Div,
4039            Token::Number("1000".to_string(), false),
4040        ];
4041        compare(expected, tokens);
4042    }
4043
4044    #[test]
4045    fn tokenize_quoted_identifier_with_no_escape() {
4046        let sql = r#" "a "" b" "a """ "c """"" "#;
4047        let dialect = GenericDialect {};
4048        let tokens = Tokenizer::new(&dialect, sql)
4049            .with_unescape(false)
4050            .tokenize()
4051            .unwrap();
4052        let expected = vec![
4053            Token::Whitespace(Whitespace::Space),
4054            Token::make_word(r#"a "" b"#, Some('"')),
4055            Token::Whitespace(Whitespace::Space),
4056            Token::make_word(r#"a """#, Some('"')),
4057            Token::Whitespace(Whitespace::Space),
4058            Token::make_word(r#"c """""#, Some('"')),
4059            Token::Whitespace(Whitespace::Space),
4060        ];
4061        compare(expected, tokens);
4062    }
4063
4064    #[test]
4065    fn tokenize_with_location() {
4066        let sql = "SELECT a,\n b";
4067        let dialect = GenericDialect {};
4068        let tokens = Tokenizer::new(&dialect, sql)
4069            .tokenize_with_location()
4070            .unwrap();
4071        let expected = vec![
4072            TokenWithSpan::at(Token::make_keyword("SELECT"), (1, 1).into(), (1, 7).into()),
4073            TokenWithSpan::at(
4074                Token::Whitespace(Whitespace::Space),
4075                (1, 7).into(),
4076                (1, 8).into(),
4077            ),
4078            TokenWithSpan::at(Token::make_word("a", None), (1, 8).into(), (1, 9).into()),
4079            TokenWithSpan::at(Token::Comma, (1, 9).into(), (1, 10).into()),
4080            TokenWithSpan::at(
4081                Token::Whitespace(Whitespace::Newline),
4082                (1, 10).into(),
4083                (2, 1).into(),
4084            ),
4085            TokenWithSpan::at(
4086                Token::Whitespace(Whitespace::Space),
4087                (2, 1).into(),
4088                (2, 2).into(),
4089            ),
4090            TokenWithSpan::at(Token::make_word("b", None), (2, 2).into(), (2, 3).into()),
4091        ];
4092        compare(expected, tokens);
4093    }
4094
4095    fn compare<T: PartialEq + fmt::Debug>(expected: Vec<T>, actual: Vec<T>) {
4096        //println!("------------------------------");
4097        //println!("tokens   = {:?}", actual);
4098        //println!("expected = {:?}", expected);
4099        //println!("------------------------------");
4100        assert_eq!(expected, actual);
4101    }
4102
4103    fn check_unescape(s: &str, expected: Option<&str>) {
4104        let s = format!("'{s}'");
4105        let mut state = State {
4106            peekable: s.chars().peekable(),
4107            line: 0,
4108            col: 0,
4109        };
4110
4111        assert_eq!(
4112            unescape_single_quoted_string(&mut state),
4113            expected.map(|s| s.to_string())
4114        );
4115    }
4116
4117    #[test]
4118    fn test_unescape() {
4119        check_unescape(r"\b", Some("\u{0008}"));
4120        check_unescape(r"\f", Some("\u{000C}"));
4121        check_unescape(r"\t", Some("\t"));
4122        check_unescape(r"\r\n", Some("\r\n"));
4123        check_unescape(r"\/", Some("/"));
4124        check_unescape(r"/", Some("/"));
4125        check_unescape(r"\\", Some("\\"));
4126
4127        // 16 and 32-bit hexadecimal Unicode character value
4128        check_unescape(r"\u0001", Some("\u{0001}"));
4129        check_unescape(r"\u4c91", Some("\u{4c91}"));
4130        check_unescape(r"\u4c916", Some("\u{4c91}6"));
4131        check_unescape(r"\u4c", None);
4132        check_unescape(r"\u0000", None);
4133        check_unescape(r"\U0010FFFF", Some("\u{10FFFF}"));
4134        check_unescape(r"\U00110000", None);
4135        check_unescape(r"\U00000000", None);
4136        check_unescape(r"\u", None);
4137        check_unescape(r"\U", None);
4138        check_unescape(r"\U1010FFFF", None);
4139
4140        // hexadecimal byte value
4141        check_unescape(r"\x4B", Some("\u{004b}"));
4142        check_unescape(r"\x4", Some("\u{0004}"));
4143        check_unescape(r"\x4L", Some("\u{0004}L"));
4144        check_unescape(r"\x", Some("x"));
4145        check_unescape(r"\xP", Some("xP"));
4146        check_unescape(r"\x0", None);
4147        check_unescape(r"\xCAD", None);
4148        check_unescape(r"\xA9", None);
4149
4150        // octal byte value
4151        check_unescape(r"\1", Some("\u{0001}"));
4152        check_unescape(r"\12", Some("\u{000a}"));
4153        check_unescape(r"\123", Some("\u{0053}"));
4154        check_unescape(r"\1232", Some("\u{0053}2"));
4155        check_unescape(r"\4", Some("\u{0004}"));
4156        check_unescape(r"\45", Some("\u{0025}"));
4157        check_unescape(r"\450", Some("\u{0028}"));
4158        check_unescape(r"\603", None);
4159        check_unescape(r"\0", None);
4160        check_unescape(r"\080", None);
4161
4162        // others
4163        check_unescape(r"\9", Some("9"));
4164        check_unescape(r"''", Some("'"));
4165        check_unescape(
4166            r"Hello\r\nRust/\u4c91 SQL Parser\U0010ABCD\1232",
4167            Some("Hello\r\nRust/\u{4c91} SQL Parser\u{10abcd}\u{0053}2"),
4168        );
4169        check_unescape(r"Hello\0", None);
4170        check_unescape(r"Hello\xCADRust", None);
4171    }
4172
4173    #[test]
4174    fn tokenize_numeric_prefix_trait() {
4175        #[derive(Debug)]
4176        struct NumericPrefixDialect;
4177
4178        impl Dialect for NumericPrefixDialect {
4179            fn is_identifier_start(&self, ch: char) -> bool {
4180                ch.is_ascii_lowercase()
4181                    || ch.is_ascii_uppercase()
4182                    || ch.is_ascii_digit()
4183                    || ch == '$'
4184            }
4185
4186            fn is_identifier_part(&self, ch: char) -> bool {
4187                ch.is_ascii_lowercase()
4188                    || ch.is_ascii_uppercase()
4189                    || ch.is_ascii_digit()
4190                    || ch == '_'
4191                    || ch == '$'
4192                    || ch == '{'
4193                    || ch == '}'
4194            }
4195
4196            fn supports_numeric_prefix(&self) -> bool {
4197                true
4198            }
4199        }
4200
4201        tokenize_numeric_prefix_inner(&NumericPrefixDialect {});
4202        tokenize_numeric_prefix_inner(&HiveDialect {});
4203        tokenize_numeric_prefix_inner(&MySqlDialect {});
4204    }
4205
4206    fn tokenize_numeric_prefix_inner(dialect: &dyn Dialect) {
4207        let sql = r#"SELECT * FROM 1"#;
4208        let tokens = Tokenizer::new(dialect, sql).tokenize().unwrap();
4209        let expected = vec![
4210            Token::make_keyword("SELECT"),
4211            Token::Whitespace(Whitespace::Space),
4212            Token::Mul,
4213            Token::Whitespace(Whitespace::Space),
4214            Token::make_keyword("FROM"),
4215            Token::Whitespace(Whitespace::Space),
4216            Token::Number(String::from("1"), false),
4217        ];
4218        compare(expected, tokens);
4219    }
4220
4221    #[test]
4222    fn tokenize_quoted_string_escape() {
4223        let dialect = SnowflakeDialect {};
4224        for (sql, expected, expected_unescaped) in [
4225            (r#"'%a\'%b'"#, r#"%a\'%b"#, r#"%a'%b"#),
4226            (r#"'a\'\'b\'c\'d'"#, r#"a\'\'b\'c\'d"#, r#"a''b'c'd"#),
4227            (r#"'\\'"#, r#"\\"#, r#"\"#),
4228            (
4229                r#"'\0\a\b\f\n\r\t\Z'"#,
4230                r#"\0\a\b\f\n\r\t\Z"#,
4231                "\0\u{7}\u{8}\u{c}\n\r\t\u{1a}",
4232            ),
4233            (r#"'\"'"#, r#"\""#, "\""),
4234            (r#"'\\a\\b\'c'"#, r#"\\a\\b\'c"#, r#"\a\b'c"#),
4235            (r#"'\'abcd'"#, r#"\'abcd"#, r#"'abcd"#),
4236            (r#"'''a''b'"#, r#"''a''b"#, r#"'a'b"#),
4237            (r#"'\q'"#, r#"\q"#, r#"q"#),
4238            (r#"'\%\_'"#, r#"\%\_"#, r#"%_"#),
4239            (r#"'\\%\\_'"#, r#"\\%\\_"#, r#"\%\_"#),
4240        ] {
4241            let tokens = Tokenizer::new(&dialect, sql)
4242                .with_unescape(false)
4243                .tokenize()
4244                .unwrap();
4245            let expected = vec![Token::SingleQuotedString(expected.to_string())];
4246            compare(expected, tokens);
4247
4248            let tokens = Tokenizer::new(&dialect, sql)
4249                .with_unescape(true)
4250                .tokenize()
4251                .unwrap();
4252            let expected = vec![Token::SingleQuotedString(expected_unescaped.to_string())];
4253            compare(expected, tokens);
4254        }
4255
4256        for sql in [r#"'\'"#, r#"'ab\'"#] {
4257            let mut tokenizer = Tokenizer::new(&dialect, sql);
4258            assert_eq!(
4259                "Unterminated string literal",
4260                tokenizer.tokenize().unwrap_err().message.as_str(),
4261            );
4262        }
4263
4264        // Non-escape dialect
4265        for (sql, expected) in [(r#"'\'"#, r#"\"#), (r#"'ab\'"#, r#"ab\"#)] {
4266            let dialect = GenericDialect {};
4267            let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4268
4269            let expected = vec![Token::SingleQuotedString(expected.to_string())];
4270
4271            compare(expected, tokens);
4272        }
4273
4274        // MySQL special case for LIKE escapes
4275        for (sql, expected) in [(r#"'\%'"#, r#"\%"#), (r#"'\_'"#, r#"\_"#)] {
4276            let dialect = MySqlDialect {};
4277            let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4278
4279            let expected = vec![Token::SingleQuotedString(expected.to_string())];
4280
4281            compare(expected, tokens);
4282        }
4283    }
4284
4285    #[test]
4286    fn tokenize_triple_quoted_string() {
4287        fn check<F>(
4288            q: char, // The quote character to test
4289            r: char, // An alternate quote character.
4290            quote_token: F,
4291        ) where
4292            F: Fn(String) -> Token,
4293        {
4294            let dialect = BigQueryDialect {};
4295
4296            for (sql, expected, expected_unescaped) in [
4297                // Empty string
4298                (format!(r#"{q}{q}{q}{q}{q}{q}"#), "".into(), "".into()),
4299                // Should not count escaped quote as end of string.
4300                (
4301                    format!(r#"{q}{q}{q}ab{q}{q}\{q}{q}cd{q}{q}{q}"#),
4302                    format!(r#"ab{q}{q}\{q}{q}cd"#),
4303                    format!(r#"ab{q}{q}{q}{q}cd"#),
4304                ),
4305                // Simple string
4306                (
4307                    format!(r#"{q}{q}{q}abc{q}{q}{q}"#),
4308                    "abc".into(),
4309                    "abc".into(),
4310                ),
4311                // Mix single-double quotes unescaped.
4312                (
4313                    format!(r#"{q}{q}{q}ab{r}{r}{r}c{r}def{r}{r}{r}{q}{q}{q}"#),
4314                    format!("ab{r}{r}{r}c{r}def{r}{r}{r}"),
4315                    format!("ab{r}{r}{r}c{r}def{r}{r}{r}"),
4316                ),
4317                // Escaped quote.
4318                (
4319                    format!(r#"{q}{q}{q}ab{q}{q}c{q}{q}\{q}de{q}{q}f{q}{q}{q}"#),
4320                    format!(r#"ab{q}{q}c{q}{q}\{q}de{q}{q}f"#),
4321                    format!(r#"ab{q}{q}c{q}{q}{q}de{q}{q}f"#),
4322                ),
4323                // backslash-escaped quote characters.
4324                (
4325                    format!(r#"{q}{q}{q}a\'\'b\'c\'d{q}{q}{q}"#),
4326                    r#"a\'\'b\'c\'d"#.into(),
4327                    r#"a''b'c'd"#.into(),
4328                ),
4329                // backslash-escaped characters
4330                (
4331                    format!(r#"{q}{q}{q}abc\0\n\rdef{q}{q}{q}"#),
4332                    r#"abc\0\n\rdef"#.into(),
4333                    "abc\0\n\rdef".into(),
4334                ),
4335            ] {
4336                let tokens = Tokenizer::new(&dialect, sql.as_str())
4337                    .with_unescape(false)
4338                    .tokenize()
4339                    .unwrap();
4340                let expected = vec![quote_token(expected.to_string())];
4341                compare(expected, tokens);
4342
4343                let tokens = Tokenizer::new(&dialect, sql.as_str())
4344                    .with_unescape(true)
4345                    .tokenize()
4346                    .unwrap();
4347                let expected = vec![quote_token(expected_unescaped.to_string())];
4348                compare(expected, tokens);
4349            }
4350
4351            for sql in [
4352                format!(r#"{q}{q}{q}{q}{q}\{q}"#),
4353                format!(r#"{q}{q}{q}abc{q}{q}\{q}"#),
4354                format!(r#"{q}{q}{q}{q}"#),
4355                format!(r#"{q}{q}{q}{r}{r}"#),
4356                format!(r#"{q}{q}{q}abc{q}"#),
4357                format!(r#"{q}{q}{q}abc{q}{q}"#),
4358                format!(r#"{q}{q}{q}abc"#),
4359            ] {
4360                let dialect = BigQueryDialect {};
4361                let mut tokenizer = Tokenizer::new(&dialect, sql.as_str());
4362                assert_eq!(
4363                    "Unterminated string literal",
4364                    tokenizer.tokenize().unwrap_err().message.as_str(),
4365                );
4366            }
4367        }
4368
4369        check('"', '\'', Token::TripleDoubleQuotedString);
4370
4371        check('\'', '"', Token::TripleSingleQuotedString);
4372
4373        let dialect = BigQueryDialect {};
4374
4375        let sql = r#"""''"#;
4376        let tokens = Tokenizer::new(&dialect, sql)
4377            .with_unescape(true)
4378            .tokenize()
4379            .unwrap();
4380        let expected = vec![
4381            Token::DoubleQuotedString("".to_string()),
4382            Token::SingleQuotedString("".to_string()),
4383        ];
4384        compare(expected, tokens);
4385
4386        let sql = r#"''"""#;
4387        let tokens = Tokenizer::new(&dialect, sql)
4388            .with_unescape(true)
4389            .tokenize()
4390            .unwrap();
4391        let expected = vec![
4392            Token::SingleQuotedString("".to_string()),
4393            Token::DoubleQuotedString("".to_string()),
4394        ];
4395        compare(expected, tokens);
4396
4397        // Non-triple quoted string dialect
4398        let dialect = SnowflakeDialect {};
4399        let sql = r#"''''''"#;
4400        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4401        let expected = vec![Token::SingleQuotedString("''".to_string())];
4402        compare(expected, tokens);
4403    }
4404
4405    #[test]
4406    fn test_mysql_users_grantees() {
4407        let dialect = MySqlDialect {};
4408
4409        let sql = "CREATE USER `root`@`%`";
4410        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4411        let expected = vec![
4412            Token::make_keyword("CREATE"),
4413            Token::Whitespace(Whitespace::Space),
4414            Token::make_keyword("USER"),
4415            Token::Whitespace(Whitespace::Space),
4416            Token::make_word("root", Some('`')),
4417            Token::AtSign,
4418            Token::make_word("%", Some('`')),
4419        ];
4420        compare(expected, tokens);
4421    }
4422
4423    #[test]
4424    fn test_postgres_abs_without_space_and_string_literal() {
4425        let dialect = MySqlDialect {};
4426
4427        let sql = "SELECT @'1'";
4428        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4429        let expected = vec![
4430            Token::make_keyword("SELECT"),
4431            Token::Whitespace(Whitespace::Space),
4432            Token::AtSign,
4433            Token::SingleQuotedString("1".to_string()),
4434        ];
4435        compare(expected, tokens);
4436    }
4437
4438    #[test]
4439    fn test_postgres_abs_without_space_and_quoted_column() {
4440        let dialect = MySqlDialect {};
4441
4442        let sql = r#"SELECT @"bar" FROM foo"#;
4443        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4444        let expected = vec![
4445            Token::make_keyword("SELECT"),
4446            Token::Whitespace(Whitespace::Space),
4447            Token::AtSign,
4448            Token::DoubleQuotedString("bar".to_string()),
4449            Token::Whitespace(Whitespace::Space),
4450            Token::make_keyword("FROM"),
4451            Token::Whitespace(Whitespace::Space),
4452            Token::make_word("foo", None),
4453        ];
4454        compare(expected, tokens);
4455    }
4456
4457    #[test]
4458    fn test_national_strings_backslash_escape_not_supported() {
4459        all_dialects_where(|dialect| {
4460            !dialect.supports_string_literal_backslash_escape()
4461                && dialect.supports_national_string_literal()
4462        })
4463        .tokenizes_to(
4464            "select n'''''\\'",
4465            vec![
4466                Token::make_keyword("select"),
4467                Token::Whitespace(Whitespace::Space),
4468                Token::NationalStringLiteral("''\\".to_string()),
4469            ],
4470        );
4471    }
4472
4473    #[test]
4474    fn test_national_strings_backslash_escape_supported() {
4475        all_dialects_where(|dialect| dialect.supports_string_literal_backslash_escape())
4476            .tokenizes_to(
4477                "select n'''''\\''",
4478                vec![
4479                    Token::make_keyword("select"),
4480                    Token::Whitespace(Whitespace::Space),
4481                    Token::NationalStringLiteral("'''".to_string()),
4482                ],
4483            );
4484    }
4485
4486    #[test]
4487    fn test_string_escape_constant_not_supported() {
4488        all_dialects_where(|dialect| !dialect.supports_string_escape_constant()).tokenizes_to(
4489            "select e'...'",
4490            vec![
4491                Token::make_keyword("select"),
4492                Token::Whitespace(Whitespace::Space),
4493                Token::make_word("e", None),
4494                Token::SingleQuotedString("...".to_string()),
4495            ],
4496        );
4497
4498        all_dialects_where(|dialect| !dialect.supports_string_escape_constant()).tokenizes_to(
4499            "select E'...'",
4500            vec![
4501                Token::make_keyword("select"),
4502                Token::Whitespace(Whitespace::Space),
4503                Token::make_word("E", None),
4504                Token::SingleQuotedString("...".to_string()),
4505            ],
4506        );
4507    }
4508
4509    #[test]
4510    fn test_string_escape_constant_supported() {
4511        all_dialects_where(|dialect| dialect.supports_string_escape_constant()).tokenizes_to(
4512            "select e'\\''",
4513            vec![
4514                Token::make_keyword("select"),
4515                Token::Whitespace(Whitespace::Space),
4516                Token::EscapedStringLiteral("'".to_string()),
4517            ],
4518        );
4519
4520        all_dialects_where(|dialect| dialect.supports_string_escape_constant()).tokenizes_to(
4521            "select E'\\''",
4522            vec![
4523                Token::make_keyword("select"),
4524                Token::Whitespace(Whitespace::Space),
4525                Token::EscapedStringLiteral("'".to_string()),
4526            ],
4527        );
4528    }
4529
4530    #[test]
4531    fn test_whitespace_required_after_single_line_comment() {
4532        all_dialects_where(|dialect| dialect.requires_single_line_comment_whitespace())
4533            .tokenizes_to(
4534                "SELECT --'abc'",
4535                vec![
4536                    Token::make_keyword("SELECT"),
4537                    Token::Whitespace(Whitespace::Space),
4538                    Token::Minus,
4539                    Token::Minus,
4540                    Token::SingleQuotedString("abc".to_string()),
4541                ],
4542            );
4543
4544        all_dialects_where(|dialect| dialect.requires_single_line_comment_whitespace())
4545            .tokenizes_to(
4546                "SELECT -- 'abc'",
4547                vec![
4548                    Token::make_keyword("SELECT"),
4549                    Token::Whitespace(Whitespace::Space),
4550                    Token::Whitespace(Whitespace::SingleLineComment {
4551                        prefix: "--".to_string(),
4552                        comment: " 'abc'".to_string(),
4553                    }),
4554                ],
4555            );
4556
4557        all_dialects_where(|dialect| dialect.requires_single_line_comment_whitespace())
4558            .tokenizes_to(
4559                "SELECT --",
4560                vec![
4561                    Token::make_keyword("SELECT"),
4562                    Token::Whitespace(Whitespace::Space),
4563                    Token::Minus,
4564                    Token::Minus,
4565                ],
4566            );
4567
4568        all_dialects_where(|d| d.requires_single_line_comment_whitespace()).tokenizes_to(
4569            "--\n-- Table structure for table...\n--\n",
4570            vec![
4571                Token::Whitespace(Whitespace::SingleLineComment {
4572                    prefix: "--".to_string(),
4573                    comment: "".to_string(),
4574                }),
4575                Token::Whitespace(Whitespace::Newline),
4576                Token::Whitespace(Whitespace::SingleLineComment {
4577                    prefix: "--".to_string(),
4578                    comment: " Table structure for table...".to_string(),
4579                }),
4580                Token::Whitespace(Whitespace::Newline),
4581                Token::Whitespace(Whitespace::SingleLineComment {
4582                    prefix: "--".to_string(),
4583                    comment: "".to_string(),
4584                }),
4585                Token::Whitespace(Whitespace::Newline),
4586            ],
4587        );
4588    }
4589
4590    #[test]
4591    fn test_whitespace_not_required_after_single_line_comment() {
4592        all_dialects_where(|dialect| !dialect.requires_single_line_comment_whitespace())
4593            .tokenizes_to(
4594                "SELECT --'abc'",
4595                vec![
4596                    Token::make_keyword("SELECT"),
4597                    Token::Whitespace(Whitespace::Space),
4598                    Token::Whitespace(Whitespace::SingleLineComment {
4599                        prefix: "--".to_string(),
4600                        comment: "'abc'".to_string(),
4601                    }),
4602                ],
4603            );
4604
4605        all_dialects_where(|dialect| !dialect.requires_single_line_comment_whitespace())
4606            .tokenizes_to(
4607                "SELECT -- 'abc'",
4608                vec![
4609                    Token::make_keyword("SELECT"),
4610                    Token::Whitespace(Whitespace::Space),
4611                    Token::Whitespace(Whitespace::SingleLineComment {
4612                        prefix: "--".to_string(),
4613                        comment: " 'abc'".to_string(),
4614                    }),
4615                ],
4616            );
4617
4618        all_dialects_where(|dialect| !dialect.requires_single_line_comment_whitespace())
4619            .tokenizes_to(
4620                "SELECT --",
4621                vec![
4622                    Token::make_keyword("SELECT"),
4623                    Token::Whitespace(Whitespace::Space),
4624                    Token::Whitespace(Whitespace::SingleLineComment {
4625                        prefix: "--".to_string(),
4626                        comment: "".to_string(),
4627                    }),
4628                ],
4629            );
4630    }
4631
4632    #[test]
4633    fn test_tokenize_identifiers_numeric_prefix() {
4634        all_dialects_where(|dialect| dialect.supports_numeric_prefix())
4635            .tokenizes_to("123abc", vec![Token::make_word("123abc", None)]);
4636
4637        all_dialects_where(|dialect| dialect.supports_numeric_prefix())
4638            .tokenizes_to("12e34", vec![Token::Number("12e34".to_string(), false)]);
4639
4640        all_dialects_where(|dialect| dialect.supports_numeric_prefix()).tokenizes_to(
4641            "t.12e34",
4642            vec![
4643                Token::make_word("t", None),
4644                Token::Period,
4645                Token::make_word("12e34", None),
4646            ],
4647        );
4648
4649        all_dialects_where(|dialect| dialect.supports_numeric_prefix()).tokenizes_to(
4650            "t.1two3",
4651            vec![
4652                Token::make_word("t", None),
4653                Token::Period,
4654                Token::make_word("1two3", None),
4655            ],
4656        );
4657    }
4658
4659    #[test]
4660    fn tokenize_period_underscore() {
4661        let sql = String::from("SELECT table._col");
4662        // a dialect that supports underscores in numeric literals
4663        let dialect = PostgreSqlDialect {};
4664        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
4665
4666        let expected = vec![
4667            Token::make_keyword("SELECT"),
4668            Token::Whitespace(Whitespace::Space),
4669            Token::Word(Word {
4670                value: "table".to_string(),
4671                quote_style: None,
4672                keyword: Keyword::TABLE,
4673            }),
4674            Token::Period,
4675            Token::Word(Word {
4676                value: "_col".to_string(),
4677                quote_style: None,
4678                keyword: Keyword::NoKeyword,
4679            }),
4680        ];
4681
4682        compare(expected, tokens);
4683
4684        // Whitespace between the word and ._ is accepted
4685        let sql = String::from("SELECT table ._col");
4686        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
4687        let expected = vec![
4688            Token::make_keyword("SELECT"),
4689            Token::Whitespace(Whitespace::Space),
4690            Token::Word(Word {
4691                value: "table".to_string(),
4692                quote_style: None,
4693                keyword: Keyword::TABLE,
4694            }),
4695            Token::Whitespace(Whitespace::Space),
4696            Token::Period,
4697            Token::Word(Word {
4698                value: "_col".to_string(),
4699                quote_style: None,
4700                keyword: Keyword::NoKeyword,
4701            }),
4702        ];
4703        compare(expected, tokens);
4704
4705        // Without a preceding identifier ._ is still rejected
4706        let err = Tokenizer::new(&dialect, "._abc").tokenize();
4707        assert!(err.is_err(), "expected tokenizer error for bare ._abc");
4708    }
4709
4710    #[test]
4711    fn tokenize_question_mark() {
4712        let dialect = PostgreSqlDialect {};
4713        let sql = "SELECT x ? y";
4714        let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
4715        compare(
4716            tokens,
4717            vec![
4718                Token::make_keyword("SELECT"),
4719                Token::Whitespace(Whitespace::Space),
4720                Token::make_word("x", None),
4721                Token::Whitespace(Whitespace::Space),
4722                Token::Question,
4723                Token::Whitespace(Whitespace::Space),
4724                Token::make_word("y", None),
4725            ],
4726        );
4727    }
4728
4729    #[test]
4730    fn tokenize_multiline_comment_with_comment_hint() {
4731        let sql = String::from("0/*! word */1");
4732
4733        let dialect = MySqlDialect {};
4734        let tokens = Tokenizer::new(&dialect, &sql).tokenize().unwrap();
4735        let expected = vec![
4736            Token::Number("0".to_string(), false),
4737            Token::Whitespace(Whitespace::Space),
4738            Token::Word(Word {
4739                value: "word".to_string(),
4740                quote_style: None,
4741                keyword: Keyword::NoKeyword,
4742            }),
4743            Token::Whitespace(Whitespace::Space),
4744            Token::Number("1".to_string(), false),
4745        ];
4746        compare(expected, tokens);
4747    }
4748
4749    #[test]
4750    fn tokenize_multiline_comment_with_comment_hint_and_version() {
4751        let sql_multi = String::from("0 /*!50110 KEY_BLOCK_SIZE = 1024*/ 1");
4752        let dialect = MySqlDialect {};
4753        let tokens = Tokenizer::new(&dialect, &sql_multi).tokenize().unwrap();
4754        let expected = vec![
4755            Token::Number("0".to_string(), false),
4756            Token::Whitespace(Whitespace::Space),
4757            Token::Whitespace(Whitespace::Space),
4758            Token::Word(Word {
4759                value: "KEY_BLOCK_SIZE".to_string(),
4760                quote_style: None,
4761                keyword: Keyword::KEY_BLOCK_SIZE,
4762            }),
4763            Token::Whitespace(Whitespace::Space),
4764            Token::Eq,
4765            Token::Whitespace(Whitespace::Space),
4766            Token::Number("1024".to_string(), false),
4767            Token::Whitespace(Whitespace::Space),
4768            Token::Number("1".to_string(), false),
4769        ];
4770        compare(expected, tokens);
4771
4772        let tokens = Tokenizer::new(&dialect, "0 /*!50110 */ 1")
4773            .tokenize()
4774            .unwrap();
4775        compare(
4776            vec![
4777                Token::Number("0".to_string(), false),
4778                Token::Whitespace(Whitespace::Space),
4779                Token::Whitespace(Whitespace::Space),
4780                Token::Whitespace(Whitespace::Space),
4781                Token::Number("1".to_string(), false),
4782            ],
4783            tokens,
4784        );
4785
4786        let tokens = Tokenizer::new(&dialect, "0 /*!*/ 1").tokenize().unwrap();
4787        compare(
4788            vec![
4789                Token::Number("0".to_string(), false),
4790                Token::Whitespace(Whitespace::Space),
4791                Token::Whitespace(Whitespace::Space),
4792                Token::Number("1".to_string(), false),
4793            ],
4794            tokens,
4795        );
4796        let tokens = Tokenizer::new(&dialect, "0 /*!   */ 1").tokenize().unwrap();
4797        compare(
4798            vec![
4799                Token::Number("0".to_string(), false),
4800                Token::Whitespace(Whitespace::Space),
4801                Token::Whitespace(Whitespace::Space),
4802                Token::Whitespace(Whitespace::Space),
4803                Token::Whitespace(Whitespace::Space),
4804                Token::Whitespace(Whitespace::Space),
4805                Token::Number("1".to_string(), false),
4806            ],
4807            tokens,
4808        );
4809    }
4810
4811    #[test]
4812    fn tokenize_comment_hint_underscore_after_non_word_is_error() {
4813        let sql = "SELECT 1 /*!50110 ._a */ FROM t";
4814        let dialect = MySqlDialect {};
4815        let err = Tokenizer::new(&dialect, sql).tokenize().unwrap_err();
4816        assert_eq!(
4817            err,
4818            TokenizerError {
4819                message: "Unexpected character '_'".to_string(),
4820                location: Location::new(1, 11),
4821            }
4822        );
4823    }
4824
4825    #[test]
4826    fn tokenize_into_existing_buffer_keeps_qualified_name_context() {
4827        let dialect = MySqlDialect {};
4828        let mut tokens = Tokenizer::new(&dialect, "SELECT t ")
4829            .tokenize_with_location()
4830            .unwrap();
4831        Tokenizer::new(&dialect, "._col FROM t")
4832            .tokenize_with_location_into_buf(&mut tokens)
4833            .unwrap();
4834        let tokens = tokens
4835            .into_iter()
4836            .map(|token| token.token)
4837            .filter(|token| !matches!(token, Token::Whitespace(_)))
4838            .collect();
4839        compare(
4840            vec![
4841                Token::make_keyword("SELECT"),
4842                Token::make_word("t", None),
4843                Token::Period,
4844                Token::make_word("_col", None),
4845                Token::make_keyword("FROM"),
4846                Token::make_word("t", None),
4847            ],
4848            tokens,
4849        );
4850    }
4851
4852    #[test]
4853    fn tokenize_lt() {
4854        all_dialects().tokenizes_to(
4855            "select a <-50",
4856            vec![
4857                Token::make_keyword("select"),
4858                Token::Whitespace(Whitespace::Space),
4859                Token::make_word("a", None),
4860                Token::Whitespace(Whitespace::Space),
4861                Token::Lt,
4862                Token::Minus,
4863                Token::Number("50".to_string(), false),
4864            ],
4865        );
4866        all_dialects().tokenizes_to(
4867            "select a <+50",
4868            vec![
4869                Token::make_keyword("select"),
4870                Token::Whitespace(Whitespace::Space),
4871                Token::make_word("a", None),
4872                Token::Whitespace(Whitespace::Space),
4873                Token::Lt,
4874                Token::Plus,
4875                Token::Number("50".to_string(), false),
4876            ],
4877        );
4878        all_dialects().tokenizes_to(
4879            "select a <=-50",
4880            vec![
4881                Token::make_keyword("select"),
4882                Token::Whitespace(Whitespace::Space),
4883                Token::make_word("a", None),
4884                Token::Whitespace(Whitespace::Space),
4885                Token::LtEq,
4886                Token::Minus,
4887                Token::Number("50".to_string(), false),
4888            ],
4889        );
4890        all_dialects().tokenizes_to(
4891            "select a <=+50",
4892            vec![
4893                Token::make_keyword("select"),
4894                Token::Whitespace(Whitespace::Space),
4895                Token::make_word("a", None),
4896                Token::Whitespace(Whitespace::Space),
4897                Token::LtEq,
4898                Token::Plus,
4899                Token::Number("50".to_string(), false),
4900            ],
4901        );
4902        all_dialects_where(|d| d.supports_geometric_types()).tokenizes_to(
4903            "select a <->b",
4904            vec![
4905                Token::make_keyword("select"),
4906                Token::Whitespace(Whitespace::Space),
4907                Token::make_word("a", None),
4908                Token::Whitespace(Whitespace::Space),
4909                Token::TwoWayArrow,
4910                Token::make_word("b", None),
4911            ],
4912        );
4913
4914        all_dialects().tokenizes_to(
4915            "select a <-b",
4916            vec![
4917                Token::make_keyword("select"),
4918                Token::Whitespace(Whitespace::Space),
4919                Token::make_word("a", None),
4920                Token::Whitespace(Whitespace::Space),
4921                Token::Lt,
4922                Token::Minus,
4923                Token::make_word("b", None),
4924            ],
4925        );
4926        all_dialects().tokenizes_to(
4927            "select a <+b",
4928            vec![
4929                Token::make_keyword("select"),
4930                Token::Whitespace(Whitespace::Space),
4931                Token::make_word("a", None),
4932                Token::Whitespace(Whitespace::Space),
4933                Token::Lt,
4934                Token::Plus,
4935                Token::make_word("b", None),
4936            ],
4937        );
4938    }
4939
4940    #[test]
4941    fn test_word_display_quote_escaping() {
4942        assert_eq!(
4943            Word {
4944                value: "a\"b".to_string(),
4945                quote_style: Some('"'),
4946                keyword: Keyword::NoKeyword,
4947            }
4948            .to_string(),
4949            "\"a\"\"b\""
4950        );
4951        assert_eq!(
4952            Word {
4953                value: "a`b".to_string(),
4954                quote_style: Some('`'),
4955                keyword: Keyword::NoKeyword,
4956            }
4957            .to_string(),
4958            "`a``b`"
4959        );
4960        assert_eq!(
4961            Word {
4962                value: "a b".to_string(),
4963                quote_style: Some('['),
4964                keyword: Keyword::NoKeyword,
4965            }
4966            .to_string(),
4967            "[a b]"
4968        );
4969    }
4970
4971    #[test]
4972    fn tokenize_period_before_digits_after_identifier_or_bracket() {
4973        let dialect = ClickHouseDialect {};
4974        for (sql, expected) in [
4975            (
4976                "t.1",
4977                vec![
4978                    Token::make_word("t", None),
4979                    Token::Period,
4980                    Token::Number("1".to_string(), false),
4981                ],
4982            ),
4983            (
4984                "(1).1",
4985                vec![
4986                    Token::LParen,
4987                    Token::Number("1".to_string(), false),
4988                    Token::RParen,
4989                    Token::Period,
4990                    Token::Number("1".to_string(), false),
4991                ],
4992            ),
4993            (
4994                "a[1].1",
4995                vec![
4996                    Token::make_word("a", None),
4997                    Token::LBracket,
4998                    Token::Number("1".to_string(), false),
4999                    Token::RBracket,
5000                    Token::Period,
5001                    Token::Number("1".to_string(), false),
5002                ],
5003            ),
5004            (
5005                "t.1.2",
5006                vec![
5007                    Token::make_word("t", None),
5008                    Token::Period,
5009                    Token::Number("1".to_string(), false),
5010                    Token::Period,
5011                    Token::Number("2".to_string(), false),
5012                ],
5013            ),
5014            (
5015                "t .1",
5016                vec![
5017                    Token::make_word("t", None),
5018                    Token::Whitespace(Whitespace::Space),
5019                    Token::Number(".1".to_string(), false),
5020                ],
5021            ),
5022            ("1.5", vec![Token::Number("1.5".to_string(), false)]),
5023            (".5", vec![Token::Number(".5".to_string(), false)]),
5024        ] {
5025            let tokens = Tokenizer::new(&dialect, sql).tokenize().unwrap();
5026            compare(expected, tokens);
5027        }
5028
5029        let tokens = Tokenizer::new(&GenericDialect {}, "t.1")
5030            .tokenize()
5031            .unwrap();
5032        compare(
5033            vec![
5034                Token::make_word("t", None),
5035                Token::Number(".1".to_string(), false),
5036            ],
5037            tokens,
5038        );
5039    }
5040
5041    #[test]
5042    fn tokenize_copy_from_stdin_payload() {
5043        let sql = "COPY t FROM STDIN; SELECT 1;\nrow1\n\\.\nSELECT 2;";
5044        let tokens = Tokenizer::new(&PostgreSqlDialect {}, sql)
5045            .tokenize()
5046            .unwrap();
5047        assert_eq!(
5048            tokens,
5049            vec![
5050                Token::make_word("COPY", None),
5051                Token::Whitespace(Whitespace::Space),
5052                Token::make_word("t", None),
5053                Token::Whitespace(Whitespace::Space),
5054                Token::make_word("FROM", None),
5055                Token::Whitespace(Whitespace::Space),
5056                Token::make_word("STDIN", None),
5057                Token::CopyData {
5058                    data: "row1\n".to_string(),
5059                    terminated: true,
5060                },
5061                Token::SemiColon,
5062                Token::Whitespace(Whitespace::Space),
5063                Token::make_word("SELECT", None),
5064                Token::Whitespace(Whitespace::Space),
5065                Token::Number("1".to_string(), false),
5066                Token::SemiColon,
5067                Token::Whitespace(Whitespace::Newline),
5068                Token::make_word("SELECT", None),
5069                Token::Whitespace(Whitespace::Space),
5070                Token::Number("2".to_string(), false),
5071                Token::SemiColon,
5072            ]
5073        );
5074    }
5075
5076    #[test]
5077    fn tokenize_qualified_underscore_across_copy_payload() {
5078        for sql in [
5079            "COPY t FROM STDIN; SELECT t ._a FROM t;\nrow1\n\\.\n",
5080            "COPY t FROM STDIN; SELECT t\nrow1\n\\.\n ._a FROM t;",
5081        ] {
5082            let tokens: Vec<_> = Tokenizer::new(&PostgreSqlDialect {}, sql)
5083                .tokenize()
5084                .unwrap()
5085                .into_iter()
5086                .filter(|token| !matches!(token, Token::Whitespace(_)))
5087                .collect();
5088            assert_eq!(
5089                tokens,
5090                vec![
5091                    Token::make_word("COPY", None),
5092                    Token::make_word("t", None),
5093                    Token::make_word("FROM", None),
5094                    Token::make_word("STDIN", None),
5095                    Token::CopyData {
5096                        data: "row1\n".to_string(),
5097                        terminated: true,
5098                    },
5099                    Token::SemiColon,
5100                    Token::make_word("SELECT", None),
5101                    Token::make_word("t", None),
5102                    Token::Period,
5103                    Token::make_word("_a", None),
5104                    Token::make_word("FROM", None),
5105                    Token::make_word("t", None),
5106                    Token::SemiColon,
5107                ],
5108                "{sql}"
5109            );
5110        }
5111    }
5112
5113    #[test]
5114    fn tokenize_copy_from_stdin_payload_span() {
5115        let sql = "COPY t FROM STDIN;\nrow1\n\\.";
5116        let tokens = Tokenizer::new(&PostgreSqlDialect {}, sql)
5117            .tokenize_with_location()
5118            .unwrap();
5119        let payload = tokens
5120            .iter()
5121            .find(|t| matches!(t.token, Token::CopyData { .. }))
5122            .unwrap();
5123        assert_eq!(
5124            payload.span,
5125            Span::new(Location::new(2, 1), Location::new(3, 3))
5126        );
5127        assert_eq!(
5128            payload.token,
5129            Token::CopyData {
5130                data: "row1\n".to_string(),
5131                terminated: true,
5132            }
5133        );
5134    }
5135
5136    #[test]
5137    fn tokenize_copy_from_stdin_payload_malformed_semicolon_line() {
5138        // An unterminated string on the `;` line fails the capture.
5139        let sql = "COPY t FROM STDIN; 'unterminated";
5140        let err = Tokenizer::new(&PostgreSqlDialect {}, sql)
5141            .tokenize()
5142            .unwrap_err();
5143        assert_eq!(
5144            err,
5145            TokenizerError {
5146                message: "Unterminated string literal".to_string(),
5147                location: Location::new(1, 20),
5148            }
5149        );
5150    }
5151
5152    #[test]
5153    fn tokenize_copy_from_stdin_payload_not_captured() {
5154        // A `FROM STDIN` nested in parens, or a statement not starting with `COPY`,
5155        // keeps the data out of a payload token.
5156        for sql in [
5157            "COPY (SELECT x FROM stdin) TO STDOUT;\nrow1\n\\.\n",
5158            "SELECT * FROM stdin;\nrow1\n\\.\n",
5159            "COPY t TO STDOUT;\nrow1\n\\.\n",
5160        ] {
5161            let tokens = Tokenizer::new(&PostgreSqlDialect {}, sql)
5162                .tokenize()
5163                .unwrap();
5164            assert!(
5165                tokens.iter().all(|t| !matches!(t, Token::CopyData { .. })),
5166                "{sql}"
5167            );
5168        }
5169    }
5170}