Skip to main content

Parser

Struct Parser 

Source
pub struct Parser<'a> { /* private fields */ }
Expand description

A SQL Parser

This struct is the main entry point for parsing SQL queries.

§Functionality:

§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"
  ]

Implementations§

Source§

impl Parser<'_>

Source

pub fn parse_alter_role(&mut self) -> Result<Statement, ParserError>

Parse ALTER ROLE statement

Source

pub fn parse_alter_policy(&mut self) -> Result<AlterPolicy, 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 ) ]

PostgreSQL

Source

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;
Source

pub fn parse_alter_user(&mut self) -> Result<AlterUser, ParserError>

Parse an ALTER USER statement

ALTER USER [ IF EXISTS ] [ <name> ] [ OPTIONS ]
Source§

impl Parser<'_>

Source

pub fn parse_merge( &mut self, merge_token: TokenWithSpan, ) -> Result<Merge, ParserError>

Parse a MERGE statement

Source§

impl<'a> Parser<'a>

Source

pub fn new(dialect: &'a dyn Dialect) -> Self

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()?;
Source

pub fn with_recursion_limit(self, recursion_limit: usize) -> Self

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

Source

pub fn with_options(self, options: ParserOptions) -> Self

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(_)));
Source

pub fn with_tokens_with_locations(self, tokens: Vec<TokenWithSpan>) -> Self

Reset this parser to parse the specified token stream

Source

pub fn with_tokens(self, tokens: Vec<Token>) -> Self

Reset this parser state to parse the specified tokens

Source

pub fn try_with_sql(self, sql: &str) -> Result<Self, 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

Source

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);
Source

pub fn parse_sql( dialect: &dyn Dialect, 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);
Source

pub fn parse_sql_with_comments( dialect: &'a dyn Dialect, sql: &str, ) -> Result<(Vec<Statement>, Comments), ParserError>

Parses the given sql into an Abstract Syntax Tree (AST), returning also encountered source code comments.

See Parser::parse_sql.

Source

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.

Source

pub fn parse_case_stmt(&mut self) -> Result<CaseStatement, ParserError>

Parse a CASE statement.

See Statement::Case

Source

pub fn parse_if_stmt(&mut self) -> Result<IfStatement, ParserError>

Parse an IF statement.

See Statement::If

Source

pub fn parse_raise_stmt(&mut self) -> Result<RaiseStatement, ParserError>

Parse a RAISE statement.

See Statement::Raise

Source

pub fn parse_comment(&mut self) -> Result<Statement, ParserError>

Parse a COMMENT statement.

See Statement::Comment

Source

pub fn parse_flush(&mut self) -> Result<Statement, ParserError>

Parse FLUSH statement.

Source

pub fn parse_msck(&mut self) -> Result<Msck, ParserError>

Parse MSCK statement.

Source

pub fn parse_truncate(&mut self) -> Result<Truncate, ParserError>

Parse TRUNCATE statement.

Source

pub fn parse_attach_duckdb_database_options( &mut self, ) -> Result<Vec<AttachDuckDBDatabaseOption>, ParserError>

Parse options for ATTACH DUCKDB DATABASE statement.

Source

pub fn parse_attach_duckdb_database(&mut self) -> Result<Statement, ParserError>

Parse ATTACH DUCKDB DATABASE statement.

Source

pub fn parse_detach_duckdb_database(&mut self) -> Result<Statement, ParserError>

Parse DETACH DUCKDB DATABASE statement.

Source

pub fn parse_attach_database(&mut self) -> Result<Statement, ParserError>

Parse ATTACH DATABASE statement.

Source

pub fn parse_analyze(&mut self) -> Result<Analyze, ParserError>

Parse ANALYZE statement.

Source

pub fn parse_wildcard_expr(&mut self) -> Result<Expr, ParserError>

Parse a new expression including wildcard & qualified wildcard.

Source

pub fn parse_expr(&mut self) -> Result<Expr, ParserError>

Parse a new expression.

Source

pub fn parse_expr_with_alias_and_order_by( &mut self, ) -> Result<ExprWithAliasAndOrderBy, ParserError>

Parse expression with optional alias and order by.

Source

pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError>

Parse tokens until the precedence changes.

Source

pub fn parse_assert(&mut self) -> Result<Statement, ParserError>

Parse ASSERT statement.

Source

pub fn parse_savepoint(&mut self) -> Result<Statement, ParserError>

Parse SAVEPOINT statement.

Source

pub fn parse_release(&mut self) -> Result<Statement, ParserError>

Parse RELEASE statement.

Source

pub fn parse_listen(&mut self) -> Result<Statement, ParserError>

Parse LISTEN statement.

Source

pub fn parse_unlisten(&mut self) -> Result<Statement, ParserError>

Parse UNLISTEN statement.

Source

pub fn parse_notify(&mut self) -> Result<Statement, ParserError>

Parse NOTIFY statement.

Source

pub fn parse_rename(&mut self) -> Result<Statement, ParserError>

Parses a RENAME TABLE statement. See Statement::RenameTable

Source

pub fn parse_prefix(&mut self) -> Result<Expr, ParserError>

Parse an expression prefix.

Source

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].

Source

pub fn parse_utility_options( &mut self, ) -> Result<Vec<UtilityOption>, ParserError>

Parse utility options in the form of (option1, option2 arg2, option3 arg3, ...)

Source

pub fn parse_function(&mut self, name: ObjectName) -> Result<Expr, ParserError>

