Skip to main content

Crate qusql_parse

Crate qusql_parse 

Source
Expand description

Parse SQL into an AST

This crate provides an lexer and parser that can parse SQL into an Abstract Syntax Tree (AST). Currently primarily focused on MariaDB/Mysql.

Example code:

use qusql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statement, Issues};

let options = ParseOptions::new()
    .dialect(SQLDialect::MariaDB)
    .arguments(SQLArguments::QuestionMark)
    .warn_unquoted_identifiers(true);


let sql = "SELECT `monkey`,
           FROM `t1` LEFT JOIN `t2` ON `t2`.`id` = `t1.two`
           WHERE `t1`.`id` = ?";
let mut issues = Issues::new(sql);
let ast = parse_statement(sql, &mut issues, &options);

println!("{}", issues);
println!("AST: {:#?}", ast);

Macros§

issue_ice
Construct an “Internal compiler error” issue, containing the current file and line
issue_todo
Construct an “Not yet implemented” issue, containing the current file and line

Structs§

AddColumn
ADD COLUMN specification
AddForeignKey
Add a foreign key
AddIndex
Add an index
AddTableConstraint
PostgreSQL: ADD CONSTRAINT … UNIQUE/PRIMARY KEY/CHECK
AggregateFunctionCallExpression
Algorithm
ALGORITHM specification
AlterColumn
ALTER COLUMN specification
AlterOperator
ALTER OPERATOR statement (PostgreSQL)
AlterOperatorClass
ALTER OPERATOR CLASS statement (PostgreSQL)
AlterOperatorFamily
ALTER OPERATOR FAMILY statement (PostgreSQL)
AlterRole
ALTER ROLE statement (PostgreSQL)
AlterSchema
ALTER SCHEMA statement (PostgreSQL)
AlterTable
Represent an alter table statement
AlterType
ALTER TYPE statement (PostgreSQL)
ArgExpression
Input argument to query, the first argument is the occurrence number of the argument
ArrayExpression
PostgreSQL ARRAY[…] literal expression
ArraySubscriptExpression
Array subscript or slice expression: expr[idx] or expr[lower:upper]
AutoIncrement
AUTO_INCREMENT specification
Begin
Begin statement
BetweenExpression
Between expression (expr BETWEEN low AND high)
BinaryExpression
Expression with binary operator
Block
Block statement, for example in stored procedures
BoolExpression
Literal bool expression “TRUE” or “FALSE”
Call
CALL statement — invokes a stored procedure
CaseExpression
Case expression
CaseStatement
Case statement
CastExpression
Cast expression
Change
CHANGE specification
CharFunctionExpression
CHAR(N,… [USING charset_name]) expression
CloseCursor
MariaDB/MySQL CLOSE cursor statement. CLOSE cursor_name
Commit
Commit statement
CompoundQuery
Compound query statement
CompoundQueryBranch
Right hand side branch of a compound query
ConvertExpression
Convert expression (CONVERT(expr, type) or CONVERT(expr USING charset))
CopyFrom
A PostgreSQL COPY ... FROM statement.
CopyTo
A PostgreSQL COPY ... TO statement.
CreateConstraintTrigger
Represent a create constraint trigger statement
CreateDatabase
CreateDomain
CREATE DOMAIN statement (PostgreSQL)
CreateExtension
CREATE EXTENSION statement (PostgreSQL)
CreateFunction
Representation of Create Function Statement
CreateIndex
CreateOperator
CREATE OPERATOR statement (PostgreSQL)
CreateOperatorClass
CREATE OPERATOR CLASS statement (PostgreSQL)
CreateOperatorFamily
CREATE OPERATOR FAMILY statement (PostgreSQL)
CreateProcedure
Representation of a CREATE PROCEDURE statement
CreateRole
CREATE ROLE statement (PostgreSQL)
CreateSchema
CREATE SCHEMA statement (PostgreSQL)
CreateSequence
CREATE SEQUENCE statement (PostgreSQL)
CreateServer
CREATE SERVER statement (PostgreSQL)
CreateTable
Represent a create table statement
CreateTableAs
CreateTablePartitionOf
CREATE TABLE name PARTITION OF parent_table (PostgreSQL)
CreateTrigger
Represent a create trigger statement
CreateTypeEnum
CreateView
Represent a create view statement
DataType
Type of data
DeclareCursor
PostgreSQL DECLARE cursor statement
DeclareCursorMariaDb
MariaDB/MySQL DECLARE cursor statement inside a stored procedure/function. DECLARE name CURSOR FOR select
DeclareHandler
MariaDB/MySQL DECLARE handler statement inside a stored procedure/function. DECLARE CONTINUE|EXIT HANDLER FOR condition statement
DeclareVariable
MariaDB/MySQL DECLARE variable statement inside a stored procedure/function. DECLARE name data_type [DEFAULT expr]
DefaultExpression
Literal DEFAULT expression
Delete
Represent a delete statement
DisableRowLevelSecurity
PostgreSQL: DISABLE ROW LEVEL SECURITY
DisableRule
PostgreSQL: DISABLE RULE rule_name
DisableTrigger
PostgreSQL: DISABLE TRIGGER { trigger_name | ALL | USER }
Do
Do statement
DropColumn
DROP COLUMN specification
DropDatabase
Represent a drop database statement
DropDomain
Represent a drop domain statement
DropEvent
Represent a drop event statement
DropExtension
Represent a drop extension statement (PostgreSQL)
DropForeignKey
DROP FOREIGN KEY specification
DropFunction
Represent a drop function statement
DropFunctionArg
DropIndex
Represent a drop index statement.
DropOperator
DropOperatorClass
Represent a drop operator class statement (PostgreSQL)
DropOperatorFamily
Represent a drop operator family statement (PostgreSQL)
DropOperatorItem
Represent a drop operator statement (PostgreSQL)
DropPrimaryKey
DROP PRIMARY KEY specification
DropProcedure
Represent a drop procedure statement
DropSequence
Represent a drop sequence statement (PostgreSQL)
DropServer
Represent a drop server statement
DropTable
Represent a drop table statement
DropTrigger
Represent a drop trigger statement
DropView
Represent a drop view statement
EnableRowLevelSecurity
PostgreSQL: ENABLE ROW LEVEL SECURITY
EnableRule
PostgreSQL: ENABLE [ REPLICA | ALWAYS ] RULE rule_name
EnableTrigger
PostgreSQL: ENABLE [ REPLICA | ALWAYS ] TRIGGER { trigger_name | ALL | USER }
End
End statement
ExistsExpression
Exists expression
Explain
PostgreSQL EXPLAIN statement
ExtractExpression
Extract expression
Fetch
Representation of a FETCH clause in VALUES
FetchCursor
MariaDB/MySQL FETCH cursor statement. FETCH [NEXT] [FROM] cursor INTO var, ...
FieldAccessExpression
PostgreSQL composite type field access: (expr).field
FloatExpression
Literal floating point expression
Flush
Parse mariadb FLUSH statement.
ForceRowLevelSecurity
PostgreSQL: FORCE ROW LEVEL SECURITY
ForeignKeyOn
Action to perform on events on foreign keys
Fragment
FunctionBody
Body of a CREATE FUNCTION AS clause
FunctionCallExpression
Function call expression,
FunctionParam
A single function parameter
GroupConcatExpression
Group contat expression
Identifier
Simple identifier in code it derefs to its string value
IdentifierExpression
Identifier pointing to column
If
If statement
IfCondition
Condition in if statement
InExpression
In expression
IncludeClause
IndexCol
Specify a column for an index, together with a with
IndexHint
InsertReplace
Representation of Insert or Replace Statement
InsertReplaceOnDuplicateKeyUpdate
InsertReplaceSet
InsertReplaceSetPair
IntegerExpression
Literal integer expression
Interval
Interior of Type::Interval.
IntervalExpression
Time Interval
Invalid
Invalid statement produced after recovering from parse error
InvalidExpression
Invalid expression, returned on recovery of a parse error
IsExpression
Is expression
Issue
An issue encountered during parsing, or later stages
IssueHandle
Issues
Iterate
MariaDB/MySQL ITERATE label statement. ITERATE label
Kill
Represent a MySQL KILL statement
Leave
MariaDB/MySQL LEAVE label statement. LEAVE label
ListHackExpression
Literal LIST expression
Lock
Represent a MySQL LOCK statement
LockMember
Locking
Loop
MariaDB/MySQL LOOP body END LOOP construct. [label:] LOOP body END LOOP [label]
MatchAgainstExpression
Full-text MATCH … AGAINST expression
MemberOfExpression
Member of expression
ModifyColumn
Modify a column
NoForceRowLevelSecurity
PostgreSQL: NO FORCE ROW LEVEL SECURITY
NullExpression
Literal NULL expression
OnConflict
OpenCursor
MariaDB/MySQL OPEN cursor statement. OPEN cursor_name
OwnerTo
OWNER TO specification
ParseOptions
Options used when parsing sql
PartitionBy
PARTITION BY clause, appended to a CREATE TABLE statement
Prepare
PostgreSQL PREPARE statement
QualifiedName
QuantifierExpression
PostgreSQL ANY / SOME / ALL quantifier expression.
RefreshMaterializedView
PostgreSQL REFRESH MATERIALIZED VIEW statement
RenameColumn
RENAME COLUMN specification
RenameConstraint
RENAME CONSTRAINT specification
RenameIndex
RENAME INDEX specification
RenameTable
Represent a rename table statement
RenameTo
RENAME TO specification
Repeat
MariaDB/MySQL REPEAT body UNTIL condition END REPEAT construct. [label:] REPEAT body UNTIL condition END REPEAT [label]
ReplicaIdentity
PostgreSQL: REPLICA IDENTITY { DEFAULT | USING INDEX | FULL | NOTHING }
Return
Return statement
RoleMembership
Role membership clause in CREATE ROLE
RowExpression
A row/tuple constructor expression: (expr1, expr2, ...)
SString
A string with attached span
Select
Representation of select Statement
SelectExpr
Value in select
Set
ShowCharacterSet
Parse result for SHOW CHARACTER SET / SHOW CHARSET
ShowCollation
Parse result for SHOW COLLATION
ShowColumns
Parse result for SHOW COLUMNS / SHOW FIELDS
ShowCreateDatabase
Parse result for SHOW CREATE DATABASE
ShowCreateTable
Parse result for SHOW CREATE TABLE
ShowCreateView
Parse result for SHOW CREATE VIEW
ShowDatabases
Parse result for SHOW DATABASES
ShowEngines
Parse result for SHOW ENGINES
ShowProcessList
Parse result for SHOW PROCESSLIST / SHOW FULL PROCESSLIST
ShowStatus
Parse result for SHOW STATUS
ShowTables
Parse result for SHOW TABLES variants
ShowVariables
Parse result for SHOW VARIABLES
Signal
Return statement
StartTransaction
Start transaction statement
Stdin
Stdin statement, used to represent input from stdin after a COPY statement
SubqueryExpression
Subquery expression
TableToTable
Timestamp
TimestampAddExpression
Timestampadd call
TimestampDiffExpression
Timestampdiff call
TriggerReference
TrimExpression
TRIM([{BOTH|LEADING|TRAILING} [remstr] FROM] str) expression
TruncateTable
TruncateTableSpec
Represent a truncate table statement
TypeCastExpression
PostgreSQL-style typecast expression (expr::type)
UnaryExpression
Expression with a unary (prefix) operator
Unlock
Represent a MySQL UNLOCK statement
Update
Representation of replace Statement
UserVariableExpression
User variable expression (@variable_name)
ValidateConstraint
PostgreSQL: VALIDATE CONSTRAINT constraint_name
Values
Representation of a VALUES statement
VariableExpression
Variable expression
When
When part of CASE
WhenStatement
When part of case statement
While
MariaDB/MySQL WHILE condition DO body END WHILE construct. [label:] WHILE condition DO body END WHILE [label]
WindowClause
WindowFrame
Window frame clause: ROWS/RANGE/GROUPS { frame_start | BETWEEN frame_start AND frame_end }
WindowFunctionCallExpression
A window function call expression
WindowSpec
When part of CASE
WithBlock
WithOption
A single key = value option inside a WITH (...) clause on CREATE INDEX.
WithQuery
Represent a with query statement

