Struct Parser
pub struct Parser<'a> {
tokens: Vec<TokenWithSpan>,
index: usize,
state: ParserState,
dialect: &'a (dyn Dialect + 'static),
options: ParserOptions,
recursion_counter: RecursionCounter,
}Expand description
A SQL Parser
This struct is the main entry point for parsing SQL queries.
§Functionality:
- Parsing SQL: see examples on
Parser::newandParser::parse_sql - Controlling recursion: See
Parser::with_recursion_limit - Controlling parser options: See
Parser::with_options - Providing your own tokens: See
Parser::with_tokens
§Internals
The parser uses a Tokenizer to tokenize the input SQL string into a
Vec of TokenWithSpans and maintains an index to the current token
being processed. The token vec may contain multiple SQL statements.
- The “current” token is the token at
index - 1 - The “next” token is the token at
index - The “previous” token is the token at
index - 2
If index is equal to the length of the token stream, the ‘next’ token is
Token::EOF.
For example, the SQL string “SELECT * FROM foo” will be tokenized into following tokens:
[
"SELECT", // token index 0
" ", // whitespace
"*",
" ",
"FROM",
" ",
"foo"
]Fields§
§tokens: Vec<TokenWithSpan>§index: usize§state: ParserState§dialect: &'a (dyn Dialect + 'static)§options: ParserOptions§recursion_counter: RecursionCounterImplementations§
§impl Parser<'_>
impl Parser<'_>
pub fn parse_alter_role(&mut self) -> Result<Statement, ParserError>
pub fn parse_alter_policy(&mut self) -> Result<Statement, ParserError>
pub fn parse_alter_policy(&mut self) -> Result<Statement, ParserError>
Parse ALTER POLICY statement
ALTER POLICY policy_name ON table_name [ RENAME TO new_name ]
or
ALTER POLICY policy_name ON table_name
[ TO { role_name | PUBLIC | CURRENT_ROLE | CURRENT_USER | SESSION_USER } [, ...] ]
[ USING ( using_expression ) ]
[ WITH CHECK ( check_expression ) ]pub fn parse_alter_connector(&mut self) -> Result<Statement, ParserError>
pub fn parse_alter_connector(&mut self) -> Result<Statement, ParserError>
Parse an ALTER CONNECTOR statement
ALTER CONNECTOR connector_name SET DCPROPERTIES(property_name=property_value, ...);
ALTER CONNECTOR connector_name SET URL new_url;
ALTER CONNECTOR connector_name SET OWNER [USER|ROLE] user_or_role;§impl<'a> Parser<'a>
impl<'a> Parser<'a>
pub fn new(dialect: &'a (dyn Dialect + 'static)) -> Parser<'a>
pub fn new(dialect: &'a (dyn Dialect + 'static)) -> Parser<'a>
Create a parser for a Dialect
See also Parser::parse_sql
Example:
let dialect = GenericDialect{};
let statements = Parser::new(&dialect)
.try_with_sql("SELECT * FROM foo")?
.parse_statements()?;pub fn with_recursion_limit(self, recursion_limit: usize) -> Parser<'a>
pub fn with_recursion_limit(self, recursion_limit: usize) -> Parser<'a>
Specify the maximum recursion limit while parsing.
Parser prevents stack overflows by returning
ParserError::RecursionLimitExceeded if the parser exceeds
this depth while processing the query.
Example:
let dialect = GenericDialect{};
let result = Parser::new(&dialect)
.with_recursion_limit(1)
.try_with_sql("SELECT * FROM foo WHERE (a OR (b OR (c OR d)))")?
.parse_statements();
assert_eq!(result, Err(ParserError::RecursionLimitExceeded));Note: when “recursive-protection” feature is enabled, this crate uses additional stack overflow protection
pub fn with_options(self, options: ParserOptions) -> Parser<'a>
pub fn with_options(self, options: ParserOptions) -> Parser<'a>
Specify additional parser options
Parser supports additional options (ParserOptions)
that allow you to mix & match behavior otherwise constrained
to certain dialects (e.g. trailing commas).
Example:
let dialect = GenericDialect{};
let options = ParserOptions::new()
.with_trailing_commas(true)
.with_unescape(false);
let result = Parser::new(&dialect)
.with_options(options)
.try_with_sql("SELECT a, b, COUNT(*), FROM foo GROUP BY a, b,")?
.parse_statements();
assert!(matches!(result, Ok(_)));pub fn with_tokens_with_locations(
self,
tokens: Vec<TokenWithSpan>,
) -> Parser<'a>
pub fn with_tokens_with_locations( self, tokens: Vec<TokenWithSpan>, ) -> Parser<'a>
Reset this parser to parse the specified token stream
pub fn with_tokens(self, tokens: Vec<Token>) -> Parser<'a>
pub fn with_tokens(self, tokens: Vec<Token>) -> Parser<'a>
Reset this parser state to parse the specified tokens
pub fn try_with_sql(self, sql: &str) -> Result<Parser<'a>, ParserError>
pub fn try_with_sql(self, sql: &str) -> Result<Parser<'a>, ParserError>
Tokenize the sql string and sets this Parser’s state to
parse the resulting tokens
Returns an error if there was an error tokenizing the SQL string.
See example on Parser::new() for an example
pub fn parse_statements(&mut self) -> Result<Vec<Statement>, ParserError>
pub fn parse_statements(&mut self) -> Result<Vec<Statement>, ParserError>
Parse potentially multiple statements
Example
let dialect = GenericDialect{};
let statements = Parser::new(&dialect)
// Parse a SQL string with 2 separate statements
.try_with_sql("SELECT * FROM foo; SELECT * FROM bar;")?
.parse_statements()?;
assert_eq!(statements.len(), 2);pub fn parse_sql(
dialect: &(dyn Dialect + 'static),
sql: &str,
) -> Result<Vec<Statement>, ParserError>
pub fn parse_sql( dialect: &(dyn Dialect + 'static), sql: &str, ) -> Result<Vec<Statement>, ParserError>
Convenience method to parse a string with one or more SQL statements into produce an Abstract Syntax Tree (AST).
Example
let dialect = GenericDialect{};
let statements = Parser::parse_sql(
&dialect, "SELECT * FROM foo"
)?;
assert_eq!(statements.len(), 1);pub fn parse_statement(&mut self) -> Result<Statement, ParserError>
pub fn parse_statement(&mut self) -> Result<Statement, ParserError>
Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.), stopping before the statement separator, if any.
pub fn parse_case_stmt(&mut self) -> Result<Statement, ParserError>
pub fn parse_case_stmt(&mut self) -> Result<Statement, ParserError>
Parse a CASE statement.
See Statement::Case
pub fn parse_if_stmt(&mut self) -> Result<Statement, ParserError>
pub fn parse_if_stmt(&mut self) -> Result<Statement, ParserError>
Parse an IF statement.
See Statement::If
pub fn parse_raise_stmt(&mut self) -> Result<Statement, ParserError>
pub fn parse_raise_stmt(&mut self) -> Result<Statement, ParserError>
Parse a RAISE statement.
See Statement::Raise
pub fn parse_comment(&mut self) -> Result<Statement, ParserError>
pub fn parse_flush(&mut self) -> Result<Statement, ParserError>
pub fn parse_msck(&mut self) -> Result<Statement, ParserError>
pub fn parse_truncate(&mut self) -> Result<Statement, ParserError>
pub fn parse_attach_duckdb_database_options( &mut self, ) -> Result<Vec<AttachDuckDBDatabaseOption>, ParserError>
pub fn parse_attach_duckdb_database(&mut self) -> Result<Statement, ParserError>
pub fn parse_detach_duckdb_database(&mut self) -> Result<Statement, ParserError>
pub fn parse_attach_database(&mut self) -> Result<Statement, ParserError>
pub fn parse_analyze(&mut self) -> Result<Statement, ParserError>
pub fn parse_wildcard_expr(&mut self) -> Result<Expr, ParserError>
pub fn parse_wildcard_expr(&mut self) -> Result<Expr, ParserError>
Parse a new expression including wildcard & qualified wildcard.
pub fn parse_expr(&mut self) -> Result<Expr, ParserError>
pub fn parse_expr(&mut self) -> Result<Expr, ParserError>
Parse a new expression.
pub fn parse_expr_with_alias_and_order_by( &mut self, ) -> Result<ExprWithAliasAndOrderBy, ParserError>
pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError>
pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError>
Parse tokens until the precedence changes.
pub fn parse_assert(&mut self) -> Result<Statement, ParserError>
pub fn parse_savepoint(&mut self) -> Result<Statement, ParserError>
pub fn parse_release(&mut self) -> Result<Statement, ParserError>
pub fn parse_listen(&mut self) -> Result<Statement, ParserError>
pub fn parse_unlisten(&mut self) -> Result<Statement, ParserError>
pub fn parse_notify(&mut self) -> Result<Statement, ParserError>
pub fn parse_rename(&mut self) -> Result<Statement, ParserError>
pub fn parse_rename(&mut self) -> Result<Statement, ParserError>
Parses a RENAME TABLE statement. See Statement::RenameTable
pub fn parse_prefix(&mut self) -> Result<Expr, ParserError>
pub fn parse_prefix(&mut self) -> Result<Expr, ParserError>
Parse an expression prefix.
pub fn parse_compound_expr(
&mut self,
root: Expr,
chain: Vec<AccessExpr>,
) -> Result<Expr, ParserError>
pub fn parse_compound_expr( &mut self, root: Expr, chain: Vec<AccessExpr>, ) -> Result<Expr, ParserError>
Try to parse an Expr::CompoundFieldAccess like a.b.c or a.b[1].c.
If all the fields are Expr::Identifiers, return an Expr::CompoundIdentifier instead.
If only the root exists, return the root.
Parses compound expressions which may be delimited by period
or bracket notation.
For example: a.b.c, a.b[1].
pub fn parse_utility_options( &mut self, ) -> Result<Vec<UtilityOption>, ParserError>
pub fn parse_function(&mut self, name: ObjectName) -> Result<Expr, ParserError>
pub fn parse_time_functions( &mut self, name: ObjectName, ) -> Result<Expr, ParserError>
pub fn parse_window_frame_units( &mut self, ) -> Result<WindowFrameUnits, ParserError>
pub fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError>
pub fn parse_window_frame_bound(
&mut self,
) -> Result<WindowFrameBound, ParserError>
pub fn parse_window_frame_bound( &mut self, ) -> Result<WindowFrameBound, ParserError>
Parse CURRENT ROW or { <positive number> | UNBOUNDED } { PRECEDING | FOLLOWING }
pub fn parse_case_expr(&mut self) -> Result<Expr, ParserError>
pub fn parse_optional_cast_format( &mut self, ) -> Result<Option<CastFormat>, ParserError>
pub fn parse_optional_time_zone(&mut self) -> Result<Option<Value>, ParserError>
pub fn parse_convert_expr(&mut self, is_try: bool) -> Result<Expr, ParserError>
pub fn parse_convert_expr(&mut self, is_try: bool) -> Result<Expr, ParserError>
Parse a SQL CONVERT function:
CONVERT('héhé' USING utf8mb4)(MySQL)CONVERT('héhé', CHAR CHARACTER SET utf8mb4)(MySQL)CONVERT(DECIMAL(10, 5), 42)(MSSQL) - the type comes first
pub fn parse_cast_expr(&mut self, kind: CastKind) -> Result<Expr, ParserError>
pub fn parse_cast_expr(&mut self, kind: CastKind) -> Result<Expr, ParserError>
Parse a SQL CAST function e.g. CAST(expr AS FLOAT)
pub fn parse_exists_expr(&mut self, negated: bool) -> Result<Expr, ParserError>
pub fn parse_exists_expr(&mut self, negated: bool) -> Result<Expr, ParserError>
Parse a SQL EXISTS expression e.g. WHERE EXISTS(SELECT ...).
pub fn parse_extract_expr(&mut self) -> Result<Expr, ParserError>
pub fn parse_ceil_floor_expr( &mut self, is_ceil: bool, ) -> Result<Expr, ParserError>
pub fn parse_position_expr(&mut self, ident: Ident) -> Result<Expr, ParserError>
pub fn parse_substring(&mut self) -> Result<Expr, ParserError>
pub fn parse_overlay_expr(&mut self) -> Result<Expr, ParserError>
pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError>
pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError>
TRIM ([WHERE] ['text' FROM] 'text')
TRIM ('text')
TRIM(<expr>, [, characters]) -- only Snowflake or BigQuerypub fn parse_trim_where(&mut self) -> Result<TrimWhereField, ParserError>
pub fn parse_array_expr(&mut self, named: bool) -> Result<Expr, ParserError>
pub fn parse_array_expr(&mut self, named: bool) -> Result<Expr, ParserError>
Parses an array expression [ex1, ex2, ..]
if named is true, came from an expression like ARRAY[ex1, ex2]
pub fn parse_listagg_on_overflow( &mut self, ) -> Result<Option<ListAggOnOverflow>, ParserError>
pub fn parse_date_time_field(&mut self) -> Result<DateTimeField, ParserError>
pub fn parse_not(&mut self) -> Result<Expr, ParserError>
pub fn parse_match_against(&mut self) -> Result<Expr, ParserError>
pub fn parse_match_against(&mut self) -> Result<Expr, ParserError>
Parses fulltext expressions sqlparser::ast::Expr::MatchAgainst
§Errors
This method will raise an error if the column list is empty or with invalid identifiers, the match expression is not a literal string, or if the search modifier is not valid.
pub fn parse_interval(&mut self) -> Result<Expr, ParserError>
pub fn parse_interval(&mut self) -> Result<Expr, ParserError>
Parse an INTERVAL expression.
Some syntactically valid intervals:
1. INTERVAL '1' DAY
2. INTERVAL '1-1' YEAR TO MONTH
3. INTERVAL '1' SECOND
4. INTERVAL '1:1:1.1' HOUR (5) TO SECOND (5)
5. INTERVAL '1.1' SECOND (2, 2)
6. INTERVAL '1:1' HOUR (5) TO MINUTE (5)
7. (MySql & BigQuery only): INTERVAL 1 DAYNote that we do not currently attempt to parse the quoted value.
pub fn next_token_is_temporal_unit(&mut self) -> bool
pub fn next_token_is_temporal_unit(&mut self) -> bool
Peek at the next token and determine if it is a temporal unit
like second.
pub fn parse_infix(
&mut self,
expr: Expr,
precedence: u8,
) -> Result<Expr, ParserError>
pub fn parse_infix( &mut self, expr: Expr, precedence: u8, ) -> Result<Expr, ParserError>
Parse an operator following an expression
pub fn parse_escape_char(&mut self) -> Result<Option<Value>, ParserError>
pub fn parse_escape_char(&mut self) -> Result<Option<Value>, ParserError>
Parse the ESCAPE CHAR portion of LIKE, ILIKE, and SIMILAR TO
pub fn parse_multi_dim_subscript(
&mut self,
chain: &mut Vec<AccessExpr>,
) -> Result<(), ParserError>
pub fn parse_multi_dim_subscript( &mut self, chain: &mut Vec<AccessExpr>, ) -> Result<(), ParserError>
Parse a multi-dimension array accessing like [1:3][1][1]
pub fn parse_in(
&mut self,
expr: Expr,
negated: bool,
) -> Result<Expr, ParserError>
pub fn parse_in( &mut self, expr: Expr, negated: bool, ) -> Result<Expr, ParserError>
Parses the parens following the [ NOT ] IN operator.
pub fn parse_between(
&mut self,
expr: Expr,
negated: bool,
) -> Result<Expr, ParserError>
pub fn parse_between( &mut self, expr: Expr, negated: bool, ) -> Result<Expr, ParserError>
Parses BETWEEN <low> AND <high>, assuming the BETWEEN keyword was already consumed.
pub fn parse_pg_cast(&mut self, expr: Expr) -> Result<Expr, ParserError>
pub fn parse_pg_cast(&mut self, expr: Expr) -> Result<Expr, ParserError>
Parse a PostgreSQL casting style which is in the form of expr::datatype.
pub fn get_next_precedence(&self) -> Result<u8, ParserError>
pub fn get_next_precedence(&self) -> Result<u8, ParserError>
Get the precedence of the next token
pub fn token_at(&self, index: usize) -> &TokenWithSpan
pub fn token_at(&self, index: usize) -> &TokenWithSpan
Return the token at the given location, or EOF if the index is beyond the length of the current set of tokens.
pub fn peek_token(&self) -> TokenWithSpan
pub fn peek_token(&self) -> TokenWithSpan
Return the first non-whitespace token that has not yet been processed or Token::EOF
See Self::peek_token_ref to avoid the copy.
pub fn peek_token_ref(&self) -> &TokenWithSpan
pub fn peek_token_ref(&self) -> &TokenWithSpan
Return a reference to the first non-whitespace token that has not yet been processed or Token::EOF
pub fn peek_tokens<const N: usize>(&self) -> [Token; N]
pub fn peek_tokens<const N: usize>(&self) -> [Token; N]
Returns the N next non-whitespace tokens that have not yet been
processed.
Example:
let dialect = GenericDialect {};
let mut parser = Parser::new(&dialect).try_with_sql("ORDER BY foo, bar").unwrap();
// Note that Rust infers the number of tokens to peek based on the
// length of the slice pattern!
assert!(matches!(
parser.peek_tokens(),
[
Token::Word(Word { keyword: Keyword::ORDER, .. }),
Token::Word(Word { keyword: Keyword::BY, .. }),
]
));pub fn peek_tokens_with_location<const N: usize>(&self) -> [TokenWithSpan; N]
pub fn peek_tokens_with_location<const N: usize>(&self) -> [TokenWithSpan; N]
Returns the N next non-whitespace tokens with locations that have not
yet been processed.
See Self::peek_token for an example.
pub fn peek_tokens_ref<const N: usize>(&self) -> [&TokenWithSpan; N]
pub fn peek_tokens_ref<const N: usize>(&self) -> [&TokenWithSpan; N]
Returns references to the N next non-whitespace tokens
that have not yet been processed.
See Self::peek_tokens for an example.
pub fn peek_nth_token(&self, n: usize) -> TokenWithSpan
pub fn peek_nth_token(&self, n: usize) -> TokenWithSpan
Return nth non-whitespace token that has not yet been processed
pub fn peek_nth_token_ref(&self, n: usize) -> &TokenWithSpan
pub fn peek_nth_token_ref(&self, n: usize) -> &TokenWithSpan
Return nth non-whitespace token that has not yet been processed
pub fn peek_token_no_skip(&self) -> TokenWithSpan
pub fn peek_token_no_skip(&self) -> TokenWithSpan
Return the first token, possibly whitespace, that has not yet been processed (or None if reached end-of-file).
pub fn peek_nth_token_no_skip(&self, n: usize) -> TokenWithSpan
pub fn peek_nth_token_no_skip(&self, n: usize) -> TokenWithSpan
Return nth token, possibly whitespace, that has not yet been processed.
pub fn next_token(&mut self) -> TokenWithSpan
pub fn next_token(&mut self) -> TokenWithSpan
Advances to the next non-whitespace token and returns a copy.
Please use Self::advance_token and Self::get_current_token to
avoid the copy.
pub fn get_current_index(&self) -> usize
pub fn get_current_index(&self) -> usize
Returns the index of the current token
This can be used with APIs that expect an index, such as
Self::token_at
pub fn next_token_no_skip(&mut self) -> Option<&TokenWithSpan>
pub fn next_token_no_skip(&mut self) -> Option<&TokenWithSpan>
Return the next unprocessed token, possibly whitespace.
pub fn advance_token(&mut self)
pub fn advance_token(&mut self)
Advances the current token to the next non-whitespace token
See Self::get_current_token to get the current token after advancing
pub fn get_current_token(&self) -> &TokenWithSpan
pub fn get_current_token(&self) -> &TokenWithSpan
Returns a reference to the current token
Does not advance the current token.
pub fn get_previous_token(&self) -> &TokenWithSpan
pub fn get_previous_token(&self) -> &TokenWithSpan
Returns a reference to the previous token
Does not advance the current token.
pub fn get_next_token(&self) -> &TokenWithSpan
pub fn get_next_token(&self) -> &TokenWithSpan
Returns a reference to the next token
Does not advance the current token.
pub fn prev_token(&mut self)
pub fn prev_token(&mut self)
Seek back the last one non-whitespace token.
Must be called after next_token(), otherwise might panic. OK to call
after next_token() indicates an EOF.
pub fn expected<T>(
&self,
expected: &str,
found: TokenWithSpan,
) -> Result<T, ParserError>
pub fn expected<T>( &self, expected: &str, found: TokenWithSpan, ) -> Result<T, ParserError>
Report found was encountered instead of expected
pub fn expected_ref<T>(
&self,
expected: &str,
found: &TokenWithSpan,
) -> Result<T, ParserError>
pub fn expected_ref<T>( &self, expected: &str, found: &TokenWithSpan, ) -> Result<T, ParserError>
report found was encountered instead of expected
pub fn expected_at<T>(
&self,
expected: &str,
index: usize,
) -> Result<T, ParserError>
pub fn expected_at<T>( &self, expected: &str, index: usize, ) -> Result<T, ParserError>
Report that the token at index was found instead of expected.
pub fn parse_keyword(&mut self, expected: Keyword) -> bool
pub fn parse_keyword(&mut self, expected: Keyword) -> bool
If the current token is the expected keyword, consume it and returns
true. Otherwise, no tokens are consumed and returns false.
pub fn peek_keyword(&self, expected: Keyword) -> bool
pub fn parse_keyword_with_tokens(
&mut self,
expected: Keyword,
tokens: &[Token],
) -> bool
pub fn parse_keyword_with_tokens( &mut self, expected: Keyword, tokens: &[Token], ) -> bool
If the current token is the expected keyword followed by
specified tokens, consume them and returns true.
Otherwise, no tokens are consumed and returns false.
Note that if the length of tokens is too long, this function will
not be efficient as it does a loop on the tokens with peek_nth_token
each time.
pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool
pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool
If the current and subsequent tokens exactly match the keywords
sequence, consume them and returns true. Otherwise, no tokens are
consumed and returns false
pub fn peek_one_of_keywords(&self, keywords: &[Keyword]) -> Option<Keyword>
pub fn peek_one_of_keywords(&self, keywords: &[Keyword]) -> Option<Keyword>
If the current token is one of the given keywords, returns the keyword
that matches, without consuming the token. Otherwise, returns None.
pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword>
pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword>
If the current token is one of the given keywords, consume the token
and return the keyword that matches. Otherwise, no tokens are consumed
and returns None.
pub fn expect_one_of_keywords(
&mut self,
keywords: &[Keyword],
) -> Result<Keyword, ParserError>
pub fn expect_one_of_keywords( &mut self, keywords: &[Keyword], ) -> Result<Keyword, ParserError>
If the current token is one of the expected keywords, consume the token and return the keyword that matches. Otherwise, return an error.
pub fn expect_keyword(
&mut self,
expected: Keyword,
) -> Result<TokenWithSpan, ParserError>
pub fn expect_keyword( &mut self, expected: Keyword, ) -> Result<TokenWithSpan, ParserError>
If the current token is the expected keyword, consume the token.
Otherwise, return an error.
pub fn expect_keyword_is(
&mut self,
expected: Keyword,
) -> Result<(), ParserError>
pub fn expect_keyword_is( &mut self, expected: Keyword, ) -> Result<(), ParserError>
If the current token is the expected keyword, consume the token.
Otherwise, return an error.
This differs from expect_keyword only in that the matched keyword token is not returned.
pub fn expect_keywords(
&mut self,
expected: &[Keyword],
) -> Result<(), ParserError>
pub fn expect_keywords( &mut self, expected: &[Keyword], ) -> Result<(), ParserError>
If the current and subsequent tokens exactly match the keywords
sequence, consume them and returns Ok. Otherwise, return an Error.
pub fn consume_token(&mut self, expected: &Token) -> bool
pub fn consume_token(&mut self, expected: &Token) -> bool
Consume the next token if it matches the expected token, otherwise return false
See Self::advance_token to consume the token unconditionally
pub fn consume_tokens(&mut self, tokens: &[Token]) -> bool
pub fn consume_tokens(&mut self, tokens: &[Token]) -> bool
If the current and subsequent tokens exactly match the tokens
sequence, consume them and returns true. Otherwise, no tokens are
consumed and returns false
pub fn expect_token(
&mut self,
expected: &Token,
) -> Result<TokenWithSpan, ParserError>
pub fn expect_token( &mut self, expected: &Token, ) -> Result<TokenWithSpan, ParserError>
Bail out if the current token is not an expected keyword, or consume it if it is
pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError>
pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError>
Parse a comma-separated list of 1+ SelectItem
pub fn parse_actions_list(&mut self) -> Result<Vec<Action>, ParserError>
pub fn parse_comma_separated<T, F>(
&mut self,
f: F,
) -> Result<Vec<T>, ParserError>
pub fn parse_comma_separated<T, F>( &mut self, f: F, ) -> Result<Vec<T>, ParserError>
Parse a comma-separated list of 1+ items accepted by F
pub fn parse_keyword_separated<T, F>(
&mut self,
keyword: Keyword,
f: F,
) -> Result<Vec<T>, ParserError>
pub fn parse_keyword_separated<T, F>( &mut self, keyword: Keyword, f: F, ) -> Result<Vec<T>, ParserError>
Parse a keyword-separated list of 1+ items accepted by F
pub fn parse_parenthesized<T, F>(&mut self, f: F) -> Result<T, ParserError>
pub fn parse_comma_separated0<T, F>(
&mut self,
f: F,
end_token: Token,
) -> Result<Vec<T>, ParserError>
pub fn parse_comma_separated0<T, F>( &mut self, f: F, end_token: Token, ) -> Result<Vec<T>, ParserError>
Parse a comma-separated list of 0+ items accepted by F
end_token- expected end token for the closure (e.g. Token::RParen, Token::RBrace …)
pub fn maybe_parse<T, F>(&mut self, f: F) -> Result<Option<T>, ParserError>
pub fn maybe_parse<T, F>(&mut self, f: F) -> Result<Option<T>, ParserError>
Run a parser method f, reverting back to the current position if unsuccessful.
Returns ParserError::RecursionLimitExceeded if f returns a RecursionLimitExceeded.
Returns Ok(None) if f returns any other error.
pub fn try_parse<T, F>(&mut self, f: F) -> Result<T, ParserError>
pub fn try_parse<T, F>(&mut self, f: F) -> Result<T, ParserError>
Run a parser method f, reverting back to the current position if unsuccessful.
pub fn parse_all_or_distinct(&mut self) -> Result<Option<Distinct>, ParserError>
pub fn parse_all_or_distinct(&mut self) -> Result<Option<Distinct>, ParserError>
Parse either ALL, DISTINCT or DISTINCT ON (...). Returns None if ALL is parsed
and results in a ParserError if both ALL and DISTINCT are found.
pub fn parse_create(&mut self) -> Result<Statement, ParserError>
pub fn parse_create(&mut self) -> Result<Statement, ParserError>
Parse a SQL CREATE statement
pub fn parse_create_secret(
&mut self,
or_replace: bool,
temporary: bool,
persistent: bool,
) -> Result<Statement, ParserError>
pub fn parse_create_secret( &mut self, or_replace: bool, temporary: bool, persistent: bool, ) -> Result<Statement, ParserError>
See DuckDB Docs for more details.
pub fn parse_cache_table(&mut self) -> Result<Statement, ParserError>
pub fn parse_cache_table(&mut self) -> Result<Statement, ParserError>
Parse a CACHE TABLE statement
pub fn parse_as_query(&mut self) -> Result<(bool, Box<Query>), ParserError>
pub fn parse_as_query(&mut self) -> Result<(bool, Box<Query>), ParserError>
Parse ‘AS’ before as query,such as WITH XXX AS SELECT XXX oer CACHE TABLE AS SELECT XXX
pub fn parse_uncache_table(&mut self) -> Result<Statement, ParserError>
pub fn parse_uncache_table(&mut self) -> Result<Statement, ParserError>
Parse a UNCACHE TABLE statement
pub fn parse_create_virtual_table(&mut self) -> Result<Statement, ParserError>
pub fn parse_create_virtual_table(&mut self) -> Result<Statement, ParserError>
SQLite-specific CREATE VIRTUAL TABLE
pub fn parse_create_schema(&mut self) -> Result<Statement, ParserError>
pub fn parse_create_database(&mut self) -> Result<Statement, ParserError>
pub fn parse_optional_create_function_using( &mut self, ) -> Result<Option<CreateFunctionUsing>, ParserError>
pub fn parse_create_function( &mut self, or_alter: bool, or_replace: bool, temporary: bool, ) -> Result<Statement, ParserError>
pub fn parse_drop_trigger(&mut self) -> Result<Statement, ParserError>
pub fn parse_drop_trigger(&mut self) -> Result<Statement, ParserError>
Parse statements of the DropTrigger type such as:
DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]pub fn parse_create_trigger( &mut self, or_alter: bool, or_replace: bool, is_constraint: bool, ) -> Result<Statement, ParserError>
pub fn parse_trigger_period(&mut self) -> Result<TriggerPeriod, ParserError>
pub fn parse_trigger_event(&mut self) -> Result<TriggerEvent, ParserError>
pub fn parse_trigger_referencing( &mut self, ) -> Result<Option<TriggerReferencing>, ParserError>
pub fn parse_trigger_exec_body( &mut self, ) -> Result<TriggerExecBody, ParserError>
pub fn parse_create_macro( &mut self, or_replace: bool, temporary: bool, ) -> Result<Statement, ParserError>
pub fn parse_create_external_table( &mut self, or_replace: bool, ) -> Result<Statement, ParserError>
pub fn parse_file_format(&mut self) -> Result<FileFormat, ParserError>
pub fn parse_analyze_format(&mut self) -> Result<AnalyzeFormat, ParserError>
pub fn parse_create_view( &mut self, or_alter: bool, or_replace: bool, temporary: bool, create_view_params: Option<CreateViewParams>, ) -> Result<Statement, ParserError>
pub fn parse_create_role(&mut self) -> Result<Statement, ParserError>
pub fn parse_owner(&mut self) -> Result<Owner, ParserError>
pub fn parse_create_policy(&mut self) -> Result<Statement, ParserError>
pub fn parse_create_policy(&mut self) -> Result<Statement, ParserError>
CREATE POLICY name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ]
[ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
[ TO { role_name | PUBLIC | CURRENT_USER | CURRENT_ROLE | SESSION_USER } [, ...] ]
[ USING ( using_expression ) ]
[ WITH CHECK ( with_check_expression ) ]pub fn parse_create_connector(&mut self) -> Result<Statement, ParserError>
pub fn parse_create_connector(&mut self) -> Result<Statement, ParserError>
CREATE CONNECTOR [IF NOT EXISTS] connector_name
[TYPE datasource_type]
[URL datasource_url]
[COMMENT connector_comment]
[WITH DCPROPERTIES(property_name=property_value, ...)]pub fn parse_drop(&mut self) -> Result<Statement, ParserError>
pub fn parse_declare(&mut self) -> Result<Statement, ParserError>
pub fn parse_declare(&mut self) -> Result<Statement, ParserError>
Parse a DECLARE statement.
DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
CURSOR [ { WITH | WITHOUT } HOLD ] FOR queryThe syntax can vary significantly between warehouses. See the grammar on the warehouse specific function in such cases.
pub fn parse_big_query_declare(&mut self) -> Result<Statement, ParserError>
pub fn parse_big_query_declare(&mut self) -> Result<Statement, ParserError>
Parse a BigQuery DECLARE statement.
Syntax:
DECLARE variable_name[, ...] [{ <variable_type> | <DEFAULT expression> }];pub fn parse_snowflake_declare(&mut self) -> Result<Statement, ParserError>
pub fn parse_snowflake_declare(&mut self) -> Result<Statement, ParserError>
Parse a Snowflake DECLARE statement.
Syntax:
DECLARE
[{ <variable_declaration>
| <cursor_declaration>
| <resultset_declaration>
| <exception_declaration> }; ... ]
<variable_declaration>
<variable_name> [<type>] [ { DEFAULT | := } <expression>]
<cursor_declaration>
<cursor_name> CURSOR FOR <query>
<resultset_declaration>
<resultset_name> RESULTSET [ { DEFAULT | := } ( <query> ) ] ;
<exception_declaration>
<exception_name> EXCEPTION [ ( <exception_number> , '<exception_message>' ) ] ;pub fn parse_mssql_declare(&mut self) -> Result<Statement, ParserError>
pub fn parse_mssql_declare(&mut self) -> Result<Statement, ParserError>
pub fn parse_mssql_declare_stmt(&mut self) -> Result<Declare, ParserError>
pub fn parse_mssql_declare_stmt(&mut self) -> Result<Declare, ParserError>
pub fn parse_snowflake_variable_declaration_expression(
&mut self,
) -> Result<Option<DeclareAssignment>, ParserError>
pub fn parse_snowflake_variable_declaration_expression( &mut self, ) -> Result<Option<DeclareAssignment>, ParserError>
Parses the assigned expression in a variable declaration.
Syntax:
[ { DEFAULT | := } <expression>]https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare#variable-declaration-syntax
pub fn parse_mssql_variable_declaration_expression(
&mut self,
) -> Result<Option<DeclareAssignment>, ParserError>
pub fn parse_mssql_variable_declaration_expression( &mut self, ) -> Result<Option<DeclareAssignment>, ParserError>
Parses the assigned expression in a variable declaration.
Syntax:
[ = <expression>]pub fn parse_fetch_statement(&mut self) -> Result<Statement, ParserError>
pub fn parse_discard(&mut self) -> Result<Statement, ParserError>
pub fn parse_create_index( &mut self, unique: bool, ) -> Result<Statement, ParserError>
pub fn parse_create_extension(&mut self) -> Result<Statement, ParserError>
pub fn parse_drop_extension(&mut self) -> Result<Statement, ParserError>
pub fn parse_drop_extension(&mut self) -> Result<Statement, ParserError>
Parse a PostgreSQL-specific Statement::DropExtension statement.
pub fn parse_hive_distribution( &mut self, ) -> Result<HiveDistributionStyle, ParserError>
pub fn parse_hive_formats(&mut self) -> Result<HiveFormat, ParserError>
pub fn parse_row_format(&mut self) -> Result<HiveRowFormat, ParserError>
pub fn parse_create_table( &mut self, or_replace: bool, temporary: bool, global: Option<bool>, transient: bool, ) -> Result<Statement, ParserError>
pub fn parse_plain_options(&mut self) -> Result<Vec<SqlOption>, ParserError>
pub fn parse_optional_inline_comment( &mut self, ) -> Result<Option<CommentDef>, ParserError>
pub fn parse_comment_value(&mut self) -> Result<String, ParserError>
pub fn parse_optional_procedure_parameters( &mut self, ) -> Result<Option<Vec<ProcedureParam>>, ParserError>
pub fn parse_columns( &mut self, ) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError>
pub fn parse_procedure_param(&mut self) -> Result<ProcedureParam, ParserError>
pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError>
pub fn parse_optional_column_option( &mut self, ) -> Result<Option<ColumnOption>, ParserError>
pub fn parse_optional_clustered_by( &mut self, ) -> Result<Option<ClusteredBy>, ParserError>
pub fn parse_referential_action( &mut self, ) -> Result<ReferentialAction, ParserError>
pub fn parse_constraint_characteristics( &mut self, ) -> Result<Option<ConstraintCharacteristics>, ParserError>
pub fn parse_optional_table_constraint( &mut self, ) -> Result<Option<TableConstraint>, ParserError>
pub fn maybe_parse_options( &mut self, keyword: Keyword, ) -> Result<Option<Vec<SqlOption>>, ParserError>
pub fn parse_options( &mut self, keyword: Keyword, ) -> Result<Vec<SqlOption>, ParserError>
pub fn parse_options_with_keywords( &mut self, keywords: &[Keyword], ) -> Result<Vec<SqlOption>, ParserError>
pub fn parse_index_type(&mut self) -> Result<IndexType, ParserError>
pub fn parse_optional_using_then_index_type(
&mut self,
) -> Result<Option<IndexType>, ParserError>
pub fn parse_optional_using_then_index_type( &mut self, ) -> Result<Option<IndexType>, ParserError>
Optionally parse the USING keyword, followed by an IndexType
Example:
pub fn parse_optional_ident(&mut self) -> Result<Option<Ident>, ParserError>
pub fn parse_optional_ident(&mut self) -> Result<Option<Ident>, ParserError>
Parse [ident], mostly ident is name, like:
window_name, index_name, …
pub fn parse_index_type_display(&mut self) -> KeyOrIndexDisplay
pub fn parse_optional_index_option( &mut self, ) -> Result<Option<IndexOption>, ParserError>
pub fn parse_index_options(&mut self) -> Result<Vec<IndexOption>, ParserError>
pub fn parse_sql_option(&mut self) -> Result<SqlOption, ParserError>
pub fn parse_option_clustered(&mut self) -> Result<SqlOption, ParserError>
pub fn parse_option_partition(&mut self) -> Result<SqlOption, ParserError>
pub fn parse_partition(&mut self) -> Result<Partition, ParserError>
pub fn parse_projection_select( &mut self, ) -> Result<ProjectionSelect, ParserError>
pub fn parse_alter_table_add_projection( &mut self, ) -> Result<AlterTableOperation, ParserError>
pub fn parse_alter_table_operation( &mut self, ) -> Result<AlterTableOperation, ParserError>
pub fn parse_alter(&mut self) -> Result<Statement, ParserError>
pub fn parse_alter_table(
&mut self,
iceberg: bool,
) -> Result<Statement, ParserError>
pub fn parse_alter_table( &mut self, iceberg: bool, ) -> Result<Statement, ParserError>
Parse a Statement::AlterTable
pub fn parse_alter_view(&mut self) -> Result<Statement, ParserError>
pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError>
pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError>
Parse a Statement::AlterType
pub fn parse_alter_schema(&mut self) -> Result<Statement, ParserError>
pub fn parse_call(&mut self) -> Result<Statement, ParserError>
pub fn parse_call(&mut self) -> Result<Statement, ParserError>
Parse a CALL procedure_name(arg1, arg2, ...)
or CALL procedure_name statement
pub fn parse_copy(&mut self) -> Result<Statement, ParserError>
pub fn parse_copy(&mut self) -> Result<Statement, ParserError>
Parse a copy statement
pub fn parse_close(&mut self) -> Result<Statement, ParserError>
pub fn parse_tab_value(&mut self) -> Vec<Option<String>>
pub fn parse_value(&mut self) -> Result<ValueWithSpan, ParserError>
pub fn parse_value(&mut self) -> Result<ValueWithSpan, ParserError>
Parse a literal value (numbers, strings, date/time, booleans)
pub fn parse_number_value(&mut self) -> Result<ValueWithSpan, ParserError>
pub fn parse_number_value(&mut self) -> Result<ValueWithSpan, ParserError>
Parse an unsigned numeric literal
pub fn parse_number(&mut self) -> Result<Expr, ParserError>
pub fn parse_number(&mut self) -> Result<Expr, ParserError>
Parse a numeric literal as an expression. Returns a Expr::UnaryOp if the number is signed,
otherwise returns a Expr::Value
pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError>
pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError>
Parse an unsigned literal integer/long
pub fn parse_literal_string(&mut self) -> Result<String, ParserError>
pub fn parse_literal_string(&mut self) -> Result<String, ParserError>
Parse a literal string
pub fn parse_unicode_is_normalized(
&mut self,
expr: Expr,
) -> Result<Expr, ParserError>
pub fn parse_unicode_is_normalized( &mut self, expr: Expr, ) -> Result<Expr, ParserError>
Parse a literal unicode normalization clause
pub fn parse_enum_values(&mut self) -> Result<Vec<EnumMember>, ParserError>
pub fn parse_data_type(&mut self) -> Result<DataType, ParserError>
pub fn parse_data_type(&mut self) -> Result<DataType, ParserError>
Parse a SQL datatype (in the context of a CREATE TABLE statement for example)
pub fn parse_string_values(&mut self) -> Result<Vec<String>, ParserError>
pub fn parse_identifier_with_alias(
&mut self,
) -> Result<IdentWithAlias, ParserError>
pub fn parse_identifier_with_alias( &mut self, ) -> Result<IdentWithAlias, ParserError>
Strictly parse identifier AS identifier
pub fn maybe_parse_table_alias(
&mut self,
) -> Result<Option<TableAlias>, ParserError>
pub fn maybe_parse_table_alias( &mut self, ) -> Result<Option<TableAlias>, ParserError>
Optionally parses an alias for a table like in ... FROM generate_series(1, 10) AS t (col).
In this case, the alias is allowed to optionally name the columns in the table, in
addition to the table itself.
pub fn parse_optional_alias(
&mut self,
reserved_kwds: &[Keyword],
) -> Result<Option<Ident>, ParserError>
pub fn parse_optional_alias( &mut self, reserved_kwds: &[Keyword], ) -> Result<Option<Ident>, ParserError>
Wrapper for parse_optional_alias_inner, left for backwards-compatibility
but new flows should use the context-specific methods such as maybe_parse_select_item_alias
and maybe_parse_table_alias.
pub fn parse_optional_group_by( &mut self, ) -> Result<Option<GroupByExpr>, ParserError>
pub fn parse_optional_order_by( &mut self, ) -> Result<Option<OrderBy>, ParserError>
pub fn parse_table_object(&mut self) -> Result<TableObject, ParserError>
pub fn parse_table_object(&mut self) -> Result<TableObject, ParserError>
Parse a table object for insertion
e.g. some_database.some_table or FUNCTION some_table_func(...)
pub fn parse_object_name(
&mut self,
in_table_clause: bool,
) -> Result<ObjectName, ParserError>
pub fn parse_object_name( &mut self, in_table_clause: bool, ) -> Result<ObjectName, ParserError>
Parse a possibly qualified, possibly quoted identifier, e.g.
foo or `myschema.“table”
The in_table_clause parameter indicates whether the object name is a table in a FROM, JOIN,
or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
in this context on BigQuery.
pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError>
pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError>
Parse identifiers
pub fn parse_multipart_identifier(&mut self) -> Result<Vec<Ident>, ParserError>
pub fn parse_multipart_identifier(&mut self) -> Result<Vec<Ident>, ParserError>
Parse identifiers of form ident1[.identN]*
Similar in functionality to parse_identifiers, with difference being this function is much more strict about parsing a valid multipart identifier, not allowing extraneous tokens to be parsed, otherwise it fails.
For example:
use sqlparser::ast::Ident;
use sqlparser::dialect::GenericDialect;
use sqlparser::parser::Parser;
let dialect = GenericDialect {};
let expected = vec![Ident::new("one"), Ident::new("two")];
// expected usage
let sql = "one.two";
let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
let actual = parser.parse_multipart_identifier().unwrap();
assert_eq!(&actual, &expected);
// parse_identifiers is more loose on what it allows, parsing successfully
let sql = "one + two";
let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
let actual = parser.parse_identifiers().unwrap();
assert_eq!(&actual, &expected);
// expected to strictly fail due to + separator
let sql = "one + two";
let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
let actual = parser.parse_multipart_identifier().unwrap_err();
assert_eq!(
actual.to_string(),
"sql parser error: Unexpected token in identifier: +"
);pub fn parse_identifier(&mut self) -> Result<Ident, ParserError>
pub fn parse_identifier(&mut self) -> Result<Ident, ParserError>
Parse a simple one-word identifier (possibly quoted, possibly a keyword)
pub fn parse_parenthesized_column_list(
&mut self,
optional: IsOptional,
allow_empty: bool,
) -> Result<Vec<Ident>, ParserError>
pub fn parse_parenthesized_column_list( &mut self, optional: IsOptional, allow_empty: bool, ) -> Result<Vec<Ident>, ParserError>
Parses a parenthesized comma-separated list of unqualified, possibly quoted identifiers.
For example: (col1, "col 2", ...)
pub fn parse_parenthesized_compound_identifier_list( &mut self, optional: IsOptional, allow_empty: bool, ) -> Result<Vec<Expr>, ParserError>
pub fn parse_parenthesized_qualified_column_list(
&mut self,
optional: IsOptional,
allow_empty: bool,
) -> Result<Vec<ObjectName>, ParserError>
pub fn parse_parenthesized_qualified_column_list( &mut self, optional: IsOptional, allow_empty: bool, ) -> Result<Vec<ObjectName>, ParserError>
Parses a parenthesized comma-separated list of qualified, possibly quoted identifiers.
For example: (db1.sc1.tbl1.col1, db1.sc1.tbl1."col 2", ...)
pub fn parse_precision(&mut self) -> Result<u64, ParserError>
pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError>
pub fn parse_datetime_64(
&mut self,
) -> Result<(u64, Option<String>), ParserError>
pub fn parse_datetime_64( &mut self, ) -> Result<(u64, Option<String>), ParserError>
Parse datetime64 1 Syntax
DateTime64(precision[, timezone])pub fn parse_optional_character_length( &mut self, ) -> Result<Option<CharacterLength>, ParserError>
pub fn parse_optional_binary_length( &mut self, ) -> Result<Option<BinaryLength>, ParserError>
pub fn parse_character_length(&mut self) -> Result<CharacterLength, ParserError>
pub fn parse_binary_length(&mut self) -> Result<BinaryLength, ParserError>
pub fn parse_optional_precision_scale( &mut self, ) -> Result<(Option<u64>, Option<u64>), ParserError>
pub fn parse_exact_number_optional_precision_scale( &mut self, ) -> Result<ExactNumberInfo, ParserError>
pub fn parse_optional_type_modifiers( &mut self, ) -> Result<Option<Vec<String>>, ParserError>
pub fn parse_delete(&mut self) -> Result<Statement, ParserError>
pub fn parse_kill(&mut self) -> Result<Statement, ParserError>
pub fn parse_explain( &mut self, describe_alias: DescribeAlias, ) -> Result<Statement, ParserError>
pub fn parse_query(&mut self) -> Result<Box<Query>, ParserError>
pub fn parse_query(&mut self) -> Result<Box<Query>, ParserError>
Parse a query expression, i.e. a SELECT statement optionally
preceded with some WITH CTE declarations and optionally followed
by ORDER BY. Unlike some other parse_… methods, this one doesn’t
expect the initial keyword to be already consumed
pub fn parse_for_clause(&mut self) -> Result<Option<ForClause>, ParserError>
pub fn parse_for_clause(&mut self) -> Result<Option<ForClause>, ParserError>
Parse a mssql FOR [XML | JSON | BROWSE] clause
pub fn parse_for_xml(&mut self) -> Result<ForClause, ParserError>
pub fn parse_for_xml(&mut self) -> Result<ForClause, ParserError>
Parse a mssql FOR XML clause
pub fn parse_for_json(&mut self) -> Result<ForClause, ParserError>
pub fn parse_for_json(&mut self) -> Result<ForClause, ParserError>
Parse a mssql FOR JSON clause
pub fn parse_cte(&mut self) -> Result<Cte, ParserError>
pub fn parse_cte(&mut self) -> Result<Cte, ParserError>
Parse a CTE (alias [( col1, col2, ... )] AS (subquery))
pub fn parse_query_body(
&mut self,
precedence: u8,
) -> Result<Box<SetExpr>, ParserError>
pub fn parse_query_body( &mut self, precedence: u8, ) -> Result<Box<SetExpr>, ParserError>
Parse a “query body”, which is an expression with roughly the following grammar:
query_body ::= restricted_select | '(' subquery ')' | set_operation
restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ]
subquery ::= query_body [ order_by_limit ]
set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_bodypub fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator>
pub fn parse_set_quantifier( &mut self, op: &Option<SetOperator>, ) -> SetQuantifier
pub fn parse_select(&mut self) -> Result<Select, ParserError>
pub fn parse_select(&mut self) -> Result<Select, ParserError>
Parse a restricted SELECT statement (no CTEs / UNION / ORDER BY)
pub fn parse_connect_by(&mut self) -> Result<ConnectBy, ParserError>
pub fn parse_as_table(&mut self) -> Result<Table, ParserError>
pub fn parse_as_table(&mut self) -> Result<Table, ParserError>
Parse CREATE TABLE x AS TABLE y
pub fn parse_set_session_params(&mut self) -> Result<Statement, ParserError>
pub fn parse_show(&mut self) -> Result<Statement, ParserError>
pub fn parse_show_create(&mut self) -> Result<Statement, ParserError>
pub fn parse_show_columns( &mut self, extended: bool, full: bool, ) -> Result<Statement, ParserError>
pub fn parse_show_functions(&mut self) -> Result<Statement, ParserError>
pub fn parse_show_collation(&mut self) -> Result<Statement, ParserError>
pub fn parse_show_statement_filter( &mut self, ) -> Result<Option<ShowStatementFilter>, ParserError>
pub fn parse_use(&mut self) -> Result<Statement, ParserError>
pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError>
pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError>
pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError>
A table name or a parenthesized subquery, followed by optional [AS] alias
pub fn maybe_parse_table_version(
&mut self,
) -> Result<Option<TableVersion>, ParserError>
pub fn maybe_parse_table_version( &mut self, ) -> Result<Option<TableVersion>, ParserError>
Parses a the timestamp version specifier (i.e. query historical data)
pub fn parse_json_table_column_def(
&mut self,
) -> Result<JsonTableColumn, ParserError>
pub fn parse_json_table_column_def( &mut self, ) -> Result<JsonTableColumn, ParserError>
Parses MySQL’s JSON_TABLE column definition.
For example: id INT EXISTS PATH '$' DEFAULT '0' ON EMPTY ERROR ON ERROR
pub fn parse_openjson_table_column_def(
&mut self,
) -> Result<OpenJsonTableColumn, ParserError>
pub fn parse_openjson_table_column_def( &mut self, ) -> Result<OpenJsonTableColumn, ParserError>
Parses MSSQL’s OPENJSON WITH column definition.
colName type [ column_path ] [ AS JSON ]pub fn parse_derived_table_factor( &mut self, lateral: IsLateral, ) -> Result<TableFactor, ParserError>
pub fn parse_expr_with_alias(&mut self) -> Result<ExprWithAlias, ParserError>
pub fn parse_expr_with_alias(&mut self) -> Result<ExprWithAlias, ParserError>
Parses an expression with an optional alias
Examples:
SUM(price) AS total_priceSUM(price)Example
let sql = r#"SUM("a") as "b""#;
let mut parser = Parser::new(&GenericDialect).try_with_sql(sql)?;
let expr_with_alias = parser.parse_expr_with_alias()?;
assert_eq!(Some("b".to_string()), expr_with_alias.alias.map(|x|x.value));pub fn parse_pivot_table_factor( &mut self, table: TableFactor, ) -> Result<TableFactor, ParserError>
pub fn parse_unpivot_table_factor( &mut self, table: TableFactor, ) -> Result<TableFactor, ParserError>
pub fn parse_join_constraint( &mut self, natural: bool, ) -> Result<JoinConstraint, ParserError>
pub fn parse_grant(&mut self) -> Result<Statement, ParserError>
pub fn parse_grant(&mut self) -> Result<Statement, ParserError>
Parse a GRANT statement.
pub fn parse_grant_deny_revoke_privileges_objects( &mut self, ) -> Result<(Privileges, Option<GrantObjects>), ParserError>
pub fn parse_grant_permission(&mut self) -> Result<Action, ParserError>
pub fn parse_grantee_name(&mut self) -> Result<GranteeName, ParserError>
pub fn parse_deny(&mut self) -> Result<Statement, ParserError>
pub fn parse_deny(&mut self) -> Result<Statement, ParserError>
Parse Statement::Deny
pub fn parse_revoke(&mut self) -> Result<Statement, ParserError>
pub fn parse_revoke(&mut self) -> Result<Statement, ParserError>
Parse a REVOKE statement
pub fn parse_replace(&mut self) -> Result<Statement, ParserError>
pub fn parse_replace(&mut self) -> Result<Statement, ParserError>
Parse an REPLACE statement
pub fn parse_insert(&mut self) -> Result<Statement, ParserError>
pub fn parse_insert(&mut self) -> Result<Statement, ParserError>
Parse an INSERT statement
pub fn parse_input_format_clause( &mut self, ) -> Result<InputFormatClause, ParserError>
pub fn parse_insert_partition( &mut self, ) -> Result<Option<Vec<Expr>>, ParserError>
pub fn parse_load_data_table_format( &mut self, ) -> Result<Option<HiveLoadDataFormat>, ParserError>
pub fn parse_update(&mut self) -> Result<Statement, ParserError>
pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError>
pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError>
Parse a var = expr assignment, used in an UPDATE statement
pub fn parse_assignment_target(
&mut self,
) -> Result<AssignmentTarget, ParserError>
pub fn parse_assignment_target( &mut self, ) -> Result<AssignmentTarget, ParserError>
Parse the left-hand side of an assignment, used in an UPDATE statement
pub fn parse_function_args(&mut self) -> Result<FunctionArg, ParserError>
pub fn parse_optional_args(&mut self) -> Result<Vec<FunctionArg>, ParserError>
pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError>
pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError>
Parse a comma-delimited list of projections after SELECT
pub fn parse_wildcard_additional_options(
&mut self,
wildcard_token: TokenWithSpan,
) -> Result<WildcardAdditionalOptions, ParserError>
pub fn parse_wildcard_additional_options( &mut self, wildcard_token: TokenWithSpan, ) -> Result<WildcardAdditionalOptions, ParserError>
Parse an WildcardAdditionalOptions information for wildcard select items.
If it is not possible to parse it, will return an option.
pub fn parse_optional_select_item_ilike(
&mut self,
) -> Result<Option<IlikeSelectItem>, ParserError>
pub fn parse_optional_select_item_ilike( &mut self, ) -> Result<Option<IlikeSelectItem>, ParserError>
Parse an Ilike information for wildcard select items.
If it is not possible to parse it, will return an option.
pub fn parse_optional_select_item_exclude(
&mut self,
) -> Result<Option<ExcludeSelectItem>, ParserError>
pub fn parse_optional_select_item_exclude( &mut self, ) -> Result<Option<ExcludeSelectItem>, ParserError>
Parse an Exclude information for wildcard select items.
If it is not possible to parse it, will return an option.
pub fn parse_optional_select_item_except(
&mut self,
) -> Result<Option<ExceptSelectItem>, ParserError>
pub fn parse_optional_select_item_except( &mut self, ) -> Result<Option<ExceptSelectItem>, ParserError>
Parse an Except information for wildcard select items.
If it is not possible to parse it, will return an option.
pub fn parse_optional_select_item_rename(
&mut self,
) -> Result<Option<RenameSelectItem>, ParserError>
pub fn parse_optional_select_item_rename( &mut self, ) -> Result<Option<RenameSelectItem>, ParserError>
Parse a Rename information for wildcard select items.
pub fn parse_optional_select_item_replace(
&mut self,
) -> Result<Option<ReplaceSelectItem>, ParserError>
pub fn parse_optional_select_item_replace( &mut self, ) -> Result<Option<ReplaceSelectItem>, ParserError>
Parse a Replace information for wildcard select items.
pub fn parse_replace_elements( &mut self, ) -> Result<ReplaceSelectElement, ParserError>
pub fn parse_asc_desc(&mut self) -> Option<bool>
pub fn parse_asc_desc(&mut self) -> Option<bool>
Parse ASC or DESC, returns an Option with true if ASC, false of DESC or None if none of
them.
pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError>
pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError>
Parse an OrderByExpr expression.
pub fn parse_create_index_expr(&mut self) -> Result<IndexColumn, ParserError>
pub fn parse_create_index_expr(&mut self) -> Result<IndexColumn, ParserError>
Parse an IndexColumn.
pub fn parse_with_fill(&mut self) -> Result<WithFill, ParserError>
pub fn parse_interpolations( &mut self, ) -> Result<Option<Interpolate>, ParserError>
pub fn parse_interpolation(&mut self) -> Result<InterpolateExpr, ParserError>
pub fn parse_top(&mut self) -> Result<Top, ParserError>
pub fn parse_top(&mut self) -> Result<Top, ParserError>
Parse a TOP clause, MSSQL equivalent of LIMIT,
that follows after SELECT [DISTINCT].
pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError>
pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError>
Parse a LIMIT clause
pub fn parse_offset(&mut self) -> Result<Offset, ParserError>
pub fn parse_offset(&mut self) -> Result<Offset, ParserError>
Parse an OFFSET clause
pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError>
pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError>
Parse a FETCH clause
pub fn parse_lock(&mut self) -> Result<LockClause, ParserError>
pub fn parse_lock(&mut self) -> Result<LockClause, ParserError>
Parse a FOR UPDATE/FOR SHARE clause
pub fn parse_values(&mut self, allow_empty: bool) -> Result<Values, ParserError>
pub fn parse_start_transaction(&mut self) -> Result<Statement, ParserError>
pub fn parse_begin(&mut self) -> Result<Statement, ParserError>
pub fn parse_begin_exception_end(&mut self) -> Result<Statement, ParserError>
pub fn parse_end(&mut self) -> Result<Statement, ParserError>
pub fn parse_transaction_modes( &mut self, ) -> Result<Vec<TransactionMode>, ParserError>
pub fn parse_commit(&mut self) -> Result<Statement, ParserError>
pub fn parse_rollback(&mut self) -> Result<Statement, ParserError>
pub fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError>
pub fn parse_rollback_savepoint(&mut self) -> Result<Option<Ident>, ParserError>
pub fn parse_raiserror(&mut self) -> Result<Statement, ParserError>
pub fn parse_raiserror(&mut self) -> Result<Statement, ParserError>
Parse a ‘RAISERROR’ statement
pub fn parse_raiserror_option(&mut self) -> Result<RaisErrorOption, ParserError>
pub fn parse_deallocate(&mut self) -> Result<Statement, ParserError>
pub fn parse_execute(&mut self) -> Result<Statement, ParserError>
pub fn parse_prepare(&mut self) -> Result<Statement, ParserError>
pub fn parse_unload(&mut self) -> Result<Statement, ParserError>
pub fn parse_merge_clauses(&mut self) -> Result<Vec<MergeClause>, ParserError>
pub fn parse_merge(&mut self) -> Result<Statement, ParserError>
pub fn parse_pragma(&mut self) -> Result<Statement, ParserError>
pub fn parse_install(&mut self) -> Result<Statement, ParserError>
pub fn parse_install(&mut self) -> Result<Statement, ParserError>
INSTALL [extension_name]
pub fn parse_load(&mut self) -> Result<Statement, ParserError>
pub fn parse_load(&mut self) -> Result<Statement, ParserError>
Parse a SQL LOAD statement
pub fn parse_optimize_table(&mut self) -> Result<Statement, ParserError>
pub fn parse_optimize_table(&mut self) -> Result<Statement, ParserError>
OPTIMIZE TABLE [db.]name [ON CLUSTER cluster] [PARTITION partition | PARTITION ID 'partition_id'] [FINAL] [DEDUPLICATE [BY expression]]pub fn parse_create_sequence(
&mut self,
temporary: bool,
) -> Result<Statement, ParserError>
pub fn parse_create_sequence( &mut self, temporary: bool, ) -> Result<Statement, ParserError>
CREATE [ { TEMPORARY | TEMP } ] SEQUENCE [ IF NOT EXISTS ] <sequence_name>See Postgres docs for more details.
pub fn parse_pg_create_server(&mut self) -> Result<Statement, ParserError>
pub fn parse_pg_create_server(&mut self) -> Result<Statement, ParserError>
Parse a CREATE SERVER statement.
pub fn parse_named_window( &mut self, ) -> Result<NamedWindowDefinition, ParserError>
pub fn parse_create_procedure( &mut self, or_alter: bool, ) -> Result<Statement, ParserError>
pub fn parse_window_spec(&mut self) -> Result<WindowSpec, ParserError>
pub fn parse_create_type(&mut self) -> Result<Statement, ParserError>
pub fn parse_create_type_enum(
&mut self,
name: ObjectName,
) -> Result<Statement, ParserError>
pub fn parse_create_type_enum( &mut self, name: ObjectName, ) -> Result<Statement, ParserError>
Parse remainder of CREATE TYPE AS ENUM statement (see Statement::CreateType and Self::parse_create_type)
See PostgreSQL
pub fn into_tokens(self) -> Vec<TokenWithSpan>
pub fn into_tokens(self) -> Vec<TokenWithSpan>
Consume the parser and return its underlying token buffer
Auto Trait Implementations§
impl<'a> Freeze for Parser<'a>
impl<'a> !RefUnwindSafe for Parser<'a>
impl<'a> !Send for Parser<'a>
impl<'a> !Sync for Parser<'a>
impl<'a> Unpin for Parser<'a>
impl<'a> !UnwindSafe for Parser<'a>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more