Parse a function call expression named by name and return it as an Expr.

Source

pub fn parse_time_functions( &mut self, name: ObjectName, ) -> Result<Expr, ParserError>

Parse time-related function name possibly followed by (...) arguments.

Source

pub fn parse_window_frame_units( &mut self, ) -> Result<WindowFrameUnits, ParserError>

Parse window frame UNITS clause: ROWS, RANGE, or GROUPS.

Source

pub fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError>

Parse a WINDOW frame definition (units and bounds).

Source

pub fn parse_window_frame_bound( &mut self, ) -> Result<WindowFrameBound, ParserError>

Parse a window frame bound: CURRENT ROW or <n> PRECEDING|FOLLOWING.

Source

pub fn parse_case_expr(&mut self) -> Result<Expr, ParserError>

Parse a CASE expression and return an Expr::Case.

Source

pub fn parse_optional_cast_format( &mut self, ) -> Result<Option<CastFormat>, ParserError>

Parse an optional FORMAT clause for CAST expressions.

Source

pub fn parse_optional_time_zone(&mut self) -> Result<Option<Value>, ParserError>

Parse an optional AT TIME ZONE clause.

Source

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
Source

pub fn parse_cast_expr(&mut self, kind: CastKind) -> Result<Expr, ParserError>

Parse a SQL CAST function e.g. CAST(expr AS FLOAT)

Source

pub fn parse_exists_expr(&mut self, negated: bool) -> Result<Expr, ParserError>

Parse a SQL EXISTS expression e.g. WHERE EXISTS(SELECT ...).

Source

pub fn parse_extract_expr(&mut self) -> Result<Expr, ParserError>

Parse a SQL EXTRACT expression e.g. EXTRACT(YEAR FROM date).

Source

pub fn parse_ceil_floor_expr( &mut self, is_ceil: bool, ) -> Result<Expr, ParserError>

Parse a CEIL or FLOOR expression.

Source

pub fn parse_position_expr(&mut self, ident: Ident) -> Result<Expr, ParserError>

Parse a POSITION expression.

Source

pub fn parse_substring(&mut self) -> Result<Expr, ParserError>

Parse SUBSTRING/SUBSTR expressions: SUBSTRING(expr FROM start FOR length) or SUBSTR(expr, start, length).

Source

pub fn parse_overlay_expr(&mut self) -> Result<Expr, ParserError>

Parse an OVERLAY expression.

See Expr::Overlay

Source

pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError>

TRIM ([WHERE] ['text' FROM] 'text')
TRIM ('text')
TRIM(<expr>, [, characters]) -- only Snowflake or BigQuery
Source

pub fn parse_trim_where(&mut self) -> Result<TrimWhereField, ParserError>

Parse the WHERE field for a TRIM expression.

See TrimWhereField

Source

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]

Source

pub fn parse_listagg_on_overflow( &mut self, ) -> Result<Option<ListAggOnOverflow>, ParserError>

Parse the ON OVERFLOW clause for LISTAGG.

See ListAggOnOverflow

Source

pub fn parse_date_time_field(&mut self) -> Result<DateTimeField, ParserError>

Parse a date/time field for EXTRACT, interval qualifiers, and ceil/floor operations.

EXTRACT supports a wider set of date/time fields than interval qualifiers, so this function may need to be split in two.

See DateTimeField

Source

pub fn parse_not(&mut self) -> Result<Expr, ParserError>

Parse a NOT expression.

Represented in the AST as Expr::UnaryOp with UnaryOperator::Not.

Source

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.

Source

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 DAY

Note that we do not currently attempt to parse the quoted value.

Source

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.

Source

pub fn parse_infix( &mut self, expr: Expr, precedence: u8, ) -> Result<Expr, ParserError>

Parse an operator following an expression

Source

pub fn parse_escape_char(&mut self) -> Result<Option<Value>, ParserError>

Parse the ESCAPE CHAR portion of LIKE, ILIKE, and SIMILAR TO

Source

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]

Source

pub fn parse_in( &mut self, expr: Expr, negated: bool, ) -> Result<Expr, ParserError>

Parses the parens following the [ NOT ] IN operator.

Source

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.

Source

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.

Source

pub fn get_next_precedence(&self) -> Result<u8, ParserError>

Get the precedence of the next token

Source

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.

Source

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.

Source

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

Source

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, .. }),
    ]
));
Source

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.

Source

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.

Source

pub fn peek_nth_token(&self, n: usize) -> TokenWithSpan

Return nth non-whitespace token that has not yet been processed

Source

pub fn peek_nth_token_ref(&self, n: usize) -> &TokenWithSpan

Return nth non-whitespace token that has not yet been processed

Source

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).

Source

pub fn peek_nth_token_no_skip(&self, n: usize) -> TokenWithSpan

Return nth token, possibly whitespace, that has not yet been processed.

Source

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.

Source

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

Source

pub fn next_token_no_skip(&mut self) -> Option<&TokenWithSpan>

Return the next unprocessed token, possibly whitespace.

Source

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

Source

pub fn get_current_token(&self) -> &TokenWithSpan

Returns a reference to the current token

Does not advance the current token.

Source

pub fn get_previous_token(&self) -> &TokenWithSpan

Returns a reference to the previous token

Does not advance the current token.

Source

pub fn get_next_token(&self) -> &TokenWithSpan

Returns a reference to the next token

Does not advance the current token.

Source

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.

Source

