tokenizer
ModuleSQL tokenizers: SQL text to Tokens, per dialect.
A Tokenizer splits SQL into keywords, identifiers, literals,
operators, punctuation, placeholders, comments and whitespace, each with
its byte position. Tokenizer::filter drops whitespace and comments,
which is what the Parser reads. Token values
borrow the SQL text where they can, so tokenizing allocates only the
token list.
PHP: Utopia\Query\Tokenizer\*.
| PHP | Rust |
|---|---|
Tokenizer\Tokenizer | Tokenizer::new |
Tokenizer\MySQL | Tokenizer::mysql |
Tokenizer\MariaDB | Tokenizer::mariadb |
Tokenizer\PostgreSQL | Tokenizer::postgresql |
Tokenizer\SQLite | Tokenizer::sqlite |
Tokenizer\ClickHouse | Tokenizer::clickhouse |
Tokenizer::tokenize() | Tokenizer::tokenize |
Tokenizer::filter() | Tokenizer::filter |
Tokenizer\Token | Token |
Tokenizer\TokenType | TokenType |
use utopia_query::tokenizer::{TokenType, Tokenizer};
let tokens = Tokenizer::filter(Tokenizer::new().tokenize("SELECT * FROM users")?);
let kinds: Vec<TokenType> = tokens.iter().map(|t| t.kind).collect();
assert_eq!(kinds, [TokenType::Keyword, TokenType::Star, TokenType::Keyword, TokenType::Identifier, TokenType::Eof]);
assert_eq!(tokens[3].text(), "users");use Utopia\Query\Tokenizer\Tokenizer;
$tokens = Tokenizer::filter((new Tokenizer())->tokenize('SELECT * FROM users'));
echo implode(' ', array_map(fn ($t) => $t->type->name, $tokens)), "\n"; // Keyword Star Keyword Identifier Eof
echo $tokens[3]->value, "\n"; // usersContents
use utopia_query::tokenizer::Token;pub struct Token<'a> {
pub kind: TokenType,
pub value: Cow<'a, [u8]>,
pub position: usize,
}One token: its type, its text and its byte position in the SQL.
The value is bytes, as PHP's strings are: a character the tokenizer does
not know outside quotes is one operator token per byte, so a multi-byte
UTF-8 character becomes several tokens that are not UTF-8 on their own
(Token::text reads a value as text). It borrows the SQL text, except
for keywords, NULL and booleans (upper-cased) and tokens of MySQL SQL
whose # comments were rewritten.
PHP: Utopia\Query\Tokenizer\Token (type, value, position).
use utopia_query::tokenizer::Tokenizer;pub struct Tokenizer {
// private fields
}Splits SQL into Tokens, the way one dialect writes it.
Dialects differ in the identifier quote (a backtick, or a double quote
for PostgreSQL and SQLite), in MySQL's # line comments and in
PostgreSQL's multi-character operators (@>, <@, <=>, <->, <#>,
?|, ?&).
PHP: Utopia\Query\Tokenizer\Tokenizer and its dialect subclasses.
Default.use utopia_query::tokenizer::TokenType;pub enum TokenType {
Keyword,
Identifier,
QuotedIdentifier,
Integer,
Float,
String,
Boolean,
Null,
Operator,
LeftParen,
RightParen,
Comma,
Semicolon,
Dot,
Star,
Placeholder,
NamedPlaceholder,
NumberedPlaceholder,
LineComment,
BlockComment,
Whitespace,
Eof,
}What a Token is.
PHP: Utopia\Query\Tokenizer\TokenType.