Struct sqlparser::parser::Parser

source ·
pub struct Parser<'a> { /* private fields */ }

Implementations§

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

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

Reset this parser to parse the specified token stream

Reset this parser state to parse the specified tokens

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

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

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

Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.), stopping before the statement separator, if any.

Parse a new expression including wildcard & qualified wildcard

Parse a new expression

Parse tokens until the precedence changes

Get the precedence of the next token With AND, OR, and XOR

Parse an expression prefix

Parse CURRENT ROW or { <positive number> | UNBOUNDED } { PRECEDING | FOLLOWING }

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

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

Parse a BigQuery SAFE_CAST function e.g. SAFE_CAST(expr AS FLOAT64)

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

TRIM ([WHERE] ['text' FROM] 'text')
TRIM ('text')

Parses an array expression [ex1, ex2, ..] if named is true, came from an expression like ARRAY[ex1, ex2]

Parse a SQL LISTAGG expression, e.g. LISTAGG(...) WITHIN GROUP (ORDER BY ...).

Parses fulltext expressions (1)

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.

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 and BigQuey only):INTERVAL 1 DAY

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

Parse an operator following an expression

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

Parses the parens following the [ NOT ] IN operator

Parses BETWEEN <low> AND <high>, assuming the BETWEEN keyword was already consumed

Parse a postgresql casting style which is in the form of expr::datatype

Get the precedence of the next token

Return the first non-whitespace token that has not yet been processed (or None if reached end-of-file)

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

Return the first non-whitespace token that has not yet been processed (or None if reached end-of-file) and mark it as processed. OK to call repeatedly after reaching EOF.

Return the first unprocessed token, possibly whitespace.

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

Report unexpected token

Look for an expected keyword and consume it if it exists

Look for an expected sequence of keywords and consume them if they exist

Look for one of the given keywords and return the one that matches.

Bail out if the current token is not one of the expected keywords, or consume it if it is

Bail out if the current token is not an expected keyword, or consume it if it is

Bail out if the following tokens are not the expected sequence of keywords, or consume them if they are.

Consume the next token if it matches the expected token, otherwise return false

Bail out if the current token is not an expected keyword, or consume it if it is

Parse a comma-separated list of 1+ SelectItem

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

Parse either ALL or DISTINCT. Returns true if DISTINCT is parsed and results in a ParserError if both ALL and DISTINCT are fround.

Parse a SQL CREATE statement

Parse a CACHE TABLE statement

Parse ‘AS’ before as query,such as WITH XXX AS SELECT XXX oer CACHE TABLE AS SELECT XXX

Parse a UNCACHE TABLE statement

SQLite-specific CREATE VIRTUAL TABLE

DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
    CURSOR [ { WITH | WITHOUT } HOLD ] FOR query

Parse a copy statement

Parse a tab separated values in COPY payload

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

Parse an unsigned literal integer/long

Parse a literal string

Parse a map key string

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

Strictly parse identifier AS identifier

Parse AS identifier (or simply identifier if it’s not a reserved keyword) Some examples with aliases: SELECT 1 foo, SELECT COUNT(*) AS cnt, SELECT ... FROM t1 foo, t2 bar, SELECT ... FROM (...) AS bar

Parse AS identifier when the AS is describing a table-valued object, 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.

Parse a possibly qualified, possibly quoted identifier, e.g. foo or `myschema.“table”

Parse identifiers

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

Parse a parenthesized comma-separated list of unqualified, possibly quoted identifiers

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

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

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

Parse a restricted SELECT statement (no CTEs / UNION / ORDER BY), assuming the initial SELECT was already consumed

Parse CREATE TABLE x AS TABLE y

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

Parse a GRANT statement.

Parse a REVOKE statement

Parse an INSERT statement

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

Parse a comma-delimited list of projections after SELECT

Parse an WildcardAdditionalOptions information for wildcard select items.

If it is not possible to parse it, will return an option.

Parse an Exclude information for wildcard select items.

If it is not possible to parse it, will return an option.

Parse an Except information for wildcard select items.

If it is not possible to parse it, will return an option.

Parse a Rename information for wildcard select items.

Parse an expression, optionally followed by ASC or DESC (used in ORDER BY)

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

Parse a LIMIT clause

Parse an OFFSET clause

Parse a FETCH clause

Parse a FOR UPDATE/FOR SHARE clause

CREATE [ { TEMPORARY | TEMP } ] SEQUENCE [ IF NOT EXISTS ] <sequence_name>

See Postgres docs for more details.

The index of the first unprocessed token.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.