pub fn expected<T>( &self, expected: &str, found: TokenWithSpan, ) -> Result<T, ParserError>

Report found was encountered instead of expected

Source

pub fn expected_ref<T>( &self, expected: &str, found: &TokenWithSpan, ) -> Result<T, ParserError>

report found was encountered instead of expected

Source

pub fn expected_at<T>( &self, expected: &str, index: usize, ) -> Result<T, ParserError>

Report that the token at index was found instead of expected.

Source

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.

Source

pub fn peek_keyword(&self, expected: Keyword) -> bool

Check if the current token is the expected keyword without consuming it.

Returns true if the current token matches the expected keyword.

Source

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.

Source

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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

Source

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

Source

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

Source

pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError>

Parse a comma-separated list of 1+ SelectItem

Source

pub fn parse_actions_list(&mut self) -> Result<Vec<Action>, ParserError>

Parse a list of actions for GRANT statements.

Source

pub fn parse_comma_separated<T, F>( &mut self, f: F, ) -> Result<Vec<T>, ParserError>
where F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,

Parse a comma-separated list of 1+ items accepted by F

Source

pub fn parse_keyword_separated<T, F>( &mut self, keyword: Keyword, f: F, ) -> Result<Vec<T>, ParserError>
where F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,

Parse a keyword-separated list of 1+ items accepted by F

Source

pub fn parse_parenthesized<T, F>(&mut self, f: F) -> Result<T, ParserError>
where F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,

Parse an expression enclosed in parentheses.

Source

pub fn parse_comma_separated0<T, F>( &mut self, f: F, end_token: Token, ) -> Result<Vec<T>, ParserError>
where F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,

Parse a comma-separated list of 0+ items accepted by F

Source

pub fn maybe_parse<T, F>(&mut self, f: F) -> Result<Option<T>, ParserError>
where F: FnMut(&mut Parser<'_>) -> Result<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.

Source

pub fn try_parse<T, F>(&mut self, f: F) -> Result<T, ParserError>
where F: FnMut(&mut Parser<'_>) -> Result<T, ParserError>,

Run a parser method f, reverting back to the current position if unsuccessful.

Source

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.

Source

pub fn parse_create(&mut self) -> Result<Statement, ParserError>

Parse a SQL CREATE statement

Source

pub fn parse_create_secret( &mut self, or_replace: bool, temporary: bool, persistent: bool, ) -> Result<Statement, ParserError>

See DuckDB Docs for more details.

Source

pub fn parse_cache_table(&mut self) -> Result<Statement, ParserError>

Parse a CACHE TABLE statement

Source

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

Source

pub fn parse_uncache_table(&mut self) -> Result<Statement, ParserError>

Parse a UNCACHE TABLE statement

Source

pub fn parse_create_virtual_table(&mut self) -> Result<Statement, ParserError>

SQLite-specific CREATE VIRTUAL TABLE

Source

pub fn parse_create_schema(&mut self) -> Result<Statement, ParserError>

Parse a CREATE SCHEMA statement.

Source

pub fn parse_create_database(&mut self) -> Result<Statement, ParserError>

Parse a CREATE DATABASE statement.

Source

pub fn parse_optional_create_function_using( &mut self, ) -> Result<Option<CreateFunctionUsing>, ParserError>

Parse an optional USING clause for CREATE FUNCTION.

Source

pub fn parse_create_function( &mut self, or_alter: bool, or_replace: bool, temporary: bool, ) -> Result<Statement, ParserError>

Parse a CREATE FUNCTION statement.

Source

pub fn parse_drop_trigger(&mut self) -> Result<DropTrigger, ParserError>

Parse statements of the DropTrigger type such as:

DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
Source

pub fn parse_create_trigger( &mut self, temporary: bool, or_alter: bool, or_replace: bool, is_constraint: bool, ) -> Result<CreateTrigger, ParserError>

Parse a CREATE TRIGGER statement.

Source

pub fn parse_trigger_period(&mut self) -> Result<TriggerPeriod, ParserError>

Parse the period part of a trigger (BEFORE, AFTER, etc.).

Source

pub fn parse_trigger_event(&mut self) -> Result<TriggerEvent, ParserError>

Parse the event part of a trigger (INSERT, UPDATE, etc.).

Source

pub fn parse_trigger_referencing( &mut self, ) -> Result<Option<TriggerReferencing>, ParserError>

Parse the REFERENCING clause of a trigger.

Source

pub fn parse_trigger_exec_body( &mut self, ) -> Result<TriggerExecBody, ParserError>

Parse the execution body of a trigger (FUNCTION or PROCEDURE).

Source

pub fn parse_create_macro( &mut self, or_replace: bool, temporary: bool, ) -> Result<Statement, ParserError>

Parse a CREATE MACRO statement.

Source

pub fn parse_create_external_table( &mut self, or_replace: bool, ) -> Result<CreateTable, ParserError>

Parse a CREATE EXTERNAL TABLE statement.

Source

pub fn parse_file_format(&mut self) -> Result<FileFormat, ParserError>

Parse a file format for external tables.

Source

pub fn parse_analyze_format(&mut self) -> Result<AnalyzeFormat, ParserError>

Parse an ANALYZE FORMAT.

Source

pub fn parse_create_view( &mut self, or_alter: bool, or_replace: bool, temporary: bool, create_view_params: Option<CreateViewParams>, ) -> Result<CreateView, ParserError>

Parse a CREATE VIEW statement.

Source

pub fn parse_create_role(&mut self) -> Result<CreateRole, ParserError>

Parse a CREATE ROLE statement.

Source

pub fn parse_owner(&mut self) -> Result<Owner, ParserError>

Parse an OWNER clause.

Source

pub fn parse_create_policy(&mut self) -> Result<CreatePolicy, 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 ) ]