Enums§

AfterEvent
Enum for constraint trigger events
AlterAlgorithm
AlterColumnAction
Enum of alterations to perform on a column
AlterLock
AlterOperatorAction
ALTER OPERATOR actions (OWNER TO, SET SCHEMA, SET (…))
AlterOperatorClassAction
AlterOperatorFamilyAction
Actions for ALTER OPERATOR FAMILY (ADD, DROP, RENAME TO, OWNER TO, SET SCHEMA)
AlterRoleAction
Actions that can be performed in ALTER ROLE
AlterRoleValue
Parameters value for ALTER ROLE SET/RESET
AlterSchemaAction
AlterSpecification
Enum of alterations to perform on a table
AlterTableOwner
Owner value for ALTER TABLE OWNER TO
AlterTypeAction
ALTER TYPE actions
AttributeAction
Attribute actions for composite types
BinaryOperator
Binary operator to apply
CascadeOrRestrict
Drop cascade or restrict option (PostgreSQL)
CompoundOperator
Set operator used between compound query branches
CompoundQuantifier
Quantifier for a compound-query operator
CopyColumnList
A column list in a COPY option: either * (all columns) or ( col, ... ).
CopyHeaderValue
Value for the HEADER option: a boolean or MATCH.
CopyLocation
Where to read from / write to in a COPY statement.
CopyOption
A single WITH ( ... ) option in a COPY statement.
CopySource
The source / destination of a COPY: either a table (with optional column list) or a parenthesised query (only valid with TO).
CreateAlgorithm
Special algorithm used for table creation
CreateDatabaseOption
CreateDefinition
Definition in create table
CreateIndexOption
CreateOption
Options for create statement
CursorHold
Hold behaviour of a declared cursor
CursorScroll
Scroll behaviour of a declared cursor
CursorSensitivity
Sensitivity of a declared cursor
DataTypeProperty
A property on a datatype
Deferrable
Whether the trigger is deferrable
DeleteFlag
Flags for deletion
DoBody
Body of a DO statement
DomainConstraint
Domain constraint for CREATE DOMAIN
DropFunctionArgMode
ExplainFormat
PostgreSQL EXPLAIN output format
ExplainOption
A single option in a parenthesized EXPLAIN (…) list
Expression
Representation of an expression
FetchDirection
Direction for FETCH clause (FIRST or NEXT)
FlushOption
ForeignKeyMatch
MATCH type for a foreign key reference
ForeignKeyOnAction
Action to take on event for foreign key
ForeignKeyOnType
When to take a foreign key action
Function
Function to execute
FunctionCharacteristic
Characteristic of a function
FunctionLanguage
Language of a function
FunctionParallel
Parallel safety level of a function
FunctionParamDirection
Direction of a function argument
HandlerAction
Action part of a MariaDB/MySQL handler declaration.
HandlerCondition
Condition part of a MariaDB/MySQL handler declaration.
IdentifierPart
Part of a full identifier
IdentityOption
Identity restart option for TRUNCATE (PostgreSQL)
IndexColExpr
Column or expression specification for an index
IndexHintFor
IndexHintType
IndexHintUse
IndexOption
Option on an index
IndexType
Type of index to add
Initially
Initial timing of the constraint trigger
InsertReplaceFlag
Flags for insert
InsertReplaceType
IntervalField
A single field qualifier for an INTERVAL type.
Is
Type of is expression
JoinSpecification
Specification for join
JoinType
Type of join
JsonTableColumn
JSON_TABLE column definition
JsonTableOnErrorEmpty
JSON_TABLE ON EMPTY/ERROR behavior
KillType
LeftOperatorType
Left operator type for ALTER OPERATOR (explicitly stores NONE span or DataType)
Level
Level of an issues
LockStrength
Lock strength for locking
LockType
LockWait
MatchMode
Mode for MATCH … AGAINST
MaterializedHint
PostgreSQL CTE materialization hint
OnCommitAction
Action for ON COMMIT clause on temporary tables
OnConflictAction
OnConflictTarget
OperatorClassItem
OperatorClassOperatorOption
OperatorFamilyDropItem
Item to drop from an operator family (OPERATOR or FUNCTION)
OperatorFamilyItem
Item to add to an operator family (OPERATOR or FUNCTION)
OperatorOption
Options for CREATE OPERATOR
OperatorRef
Reference to an operator
OrderFlag
Ordering direction
PartitionBoundExpr
A single value in a partition bound specification: an expression, MINVALUE, or MAXVALUE
PartitionBoundSpec
The partition bound specification for CREATE TABLE … PARTITION OF
PartitionMethod
The partitioning method for PARTITION BY
PartitionOfBound
The bound clause of a PARTITION OF statement
Quantifier
Which row quantifier keyword was used
RangeSubtype
Subtype for a built-in PostgreSQL range or multirange type.
ReplicaIdentityOption
Options for REPLICA IDENTITY
RoleMembershipType
Role membership type for CREATE ROLE
RoleOption
Role option for CREATE ROLE / ALTER ROLE
SQLArguments
What kinds or arguments
SQLDialect
What sql diarect to parse as
SelectFlag
Flags specified after SELECT
SequenceOption
Sequence option for CREATE SEQUENCE / ALTER SEQUENCE
SignalConditionInformationName
Statement
SQL statement
TableConstraintType
Table constraint types for ADD CONSTRAINT
TableFunctionName
The name of a table-valued function in a FROM clause.
TableOption
Options on created table
TableReference
Reference to table in select
TimeUnit
Units of time
TriggerEvent
On what event to fire the trigger
TriggerName
Trigger name variants for ENABLE/DISABLE TRIGGER
TriggerReferenceDirection
TriggerTime
When to fire the trigger
TrimDirection
Direction for TRIM()
Type
Type of datatype
UnaryOperator
Unary operator to apply
UpdateFlag
Flags specified after “UPDATE”
UsingIndexMethod
Variable
Function to execute
WindowFrameBound
One bound in a window frame clause
WindowFrameMode
Window frame mode: ROWS, RANGE, or GROUPS

Traits§

OptSpanned
Compute an optional byte span of an ast fragment
Spanned
Compute byte span of an ast fragment

Functions§

parse_statement
Parse a single statement, A statement may be returned even if there where parse errors. The statement is free of errors if no Error issues are added to issues
parse_statements
Parse multiple statements, return an Vec of Statements even if there are parse errors. The statements are free of errors if no Error issues are added to issues

Type Aliases§

Span
Byte span of ast fragment