PostgreSQL Documentation

Source

pub fn parse_create_connector(&mut self) -> Result<CreateConnector, ParserError>

CREATE CONNECTOR [IF NOT EXISTS] connector_name
[TYPE datasource_type]
[URL datasource_url]
[COMMENT connector_comment]
[WITH DCPROPERTIES(property_name=property_value, ...)]

Hive Documentation

Source

pub fn parse_create_operator(&mut self) -> Result<CreateOperator, ParserError>

Source

pub fn parse_create_operator_family( &mut self, ) -> Result<CreateOperatorFamily, ParserError>

Source

pub fn parse_create_operator_class( &mut self, ) -> Result<CreateOperatorClass, ParserError>

Source

pub fn parse_drop(&mut self) -> Result<Statement, ParserError>

Parse a DROP statement.

Source

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 query

The syntax can vary significantly between warehouses. See the grammar on the warehouse specific function in such cases.

Source

pub fn parse_big_query_declare(&mut self) -> Result<Statement, ParserError>

Parse a BigQuery DECLARE statement.

Syntax:

DECLARE variable_name[, ...] [{ <variable_type> | <DEFAULT expression> }];
Source

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>' ) ] ;
Source

pub fn parse_mssql_declare(&mut self) -> Result<Statement, ParserError>

Parse a MsSql DECLARE statement.

Syntax:

DECLARE
Source

pub fn parse_mssql_declare_stmt(&mut self) -> Result<Declare, ParserError>

Parse the body of a MsSql DECLAREstatement.

Syntax:

Source

pub fn parse_snowflake_variable_declaration_expression( &mut self, ) -> Result<Option<DeclareAssignment>, ParserError>

Source

pub fn parse_mssql_variable_declaration_expression( &mut self, ) -> Result<Option<DeclareAssignment>, ParserError>

Parses the assigned expression in a variable declaration.

Syntax:

[ = <expression>]
Source

pub fn parse_fetch_statement(&mut self) -> Result<Statement, ParserError>

Parse FETCH [direction] { FROM | IN } cursor INTO target; statement.

Source

pub fn parse_discard(&mut self) -> Result<Statement, ParserError>

Parse a DISCARD statement.

Source

pub fn parse_create_index( &mut self, unique: bool, ) -> Result<CreateIndex, ParserError>

Parse a CREATE INDEX statement.

Source

pub fn parse_create_extension(&mut self) -> Result<CreateExtension, ParserError>

Parse a CREATE EXTENSION statement.

Source

pub fn parse_drop_extension(&mut self) -> Result<Statement, ParserError>

Parse a PostgreSQL-specific Statement::DropExtension statement.

Source

pub fn parse_drop_operator(&mut self) -> Result<Statement, ParserError>

Parse aStatement::DropOperator statement.

Source

pub fn parse_drop_operator_family(&mut self) -> Result<Statement, ParserError>

Source

pub fn parse_drop_operator_class(&mut self) -> Result<Statement, ParserError>

Source

pub fn parse_hive_distribution( &mut self, ) -> Result<HiveDistributionStyle, ParserError>

Parse Hive distribution style.

TODO: Support parsing for SKEWED distribution style.

Source

pub fn parse_hive_formats(&mut self) -> Result<Option<HiveFormat>, ParserError>

Parse Hive formats.

Source

pub fn parse_row_format(&mut self) -> Result<HiveRowFormat, ParserError>

Parse Hive row format.

Source

pub fn parse_create_table( &mut self, or_replace: bool, temporary: bool, global: Option<bool>, transient: bool, ) -> Result<CreateTable, ParserError>

Parse CREATE TABLE statement.

Source

pub fn parse_plain_options(&mut self) -> Result<Vec<SqlOption>, ParserError>

Parse plain options.

Source

pub fn parse_optional_inline_comment( &mut self, ) -> Result<Option<CommentDef>, ParserError>

Parse optional inline comment.

Source

pub fn parse_comment_value(&mut self) -> Result<String, ParserError>

Parse comment value.

Source

pub fn parse_optional_procedure_parameters( &mut self, ) -> Result<Option<Vec<ProcedureParam>>, ParserError>

Parse optional procedure parameters.

Source

pub fn parse_columns( &mut self, ) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError>

Parse columns and constraints.

Source

pub fn parse_procedure_param(&mut self) -> Result<ProcedureParam, ParserError>

Parse procedure parameter.

Source

pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError>

Parse column definition.

Source

pub fn parse_optional_column_option( &mut self, ) -> Result<Option<ColumnOption>, ParserError>

Parse optional column option.

Source

pub fn parse_optional_clustered_by( &mut self, ) -> Result<Option<ClusteredBy>, ParserError>

Parse optional CLUSTERED BY clause for Hive/Generic dialects.

Source

pub fn parse_referential_action( &mut self, ) -> Result<ReferentialAction, ParserError>

Parse a referential action used in foreign key clauses.

Recognized forms: RESTRICT, CASCADE, SET NULL, NO ACTION, SET DEFAULT.

Source

pub fn parse_match_kind( &mut self, ) -> Result<ConstraintReferenceMatchKind, ParserError>

Parse a MATCH kind for constraint references: FULL, PARTIAL, or SIMPLE.

Source

pub fn parse_constraint_characteristics( &mut self, ) -> Result<Option<ConstraintCharacteristics>, ParserError>

Parse optional constraint characteristics such as DEFERRABLE, INITIALLY and ENFORCED.

Source

pub fn parse_optional_table_constraint( &mut self, ) -> Result<Option<TableConstraint>, ParserError>

Parse an optional table constraint (e.g. PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK).

Source

pub fn maybe_parse_options( &mut self, keyword: Keyword, ) -> Result<Option<Vec<SqlOption>>, ParserError>

Optionally parse a parenthesized list of SqlOptions introduced by keyword.

Source

pub fn parse_options( &mut self, keyword: Keyword, ) -> Result<Vec<SqlOption>, ParserError>

Parse a parenthesized list of SqlOptions following keyword, or return an empty vec.

Source

pub fn parse_options_with_keywords( &mut self, keywords: &[Keyword], ) -> Result<Vec<SqlOption>, ParserError>

Parse options introduced by one of keywords followed by a parenthesized list.

Source

pub fn parse_index_type(&mut self) -> Result<IndexType, ParserError>

Parse an index type token (e.g. BTREE, HASH, or a custom identifier).

Source

pub fn parse_optional_using_then_index_type( &mut self, ) -> Result<Option<IndexType>, ParserError>

Optionally parse the USING keyword, followed by an IndexType Example:

Optionally parse USING <index_type> and return the parsed IndexType if present.

Source

pub fn parse_optional_ident(&mut self) -> Result<Option<Ident>, ParserError>

Parse [ident], mostly ident is name, like: window_name, index_name, … Parse an optional identifier, returning Some(Ident) if present.

Source

pub fn parse_index_type_display(&mut self) -> KeyOrIndexDisplay

Parse optional KEY or INDEX display tokens used in index/constraint declarations.

Source

pub fn parse_optional_index_option( &mut self, ) -> Result<Option<IndexOption>, ParserError>

Parse an optional index option such as USING <type> or COMMENT <string>.

Source

pub fn parse_index_options(&mut self) -> Result<Vec<IndexOption>, ParserError>

Parse zero or more index options and return them as a vector.

Source

pub fn parse_sql_option(&mut self) -> Result<SqlOption, ParserError>

Parse a single SqlOption used by various dialect-specific DDL statements.

Source

pub fn parse_option_clustered(&mut self) -> Result<SqlOption, ParserError>

Parse a CLUSTERED table option (MSSQL-specific syntaxes supported).

Source

pub fn parse_option_partition(&mut self) -> Result<SqlOption, ParserError>

Parse a PARTITION(...) FOR VALUES(...) table option.

Source

pub fn parse_partition(&mut self) -> Result<Partition, ParserError>

Parse a parenthesized list of partition expressions and return a Partition value.

Source

pub fn parse_projection_select( &mut self, ) -> Result<ProjectionSelect, ParserError>

Parse a parenthesized SELECT projection used for projection-based operations.

Source

pub fn parse_alter_table_add_projection( &mut self, ) -> Result<AlterTableOperation, ParserError>

Parse ALTER TABLE ... ADD PROJECTION ... operation.

Source

pub fn parse_alter_table_operation( &mut self, ) -> Result<AlterTableOperation, ParserError>

Parse a single ALTER TABLE operation and return an AlterTableOperation.

Source

pub fn parse_alter(&mut self) -> Result<Statement, ParserError>

Parse an ALTER <object> statement and dispatch to the appropriate alter handler.

Source

pub fn parse_alter_table( &mut self, iceberg: bool, ) -> Result<Statement, ParserError>

Source

pub fn parse_alter_view(&mut self) -> Result<Statement, ParserError>

Parse an ALTER VIEW statement.

Source

pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError>

Source

pub fn parse_alter_operator(&mut self) -> Result<AlterOperator, ParserError>

Source

pub fn parse_alter_operator_family( &mut self, ) -> Result<AlterOperatorFamily, ParserError>

Source

pub fn parse_alter_operator_class( &mut self, ) -> Result<AlterOperatorClass, ParserError>

Parse an ALTER OPERATOR CLASS statement.

Handles operations like RENAME TO, OWNER TO, and SET SCHEMA.

Source

pub fn parse_alter_schema(&mut self) -> Result<Statement, ParserError>

Parse an ALTER SCHEMA statement.

Supports operations such as setting options, renaming, adding/dropping replicas, and changing owner.

Source

pub fn parse_call(&mut self) -> Result<Statement, ParserError>

Parse a CALL procedure_name(arg1, arg2, ...) or CALL procedure_name statement

Source

pub fn parse_copy(&mut self) -> Result<Statement, ParserError>

Parse a copy statement

Source

pub fn parse_close(&mut self) -> Result<Statement, ParserError>

Parse a CLOSE cursor statement.

Source

pub fn parse_tsv(&mut self) -> Vec<Option<String>>

Parse a tab separated values in COPY payload

Source

pub fn parse_tab_value(&mut self) -> Vec<Option<String>>

Parse a single tab-separated value row used by COPY payload parsing.

Source

pub fn parse_value(&mut self) -> Result<ValueWithSpan, ParserError>

Parse a literal value (numbers, strings, date/time, booleans)

Source

pub fn parse_number_value(&mut self) -> Result<ValueWithSpan, ParserError>

Parse an unsigned numeric literal

Source

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

Source

pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError>

Parse an unsigned literal integer/long

Source

pub fn parse_literal_string(&mut self) -> Result<String, ParserError>

Parse a literal string

Source

pub fn parse_unicode_is_normalized( &mut self, expr: Expr, ) -> Result<Expr, ParserError>

Parse a literal unicode normalization clause

Source

pub fn parse_enum_values(&mut self) -> Result<Vec<EnumMember>, ParserError>

Parse parenthesized enum members, used with ENUM(...) type definitions.

Source

pub fn parse_data_type(&mut self) -> Result<DataType, ParserError>

Parse a SQL datatype (in the context of a CREATE TABLE statement for example)

Source

pub fn parse_string_values(&mut self) -> Result<Vec<String>, ParserError>

Parse a parenthesized, comma-separated list of single-quoted strings.

Source

pub fn parse_identifier_with_alias( &mut self, ) -> Result<IdentWithAlias, ParserError>

Strictly parse identifier AS identifier

Source

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.

Source

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.

Source

pub fn parse_optional_group_by( &mut self, ) -> Result<Option<GroupByExpr>, ParserError>

Parse an optional GROUP BY clause, returning Some(GroupByExpr) when present.

Source

pub fn parse_optional_order_by( &mut self, ) -> Result<Option<OrderBy>, ParserError>

Parse an optional ORDER BY clause, returning Some(OrderBy) when present.

Source

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(...)

Source

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.

Source

pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError>

Parse identifiers

Source

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: +"
);
Source

pub fn parse_identifier(&mut self) -> Result<Ident, ParserError>

Parse a simple one-word identifier (possibly quoted, possibly a keyword)

Source

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", ...)

Source

pub fn parse_parenthesized_compound_identifier_list( &mut self, optional: IsOptional, allow_empty: bool, ) -> Result<Vec<Expr>, ParserError>

Parse a parenthesized list of compound identifiers as expressions.

Source

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", ...)

Source

pub fn parse_precision(&mut self) -> Result<u64, ParserError>

Parse an unsigned precision value enclosed in parentheses, e.g. (10).

Source

pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError>

Parse an optional precision (n) and return it as Some(n) when present.

Source

pub fn parse_datetime_64( &mut self, ) -> Result<(u64, Option<String>), ParserError>

Parse datetime64 1 Syntax

DateTime64(precision[, timezone])
Source

pub fn parse_optional_character_length( &mut self, ) -> Result<Option<CharacterLength>, ParserError>

Parse an optional character length specification (n | MAX [CHARACTERS|OCTETS]).

Source

pub fn parse_optional_binary_length( &mut self, ) -> Result<Option<BinaryLength>, ParserError>

Parse an optional binary length specification like (n).

Source

pub fn parse_character_length(&mut self) -> Result<CharacterLength, ParserError>

Parse a character length, handling MAX or integer lengths with optional units.

Source

pub fn parse_binary_length(&mut self) -> Result<BinaryLength, ParserError>

Parse a binary length specification, returning BinaryLength.

Source

pub fn parse_optional_precision_scale( &mut self, ) -> Result<(Option<u64>, Option<u64>), ParserError>

Parse an optional (precision[, scale]) and return (Option<precision>, Option<scale>).

Source

pub fn parse_exact_number_optional_precision_scale( &mut self, ) -> Result<ExactNumberInfo, ParserError>

Parse exact-number precision/scale info like (precision[, scale]) for decimal types.

Source

pub fn parse_optional_type_modifiers( &mut self, ) -> Result<Option<Vec<String>>, ParserError>

Parse optional type modifiers appearing in parentheses e.g. (UNSIGNED, ZEROFILL).

Source

pub fn parse_delete( &mut self, delete_token: TokenWithSpan, ) -> Result<Statement, ParserError>

Parse a DELETE statement and return Statement::Delete.

Source

pub fn parse_kill(&mut self) -> Result<Statement, ParserError>

Parse a KILL statement, optionally specifying CONNECTION, QUERY, or MUTATION. KILL [CONNECTION | QUERY | MUTATION] processlist_id

Source

pub fn parse_explain( &mut self, describe_alias: DescribeAlias, ) -> Result<Statement, ParserError>

Parse an EXPLAIN statement, handling dialect-specific options and modifiers.

Source

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

Source

pub fn parse_for_clause(&mut self) -> Result<Option<ForClause>, ParserError>

Parse a mssql FOR [XML | JSON | BROWSE] clause

Source

pub fn parse_for_xml(&mut self) -> Result<ForClause, ParserError>

Parse a mssql FOR XML clause

Source

pub fn parse_for_json(&mut self) -> Result<ForClause, ParserError>

Parse a mssql FOR JSON clause

Source

pub fn parse_cte(&mut self) -> Result<Cte, ParserError>

Parse a CTE (alias [( col1, col2, ... )] AS (subquery))

Source

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_body
Source

pub fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator>

Parse a set operator token into its SetOperator variant.

Source

pub fn parse_set_quantifier( &mut self, op: &Option<SetOperator>, ) -> SetQuantifier

Parse a set quantifier (e.g., ALL, DISTINCT BY NAME) for the given set operator.

Source

pub fn parse_select(&mut self) -> Result<Select, ParserError>

Parse a restricted SELECT statement (no CTEs / UNION / ORDER BY)

Source

pub fn maybe_parse_connect_by( &mut self, ) -> Result<Vec<ConnectByKind>, ParserError>

Parse a CONNECT BY clause (Oracle-style hierarchical query support).

Source

pub fn parse_as_table(&mut self) -> Result<Table, ParserError>

Parse CREATE TABLE x AS TABLE y

Source

pub fn parse_set_session_params(&mut self) -> Result<Statement, ParserError>

Parse session parameter assignments after SET when no = or TO is present.

Source

pub fn parse_show(&mut self) -> Result<Statement, ParserError>

Parse a SHOW statement and dispatch to specific SHOW handlers.

Source

pub fn parse_show_create(&mut self) -> Result<Statement, ParserError>

Parse SHOW CREATE <object> returning the corresponding ShowCreate statement.

Source

pub fn parse_show_columns( &mut self, extended: bool, full: bool, ) -> Result<Statement, ParserError>

Parse SHOW COLUMNS/SHOW FIELDS and return a ShowColumns statement.

Source

pub fn parse_show_functions(&mut self) -> Result<Statement, ParserError>

Parse SHOW FUNCTIONS and optional filter.

Source

pub fn parse_show_collation(&mut self) -> Result<Statement, ParserError>

Parse SHOW COLLATION and optional filter.

Source

pub fn parse_show_statement_filter( &mut self, ) -> Result<Option<ShowStatementFilter>, ParserError>

Parse an optional filter used by SHOW statements (LIKE, ILIKE, WHERE, or literal).

Source

pub fn parse_use(&mut self) -> Result<Statement, ParserError>

Parse a USE statement (database/catalog/schema/warehouse/role selection).

Source

pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError>

Parse a table factor followed by any join clauses, returning TableWithJoins.

Source

pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError>

A table name or a parenthesized subquery, followed by optional [AS] alias

Source

pub fn maybe_parse_table_version( &mut self, ) -> Result<Option<TableVersion>, ParserError>

Parses a the timestamp version specifier (i.e. query historical data)

Source

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

Source

pub fn parse_openjson_table_column_def( &mut self, ) -> Result<OpenJsonTableColumn, ParserError>

Source

pub fn parse_derived_table_factor( &mut self, lateral: IsLateral, ) -> Result<TableFactor, ParserError>

Parse a derived table factor (a parenthesized subquery), handling optional LATERAL.

Source

pub fn parse_expr_with_alias(&mut self) -> Result<ExprWithAlias, ParserError>

Parses an expression with an optional alias

Examples:

SUM(price) AS total_price
SUM(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));
Source

pub fn parse_pivot_table_factor( &mut self, table: TableFactor, ) -> Result<TableFactor, ParserError>

Parse a PIVOT table factor (ClickHouse/Oracle style pivot), returning a TableFactor.

Source

pub fn parse_unpivot_table_factor( &mut self, table: TableFactor, ) -> Result<TableFactor, ParserError>

Parse an UNPIVOT table factor, returning a TableFactor.

Source

pub fn parse_join_constraint( &mut self, natural: bool, ) -> Result<JoinConstraint, ParserError>

Parse a JOIN constraint (NATURAL, ON <expr>, USING (...), or no constraint).

Source

pub fn parse_grant(&mut self) -> Result<Grant, ParserError>

Parse a GRANT statement.

Source

pub fn parse_grant_deny_revoke_privileges_objects( &mut self, ) -> Result<(Privileges, Option<GrantObjects>), ParserError>

Parse privileges and optional target objects for GRANT/DENY/REVOKE statements.

Source

pub fn parse_grant_permission(&mut self) -> Result<Action, ParserError>

Parse a single grantable permission/action (used within GRANT statements).

Source

pub fn parse_grantee_name(&mut self) -> Result<GranteeName, ParserError>

Parse a grantee name, possibly with a host qualifier (user@host).

Source

pub fn parse_deny(&mut self) -> Result<Statement, ParserError>

Source

pub fn parse_revoke(&mut self) -> Result<Revoke, ParserError>

Parse a REVOKE statement

Source

pub fn parse_replace( &mut self, replace_token: TokenWithSpan, ) -> Result<Statement, ParserError>

Parse an REPLACE statement

Source

pub fn parse_insert( &mut self, insert_token: TokenWithSpan, ) -> Result<Statement, ParserError>

Parse an INSERT statement

Source

pub fn parse_input_format_clause( &mut self, ) -> Result<InputFormatClause, ParserError>

Source

pub fn parse_insert_partition( &mut self, ) -> Result<Option<Vec<Expr>>, ParserError>

Parse an optional PARTITION (...) clause for INSERT statements.

Source

pub fn parse_load_data_table_format( &mut self, ) -> Result<Option<HiveLoadDataFormat>, ParserError>

Parse optional Hive INPUTFORMAT ... SERDE ... clause used by LOAD DATA.

Source

pub fn parse_update( &mut self, update_token: TokenWithSpan, ) -> Result<Statement, ParserError>

Parse an UPDATE statement and return Statement::Update.

Source

pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError>

Parse a var = expr assignment, used in an UPDATE statement

Source

pub fn parse_assignment_target( &mut self, ) -> Result<AssignmentTarget, ParserError>

Parse the left-hand side of an assignment, used in an UPDATE statement

Source

pub fn parse_function_args(&mut self) -> Result<FunctionArg, ParserError>

Parse a single function argument, handling named and unnamed variants.

Source

pub fn parse_optional_args(&mut self) -> Result<Vec<FunctionArg>, ParserError>

Parse an optional, comma-separated list of function arguments (consumes closing paren).

Source

pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError>

Parse a comma-delimited list of projections after SELECT

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn parse_optional_select_item_rename( &mut self, ) -> Result<Option<RenameSelectItem>, ParserError>

Parse a Rename information for wildcard select items.

Source

pub fn parse_optional_select_item_replace( &mut self, ) -> Result<Option<ReplaceSelectItem>, ParserError>

Parse a Replace information for wildcard select items.

Source

pub fn parse_replace_elements( &mut self, ) -> Result<ReplaceSelectElement, ParserError>

Parse a single element of a REPLACE (...) select-item clause.

Source

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.

Source

pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError>

Parse an OrderByExpr expression.

Source

pub fn parse_create_index_expr(&mut self) -> Result<IndexColumn, ParserError>

Parse an IndexColumn.

Source

pub fn parse_with_fill(&mut self) -> Result<WithFill, ParserError>

Parse a WITH FILL clause used in ORDER BY (ClickHouse dialect).

Source

pub fn parse_interpolations( &mut self, ) -> Result<Option<Interpolate>, ParserError>

Parse a set of comma separated INTERPOLATE expressions (ClickHouse dialect) that follow the INTERPOLATE keyword in an ORDER BY clause with the WITH FILL modifier

Source

pub fn parse_interpolation(&mut self) -> Result<InterpolateExpr, ParserError>

Parse a INTERPOLATE expression (ClickHouse dialect)

Source

pub fn parse_top(&mut self) -> Result<Top, ParserError>

Parse a TOP clause, MSSQL equivalent of LIMIT, that follows after SELECT [DISTINCT].

Source

pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError>

Parse a LIMIT clause

Source

pub fn parse_offset(&mut self) -> Result<Offset, ParserError>

Parse an OFFSET clause

Source

pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError>

Parse a FETCH clause

Source

pub fn parse_lock(&mut self) -> Result<LockClause, ParserError>

Parse a FOR UPDATE/FOR SHARE clause

Source

pub fn parse_values( &mut self, allow_empty: bool, value_keyword: bool, ) -> Result<Values, ParserError>

Parse a VALUES clause

Source

pub fn parse_start_transaction(&mut self) -> Result<Statement, ParserError>

Parse a ‘START TRANSACTION’ statement

Source

pub fn parse_begin(&mut self) -> Result<Statement, ParserError>

Parse a ‘BEGIN’ statement

Source

pub fn parse_begin_exception_end(&mut self) -> Result<Statement, ParserError>

Parse a ‘BEGIN … EXCEPTION … END’ block

Source

pub fn parse_end(&mut self) -> Result<Statement, ParserError>

Parse an ‘END’ statement

Source

pub fn parse_transaction_modes( &mut self, ) -> Result<Vec<TransactionMode>, ParserError>

Parse a list of transaction modes

Source

pub fn parse_commit(&mut self) -> Result<Statement, ParserError>

Parse a ‘COMMIT’ statement

Source

pub fn parse_rollback(&mut self) -> Result<Statement, ParserError>

Parse a ‘ROLLBACK’ statement

Source

pub fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError>

Parse an optional AND [NO] CHAIN clause for COMMIT and ROLLBACK statements

Source

pub fn parse_rollback_savepoint(&mut self) -> Result<Option<Ident>, ParserError>

Parse an optional ‘TO SAVEPOINT savepoint_name’ clause for ROLLBACK statements

Source

pub fn parse_raiserror(&mut self) -> Result<Statement, ParserError>

Parse a ‘RAISERROR’ statement

Source

pub fn parse_raiserror_option(&mut self) -> Result<RaisErrorOption, ParserError>

Parse a single RAISERROR option

Source

pub fn parse_deallocate(&mut self) -> Result<Statement, ParserError>

Parse a SQL DEALLOCATE statement

Source

pub fn parse_execute(&mut self) -> Result<Statement, ParserError>

Parse a SQL EXECUTE statement

Source

pub fn parse_prepare(&mut self) -> Result<Statement, ParserError>

Parse a SQL PREPARE statement

Source

pub fn parse_unload(&mut self) -> Result<Statement, ParserError>

Parse a SQL UNLOAD statement

Source

pub fn parse_pragma(&mut self) -> Result<Statement, ParserError>

PRAGMA [schema-name ‘.’] pragma-name [(‘=’ pragma-value) | ‘(’ pragma-value ‘)’]

Source

pub fn parse_install(&mut self) -> Result<Statement, ParserError>

INSTALL [extension_name]

Source

pub fn parse_load(&mut self) -> Result<Statement, ParserError>

Parse a SQL LOAD statement

Source

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]]

ClickHouse

Source

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.

Source

pub fn parse_pg_create_server(&mut self) -> Result<Statement, ParserError>

Parse a CREATE SERVER statement.

See Statement::CreateServer

Source

pub fn index(&self) -> usize

The index of the first unprocessed token.

Source

pub fn parse_named_window( &mut self, ) -> Result<NamedWindowDefinition, ParserError>

Parse a named window definition.

Source

pub fn parse_create_procedure( &mut self, or_alter: bool, ) -> Result<Statement, ParserError>

Parse CREATE PROCEDURE statement.

Source

pub fn parse_window_spec(&mut self) -> Result<WindowSpec, ParserError>

Parse a window specification.

Source

pub fn parse_create_type(&mut self) -> Result<Statement, ParserError>

Parse CREATE TYPE statement.

Source

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

Source

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.