├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── HEADER ├── LICENSE.TXT ├── README.md ├── docs └── custom_sql_parser.md ├── examples ├── cli.rs └── parse_select.rs ├── rustfmt.toml ├── src ├── ast │ ├── data_type.rs │ ├── ddl.rs │ ├── mod.rs │ ├── operator.rs │ ├── query.rs │ ├── value.rs │ ├── value │ │ └── datetime.rs │ └── visit_macro.rs ├── dialect │ ├── ansi.rs │ ├── generic.rs │ ├── keywords.rs │ ├── mod.rs │ ├── mssql.rs │ ├── mysql.rs │ └── postgresql.rs ├── lib.rs ├── parser.rs ├── parser │ └── datetime.rs ├── test_utils.rs └── tokenizer.rs └── tests ├── sqlparser_common.rs ├── sqlparser_mssql.rs ├── sqlparser_mysql.rs └── sqlparser_postgres.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | # IDEs 13 | .idea 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | sudo: required 3 | cache: cargo 4 | language: rust 5 | addons: 6 | apt: 7 | packages: 8 | - kcov 9 | - libcurl4-openssl-dev 10 | - libelf-dev 11 | - libdw-dev 12 | - binutils-dev 13 | - cmake 14 | sources: 15 | - kalakris-cmake 16 | # The version of kcov shipped with Xenial (v25) doesn't support the 17 | # --verify option that `cargo coveralls` passes. This PPA has a more 18 | # up-to-date version. It can be removed if Ubuntu ever ships a newer 19 | # version, or replaced with another PPA if this one falls out of date. 20 | - sourceline: ppa:sivakov512/kcov 21 | 22 | rust: 23 | - stable 24 | 25 | before_script: 26 | - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH 27 | - export PATH=$HOME/.cargo/bin:$PATH 28 | # `cargo install` fails if the specified binary is already installed, and 29 | # doesn't yet support a `--if-not-installed` option [0], so for now assume 30 | # failures mean the package is already installed. If installation truly 31 | # failed, the build will fail later anyway, when we try to use the installed 32 | # binary. Note that `cargo install --force` is not a solution, as it always 33 | # rebuilds from scratch, ignoring the cache entirely. 34 | # 35 | # [0]: https://github.com/rust-lang/cargo/issues/2082 36 | - cargo install cargo-update || echo "cargo-update already installed" 37 | - cargo install cargo-travis || echo "cargo-travis already installed" 38 | - cargo install-update -a # updates cargo-travis, if the cached version is outdated 39 | - rustup component add clippy 40 | # The license_template_path setting we use to verify copyright headers is 41 | # only available on the nightly rustfmt. 42 | - rustup toolchain install nightly && rustup component add --toolchain nightly rustfmt 43 | 44 | script: 45 | # Clippy must be run first, as its lints are only triggered during 46 | # compilation. Put another way: after a successful `cargo build`, `cargo 47 | # clippy` is guaranteed to produce no results. This bug is known upstream: 48 | # https://github.com/rust-lang/rust-clippy/issues/2604. 49 | - travis-cargo clippy -- --all-targets --all-features -- -D warnings 50 | - travis-cargo build 51 | - travis-cargo test 52 | - travis-cargo test -- all-features 53 | - cargo +nightly fmt -- --check --config-path <(echo 'license_template_path = "HEADER"') 54 | 55 | after_success: 56 | - cargo coveralls --verbose 57 | 58 | env: 59 | global: 60 | - TRAVIS_CARGO_NIGHTLY_FEATURE="" 61 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project aims to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 5 | 6 | Given that the parser produces a typed AST, any changes to the AST will technically be breaking and thus will result in a `0.(N+1)` version. We document changes that break via addition as "Added". 7 | 8 | ## [Unreleased] 9 | Nothing here yet! Check https://github.com/andygrove/sqlparser-rs/commits/master for undocumented changes. 10 | 11 | ### Changed 12 | 13 | - Now supports parsing date and time types 14 | - ast::Value::Interval changed its representation to include an inner 15 | IntervalValue that includes a `ParsedDateTime` and some useful methods. 16 | - ast::Value::Date changed its representation to include an inner 17 | `ParsedDate` 18 | 19 | ## [0.4.0] - 2019-07-02 20 | This release brings us closer to SQL-92 support, mainly thanks to the improvements contributed back from @MaterializeInc's fork and other work by @benesch. 21 | 22 | ### Changed 23 | - Remove "SQL" from type and enum variant names, `SQLType` -> `DataType`, remove "sql" prefix from module names (#105, #122) 24 | - Rename `ASTNode` -> `Expr` (#119) 25 | - Improve consistency of binary/unary op nodes (#112): 26 | - `ASTNode::SQLBinaryExpr` is now `Expr::BinaryOp` and `ASTNode::SQLUnary` is `Expr::UnaryOp`; 27 | - The `op: SQLOperator` field is now either a `BinaryOperator` or an `UnaryOperator`. 28 | - Change the representation of JOINs to match the standard (#109): `SQLSelect`'s `relation` and `joins` are replaced with `from: Vec`. Before this change `FROM foo NATURAL JOIN bar, baz` was represented as "foo" as the `relation` followed by two joins (`Inner(Natural)` and `Implicit`); now it's two `TableWithJoins` (`foo NATURAL JOIN bar` and `baz`). 29 | - Extract a `SQLFunction` struct (#89) 30 | - Replace `Option>` with `Vec` in the AST structs (#73) 31 | - Change `Value::Long()` to be unsigned, use u64 consistently (#65) 32 | 33 | ### Added 34 | - Infra: 35 | - Implement `fmt::Display` on AST nodes (#124) - thanks @vemoo! 36 | - Implement `Hash` (#88) and `Eq` (#123) on all AST nodes 37 | - Implement `std::error::Error` for `ParserError` (#72) 38 | - Handle Windows line-breaks (#54) 39 | - Expressions: 40 | - Support `INTERVAL` literals (#103) 41 | - Support `DATE` / `TIME` / `TIMESTAMP` literals (#99) 42 | - Support `EXTRACT` (#96) 43 | - Support `X'hex value'` literals (#95) 44 | - Support `EXISTS` subqueries (#90) 45 | - Support nested expressions in `BETWEEN` (#80) 46 | - Support `COUNT(DISTINCT x)` and similar (#77) 47 | - Support `CASE operand WHEN expected_value THEN ..` and table-valued functions (#59) 48 | - Support analytic (window) functions (`OVER` clause) (#50) 49 | - Queries / DML: 50 | - Support nested joins (#100) and derived tables with set operations (#111) 51 | - Support `UPDATE` statements (#97) 52 | - Support `INSERT INTO foo SELECT * FROM bar` and `FROM VALUES (...)` (#91) 53 | - Support `SELECT ALL` (#76) 54 | - Add `FETCH` and `OFFSET` support, and `LATERAL` (#69) - thanks @thomas-jeepe! 55 | - Support `COLLATE`, optional column list in CTEs (#64) 56 | - DDL/TCL: 57 | - Support `START/SET/COMMIT/ROLLBACK TRANSACTION` (#106) - thanks @SamuelMarks! 58 | - Parse column constraints in any order (#93) 59 | - Parse `DECIMAL` and `DEC` aliases for `NUMERIC` type (#92) 60 | - Support `DROP [TABLE|VIEW]` (#75) 61 | - Support arbitrary `WITH` options for `CREATE [TABLE|VIEW]` (#74) 62 | - Support constraints in `CREATE TABLE` (#65) 63 | - Add basic MSSQL dialect (#61) and some MSSQL-specific features: 64 | - `CROSS`/`OUTER APPLY` (#120) 65 | - MSSQL identifier and alias parsing rules (#66) 66 | - `WITH` hints (#59) 67 | 68 | ### Fixed 69 | - Report an error for `SELECT * FROM a OUTER JOIN b` instead of parsing `OUTER` as an alias (#118) 70 | - Fix the precedence of `NOT LIKE` (#82) and unary `NOT` (#107) 71 | - Do not panic when `NOT` is not followed by an expected keyword (#71) 72 | successfully instead of returning a parse error - thanks @ivanceras! (#67) - and similar fixes for queries with no `FROM` (#116) 73 | - Fix issues with `ALTER TABLE ADD CONSTRAINT` parsing (#65) 74 | - Serialize the "not equals" operator as `<>` instead of `!=` (#64) 75 | - Remove dependencies on `uuid` (#59) and `chrono` (#61) 76 | - Make `SELECT` query with `LIMIT` clause but no `WHERE` parse - Fix incorrect behavior of `ASTNode::SQLQualifiedWildcard::to_string()` (returned `foo*` instead of `foo.*`) - thanks @thomas-jeepe! (#52) 77 | 78 | ## [0.3.1] - 2019-04-20 79 | ### Added 80 | - Extended `SQLStatement::SQLCreateTable` to support Hive's EXTERNAL TABLES (`CREATE EXTERNAL TABLE .. STORED AS .. LOCATION '..'`) - thanks @zhzy0077! (#46) 81 | - Parse `SELECT DISTINCT` to `SQLSelect::distinct` (#49) 82 | 83 | ## [0.3.0] - 2019-04-03 84 | ### Changed 85 | This release includes major changes to the AST structs to add a number of features, as described in #37 and #43. In particular: 86 | - `ASTNode` variants that represent statements were extracted from `ASTNode` into a separate `SQLStatement` enum; 87 | - `Parser::parse_sql` now returns a `Vec` of parsed statements. 88 | - `ASTNode` now represents an expression (renamed to `Expr` in 0.4.0) 89 | - The query representation (formerly `ASTNode::SQLSelect`) became more complicated to support: 90 | - `WITH` and `UNION`/`EXCEPT`/`INTERSECT` (via `SQLQuery`, `Cte`, and `SQLSetExpr`), 91 | - aliases and qualified wildcards in `SELECT` (via `SQLSelectItem`), 92 | - and aliases in `FROM`/`JOIN` (via `TableFactor`). 93 | - A new `SQLObjectName` struct is used instead of `String` or `ASTNode::SQLCompoundIdentifier` - for objects like tables, custom types, etc. 94 | - Added support for "delimited identifiers" and made keywords context-specific (thus accepting them as valid identifiers in most contexts) - **this caused a regression in parsing `SELECT .. FROM .. LIMIT ..` (#67), fixed in 0.4.0** 95 | 96 | ### Added 97 | Other than the changes listed above, some less intrusive additions include: 98 | - Support `CREATE [MATERIALIZED] VIEW` statement 99 | - Support `IN`, `BETWEEN`, unary +/- in epressions 100 | - Support `CHAR` data type and `NUMERIC` not followed by `(p,s)`. 101 | - Support national string literals (`N'...'`) 102 | 103 | ## [0.2.4] - 2019-03-08 104 | Same as 0.2.2. 105 | 106 | ## [0.2.3] - 2019-03-08 [YANKED] 107 | 108 | ## [0.2.2] - 2019-03-08 109 | ### Changed 110 | - Removed `Value::String`, `Value::DoubleQuotedString`, and `Token::String`, making 111 | - `'...'` parse as a string literal (`Value::SingleQuotedString`), and 112 | - `"..."` fail to parse until version 0.3.0 (#36) 113 | 114 | ## [0.2.1] - 2019-01-13 115 | We don't have a changelog for the changes made in 2018, but thanks to @crw5996, @cswinter, @fredrikroos, @ivanceras, @nickolay, @virattara for their contributions in the early stages of the project! 116 | 117 | ## [0.1.0] - 2018-09-03 118 | Initial release 119 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sqlparser" 3 | description = "Extensible SQL Lexer and Parser with support for ANSI SQL:2011" 4 | version = "0.4.1-alpha.0" 5 | authors = ["Andy Grove "] 6 | homepage = "https://github.com/andygrove/sqlparser-rs" 7 | documentation = "https://docs.rs/sqlparser/" 8 | keywords = [ "ansi", "sql", "lexer", "parser" ] 9 | repository = "https://github.com/andygrove/sqlparser-rs" 10 | license = "Apache-2.0" 11 | include = [ 12 | "src/**/*.rs", 13 | "Cargo.toml", 14 | ] 15 | edition = "2018" 16 | 17 | [lib] 18 | name = "sqlparser" 19 | path = "src/lib.rs" 20 | 21 | [dependencies] 22 | bigdecimal = { version = "0.1.0", optional = true } 23 | log = "0.4.5" 24 | 25 | [dev-dependencies] 26 | simple_logger = "1.0.1" 27 | matches = "0.1" 28 | -------------------------------------------------------------------------------- /HEADER: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Materialize SQL parser 2 | 3 | This parser is a fork of , with 4 | some additional patches from . 5 | 6 | At the time the parser was originally forked (March 2019), there was no modular 7 | means by which its SQL syntax could be extended. This is particularly 8 | unfortunate because the parser is under active upstream development, and we'd 9 | like to periodically incorporate as much of their work as possible. 10 | 11 | When hacking on this repository, please try to minimize the divergence from 12 | upstream, e.g. by limiting unnecessary refactoring, so that upstream patches can 13 | be easily incorporated. 14 | 15 | At some point, if the parsers diverge enough, it may be worth jettisoning 16 | compatibility with upstream so that we can perform large-scale refactors, but we 17 | should make such a decision deliberately, not accidentally. 18 | 19 | ## Upstream overview 20 | 21 | The goal of this project is to build a SQL lexer and parser capable of parsing 22 | SQL that conforms with the [ANSI/ISO SQL standard][sql-standard] while also 23 | making it easy to support custom dialects so that this crate can be used as a 24 | foundation for vendor-specific parsers. 25 | 26 | This parser is currently being used by the [DataFusion] query engine and 27 | [LocustDB]. 28 | 29 | ## Example 30 | 31 | To parse a simple `SELECT` statement: 32 | 33 | ```rust 34 | use sqlparser::dialect::GenericDialect; 35 | use sqlparser::parser::Parser; 36 | 37 | let sql = "SELECT a, b, 123, myfunc(b) \ 38 | FROM table_1 \ 39 | WHERE a > b AND b < 100 \ 40 | ORDER BY a DESC, b"; 41 | 42 | let dialect = GenericDialect {}; // or AnsiDialect, or your own dialect ... 43 | 44 | let ast = Parser::parse_sql(&dialect, sql.to_string()).unwrap(); 45 | 46 | println!("AST: {:?}", ast); 47 | ``` 48 | 49 | This outputs 50 | 51 | ```rust 52 | AST: [Query(Query { ctes: [], body: Select(Select { distinct: false, projection: [UnnamedExpr(Identifier("a")), UnnamedExpr(Identifier("b")), UnnamedExpr(Value(Long(123))), UnnamedExpr(Function(Function { name: ObjectName(["myfunc"]), args: [Identifier("b")], over: None, distinct: false }))], from: [TableWithJoins { relation: Table { name: ObjectName(["table_1"]), alias: None, args: [], with_hints: [] }, joins: [] }], selection: Some(BinaryOp { left: BinaryOp { left: Identifier("a"), op: Gt, right: Identifier("b") }, op: And, right: BinaryOp { left: Identifier("b"), op: Lt, right: Value(Long(100)) } }), group_by: [], having: None }), order_by: [OrderByExpr { expr: Identifier("a"), asc: Some(false) }, OrderByExpr { expr: Identifier("b"), asc: None }], limit: None, offset: None, fetch: None })] 53 | ``` 54 | 55 | ## SQL compliance 56 | 57 | SQL was first standardized in 1987, and revisions of the standard have been 58 | published regularly since. Most revisions have added significant new features to 59 | the language, and as a result no database claims to support the full breadth of 60 | features. This parser currently supports most of the SQL-92 syntax, plus some 61 | syntax from newer versions that have been explicitly requested, plus some MSSQL- 62 | and PostgreSQL-specific syntax. Whenever possible, the [online SQL:2011 63 | grammar][sql-2011-grammar] is used to guide what syntax to accept. (We will 64 | happily accept changes that conform to the SQL:2016 syntax as well, but that 65 | edition's grammar is not yet available online.) 66 | 67 | Unfortunately, stating anything more specific about compliance is difficult. 68 | There is no publicly available test suite that can assess compliance 69 | automatically, and doing so manually would strain the project's limited 70 | resources. Still, we are interested in eventually supporting the full SQL 71 | dialect, and we are slowly building out our own test suite. 72 | 73 | If you are assessing whether this project will be suitable for your needs, 74 | you'll likely need to experimentally verify whether it supports the subset of 75 | SQL that you need. Please file issues about any unsupported queries that you 76 | discover. Doing so helps us prioritize support for the portions of the standard 77 | that are actually used. Note that if you urgently need support for a feature, 78 | you will likely need to write the implementation yourself. See the 79 | [Contributing](#Contributing) section for details. 80 | 81 | ### Supporting custom SQL dialects 82 | 83 | This is a work in progress, but we have some notes on [writing a custom SQL 84 | parser](docs/custom_sql_parser.md). 85 | 86 | ## Design 87 | 88 | The core expression parser uses the [Pratt Parser] design, which is a top-down 89 | operator-precedence (TDOP) parser, while the surrounding SQL statement parser is 90 | a traditional, hand-written recursive descent parser. Eli Bendersky has a good 91 | [tutorial on TDOP parsers][tdop-tutorial], if you are interested in learning 92 | more about the technique. 93 | 94 | We are a fan of this design pattern over parser generators for the following 95 | reasons: 96 | 97 | - Code is simple to write and can be concise and elegant 98 | - Performance is generally better than code generated by parser generators 99 | - Debugging is much easier with hand-written code 100 | - It is far easier to extend and make dialect-specific extensions 101 | compared to using a parser generator 102 | 103 | ## Contributing 104 | 105 | Contributions are highly encouraged! 106 | 107 | Pull requests that add support for or fix a bug in a feature in the SQL 108 | standard, or a feature in a popular RDBMS, like Microsoft SQL Server or 109 | PostgreSQL, will almost certainly be accepted after a brief review. For 110 | particularly large or invasive changes, consider opening an issue first, 111 | especially if you are a first time contributor, so that you can coordinate with 112 | the maintainers. CI will ensure that your code passes `cargo test`, 113 | `cargo fmt`, and `cargo clippy`, so you will likely want to run all three 114 | commands locally before submitting your PR. 115 | 116 | If you are unable to submit a patch, feel free to file an issue instead. Please 117 | try to include: 118 | 119 | * some representative examples of the syntax you wish to support or fix; 120 | * the relevant bits of the [SQL grammar][sql-2011-grammar], if the syntax is 121 | part of SQL:2011; and 122 | * links to documentation for the feature for a few of the most popular 123 | databases that support it. 124 | 125 | Please be aware that, while we strive to address bugs and review PRs quickly, we 126 | make no such guarantees for feature requests. If you need support for a feature, 127 | you will likely need to implement it yourself. Our goal as maintainers is to 128 | facilitate the integration of various features from various contributors, but 129 | not to provide the implementations ourselves, as we simply don't have the 130 | resources. 131 | 132 | [tdop-tutorial]: https://eli.thegreenplace.net/2010/01/02/top-down-operator-precedence-parsing 133 | [`cargo fmt`]: https://github.com/rust-lang/rustfmt#on-the-stable-toolchain 134 | [current issues]: https://github.com/andygrove/sqlparser-rs/issues 135 | [DataFusion]: https://github.com/apache/arrow/tree/master/rust/datafusion 136 | [LocustDB]: https://github.com/cswinter/LocustDB 137 | [Pratt Parser]: https://tdop.github.io/ 138 | [sql-2011-grammar]: https://jakewheat.github.io/sql-overview/sql-2011-foundation-grammar.html 139 | [sql-standard]: https://en.wikipedia.org/wiki/ISO/IEC_9075 140 | -------------------------------------------------------------------------------- /docs/custom_sql_parser.md: -------------------------------------------------------------------------------- 1 | # Writing a Custom SQL Parser 2 | 3 | I have explored many different ways of building this library to make it easy to extend it for custom SQL dialects. Most of my attempts ended in failure but I have now found a workable solution. It is not without downsides but this seems to be the most pragmatic solution. 4 | 5 | The concept is simply to write a new parser that delegates to the ANSI parser so that as much as possible of the core functionality can be re-used. 6 | 7 | I also plan on building in specific support for custom data types, where a lambda function can be parsed to the parser to parse data types. 8 | 9 | For an example of this, see the [DataFusion](https://github.com/datafusion-rs/datafusion) project. 10 | 11 | -------------------------------------------------------------------------------- /examples/cli.rs: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. 12 | 13 | #![warn(clippy::all)] 14 | 15 | use simple_logger; 16 | 17 | ///! A small command-line app to run the parser. 18 | /// Run with `cargo run --example cli` 19 | use std::fs; 20 | 21 | use sqlparser::dialect::*; 22 | use sqlparser::parser::Parser; 23 | 24 | fn main() { 25 | simple_logger::init().unwrap(); 26 | 27 | let filename = std::env::args().nth(1).expect( 28 | "No arguments provided!\n\n\ 29 | Usage: cargo run --example cli FILENAME.sql [--dialectname]", 30 | ); 31 | 32 | let dialect: Box = match std::env::args().nth(2).unwrap_or_default().as_ref() { 33 | "--ansi" => Box::new(AnsiDialect {}), 34 | "--postgres" => Box::new(PostgreSqlDialect {}), 35 | "--ms" => Box::new(MsSqlDialect {}), 36 | "--generic" | "" => Box::new(GenericDialect {}), 37 | s => panic!("Unexpected parameter: {}", s), 38 | }; 39 | 40 | println!("Parsing from file '{}' using {:?}", &filename, dialect); 41 | let contents = fs::read_to_string(&filename) 42 | .unwrap_or_else(|_| panic!("Unable to read the file {}", &filename)); 43 | let without_bom = if contents.chars().nth(0).unwrap() as u64 != 0xfeff { 44 | contents.as_str() 45 | } else { 46 | let mut chars = contents.chars(); 47 | chars.next(); 48 | chars.as_str() 49 | }; 50 | let parse_result = Parser::parse_sql(&*dialect, without_bom.to_owned()); 51 | match parse_result { 52 | Ok(statements) => { 53 | println!( 54 | "Round-trip:\n'{}'", 55 | statements 56 | .iter() 57 | .map(std::string::ToString::to_string) 58 | .collect::>() 59 | .join("\n") 60 | ); 61 | println!("Parse results:\n{:#?}", statements); 62 | std::process::exit(0); 63 | } 64 | Err(e) => { 65 | println!("Error during parsing: {:?}", e); 66 | std::process::exit(1); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /examples/parse_select.rs: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. 12 | 13 | #![warn(clippy::all)] 14 | 15 | use sqlparser::dialect::GenericDialect; 16 | use sqlparser::parser::*; 17 | 18 | fn main() { 19 | let sql = "SELECT a, b, 123, myfunc(b) \ 20 | FROM table_1 \ 21 | WHERE a > b AND b < 100 \ 22 | ORDER BY a DESC, b"; 23 | 24 | let dialect = GenericDialect {}; 25 | 26 | let ast = Parser::parse_sql(&dialect, sql.to_string()).unwrap(); 27 | 28 | println!("AST: {:?}", ast); 29 | } 30 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # We use rustfmt's default settings to format the source code -------------------------------------------------------------------------------- /src/ast/data_type.rs: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. 12 | 13 | use super::ObjectName; 14 | use std::fmt; 15 | 16 | /// SQL data types 17 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 18 | pub enum DataType { 19 | /// Fixed-length character type e.g. CHAR(10) 20 | Char(Option), 21 | /// Variable-length character type e.g. VARCHAR(10) 22 | Varchar(Option), 23 | /// Uuid type 24 | Uuid, 25 | /// Large character object e.g. CLOB(1000) 26 | Clob(u64), 27 | /// Fixed-length binary type e.g. BINARY(10) 28 | Binary(u64), 29 | /// Variable-length binary type e.g. VARBINARY(10) 30 | Varbinary(u64), 31 | /// Large binary object e.g. BLOB(1000) 32 | Blob(u64), 33 | /// Decimal type with optional precision and scale e.g. DECIMAL(10,2) 34 | Decimal(Option, Option), 35 | /// Floating point with optional precision e.g. FLOAT(8) 36 | Float(Option), 37 | /// Small integer 38 | SmallInt, 39 | /// Integer 40 | Int, 41 | /// Big integer 42 | BigInt, 43 | /// Floating point e.g. REAL 44 | Real, 45 | /// Double e.g. DOUBLE PRECISION 46 | Double, 47 | /// Boolean 48 | Boolean, 49 | /// Date 50 | Date, 51 | /// Time without time zone 52 | Time, 53 | /// Time with time zone 54 | TimeTz, 55 | /// Timestamp without time zone 56 | Timestamp, 57 | /// Timestamp with time zone 58 | TimestampTz, 59 | /// Interval 60 | Interval, 61 | /// Regclass used in postgresql serial 62 | Regclass, 63 | /// Text 64 | Text, 65 | /// Bytea 66 | Bytea, 67 | /// Custom type such as enums 68 | Custom(ObjectName), 69 | /// Arrays 70 | Array(Box), 71 | } 72 | 73 | impl fmt::Display for DataType { 74 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 75 | match self { 76 | DataType::Char(size) => format_type_with_optional_length(f, "char", size), 77 | DataType::Varchar(size) => { 78 | format_type_with_optional_length(f, "character varying", size) 79 | } 80 | DataType::Uuid => write!(f, "uuid"), 81 | DataType::Clob(size) => write!(f, "clob({})", size), 82 | DataType::Binary(size) => write!(f, "binary({})", size), 83 | DataType::Varbinary(size) => write!(f, "varbinary({})", size), 84 | DataType::Blob(size) => write!(f, "blob({})", size), 85 | DataType::Decimal(precision, scale) => { 86 | if let Some(scale) = scale { 87 | write!(f, "numeric({},{})", precision.unwrap(), scale) 88 | } else { 89 | format_type_with_optional_length(f, "numeric", precision) 90 | } 91 | } 92 | DataType::Float(size) => format_type_with_optional_length(f, "float", size), 93 | DataType::SmallInt => write!(f, "smallint"), 94 | DataType::Int => write!(f, "int"), 95 | DataType::BigInt => write!(f, "bigint"), 96 | DataType::Real => write!(f, "real"), 97 | DataType::Double => write!(f, "double"), 98 | DataType::Boolean => write!(f, "boolean"), 99 | DataType::Date => write!(f, "date"), 100 | DataType::Time => write!(f, "time"), 101 | DataType::TimeTz => write!(f, "time with time zone"), 102 | DataType::Timestamp => write!(f, "timestamp"), 103 | DataType::TimestampTz => write!(f, "timestamp with time zone"), 104 | DataType::Interval => write!(f, "interval"), 105 | DataType::Regclass => write!(f, "regclass"), 106 | DataType::Text => write!(f, "text"), 107 | DataType::Bytea => write!(f, "bytea"), 108 | DataType::Array(ty) => write!(f, "{}[]", ty), 109 | DataType::Custom(ty) => write!(f, "{}", ty), 110 | } 111 | } 112 | } 113 | 114 | fn format_type_with_optional_length( 115 | f: &mut fmt::Formatter, 116 | sql_type: &'static str, 117 | len: &Option, 118 | ) -> fmt::Result { 119 | write!(f, "{}", sql_type)?; 120 | if let Some(len) = len { 121 | write!(f, "({})", len)?; 122 | } 123 | Ok(()) 124 | } 125 | -------------------------------------------------------------------------------- /src/ast/ddl.rs: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. 12 | 13 | //! AST types specific to CREATE/ALTER variants of [Statement] 14 | //! (commonly referred to as Data Definition Language, or DDL) 15 | use super::{display_comma_separated, DataType, Expr, Ident, ObjectName}; 16 | use std::fmt; 17 | 18 | /// An `ALTER TABLE` (`Statement::AlterTable`) operation 19 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 20 | pub enum AlterTableOperation { 21 | /// `ADD ` 22 | AddConstraint(TableConstraint), 23 | /// TODO: implement `DROP CONSTRAINT ` 24 | DropConstraint { name: Ident }, 25 | } 26 | 27 | impl fmt::Display for AlterTableOperation { 28 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 29 | match self { 30 | AlterTableOperation::AddConstraint(c) => write!(f, "ADD {}", c), 31 | AlterTableOperation::DropConstraint { name } => write!(f, "DROP CONSTRAINT {}", name), 32 | } 33 | } 34 | } 35 | 36 | /// A table-level constraint, specified in a `CREATE TABLE` or an 37 | /// `ALTER TABLE ADD ` statement. 38 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 39 | pub enum TableConstraint { 40 | /// `[ CONSTRAINT ] { PRIMARY KEY | UNIQUE } ()` 41 | Unique { 42 | name: Option, 43 | columns: Vec, 44 | /// Whether this is a `PRIMARY KEY` or just a `UNIQUE` constraint 45 | is_primary: bool, 46 | }, 47 | /// A referential integrity constraint (`[ CONSTRAINT ] FOREIGN KEY () 48 | /// REFERENCES ()`) 49 | ForeignKey { 50 | name: Option, 51 | columns: Vec, 52 | foreign_table: ObjectName, 53 | referred_columns: Vec, 54 | }, 55 | /// `[ CONSTRAINT ] CHECK ()` 56 | Check { 57 | name: Option, 58 | expr: Box, 59 | }, 60 | } 61 | 62 | impl fmt::Display for TableConstraint { 63 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 64 | match self { 65 | TableConstraint::Unique { 66 | name, 67 | columns, 68 | is_primary, 69 | } => write!( 70 | f, 71 | "{}{} ({})", 72 | display_constraint_name(name), 73 | if *is_primary { "PRIMARY KEY" } else { "UNIQUE" }, 74 | display_comma_separated(columns) 75 | ), 76 | TableConstraint::ForeignKey { 77 | name, 78 | columns, 79 | foreign_table, 80 | referred_columns, 81 | } => write!( 82 | f, 83 | "{}FOREIGN KEY ({}) REFERENCES {}({})", 84 | display_constraint_name(name), 85 | display_comma_separated(columns), 86 | foreign_table, 87 | display_comma_separated(referred_columns) 88 | ), 89 | TableConstraint::Check { name, expr } => { 90 | write!(f, "{}CHECK ({})", display_constraint_name(name), expr) 91 | } 92 | } 93 | } 94 | } 95 | 96 | /// SQL column definition 97 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 98 | pub struct ColumnDef { 99 | pub name: Ident, 100 | pub data_type: DataType, 101 | pub collation: Option, 102 | pub options: Vec, 103 | } 104 | 105 | impl fmt::Display for ColumnDef { 106 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 107 | write!(f, "{} {}", self.name, self.data_type)?; 108 | for option in &self.options { 109 | write!(f, " {}", option)?; 110 | } 111 | Ok(()) 112 | } 113 | } 114 | 115 | /// An optionally-named `ColumnOption`: `[ CONSTRAINT ] `. 116 | /// 117 | /// Note that implementations are substantially more permissive than the ANSI 118 | /// specification on what order column options can be presented in, and whether 119 | /// they are allowed to be named. The specification distinguishes between 120 | /// constraints (NOT NULL, UNIQUE, PRIMARY KEY, and CHECK), which can be named 121 | /// and can appear in any order, and other options (DEFAULT, GENERATED), which 122 | /// cannot be named and must appear in a fixed order. PostgreSQL, however, 123 | /// allows preceding any option with `CONSTRAINT `, even those that are 124 | /// not really constraints, like NULL and DEFAULT. MSSQL is less permissive, 125 | /// allowing DEFAULT, UNIQUE, PRIMARY KEY and CHECK to be named, but not NULL or 126 | /// NOT NULL constraints (the last of which is in violation of the spec). 127 | /// 128 | /// For maximum flexibility, we don't distinguish between constraint and 129 | /// non-constraint options, lumping them all together under the umbrella of 130 | /// "column options," and we allow any column option to be named. 131 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 132 | pub struct ColumnOptionDef { 133 | pub name: Option, 134 | pub option: ColumnOption, 135 | } 136 | 137 | impl fmt::Display for ColumnOptionDef { 138 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 139 | write!(f, "{}{}", display_constraint_name(&self.name), self.option) 140 | } 141 | } 142 | 143 | /// `ColumnOption`s are modifiers that follow a column definition in a `CREATE 144 | /// TABLE` statement. 145 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 146 | pub enum ColumnOption { 147 | /// `NULL` 148 | Null, 149 | /// `NOT NULL` 150 | NotNull, 151 | /// `DEFAULT ` 152 | Default(Expr), 153 | /// `{ PRIMARY KEY | UNIQUE }` 154 | Unique { 155 | is_primary: bool, 156 | }, 157 | /// A referential integrity constraint (`[FOREIGN KEY REFERENCES 158 | /// ()`). 159 | ForeignKey { 160 | foreign_table: ObjectName, 161 | referred_columns: Vec, 162 | }, 163 | // `CHECK ()` 164 | Check(Expr), 165 | } 166 | 167 | impl fmt::Display for ColumnOption { 168 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 169 | use ColumnOption::*; 170 | match self { 171 | Null => write!(f, "NULL"), 172 | NotNull => write!(f, "NOT NULL"), 173 | Default(expr) => write!(f, "DEFAULT {}", expr), 174 | Unique { is_primary } => { 175 | write!(f, "{}", if *is_primary { "PRIMARY KEY" } else { "UNIQUE" }) 176 | } 177 | ForeignKey { 178 | foreign_table, 179 | referred_columns, 180 | } => write!( 181 | f, 182 | "REFERENCES {} ({})", 183 | foreign_table, 184 | display_comma_separated(referred_columns) 185 | ), 186 | Check(expr) => write!(f, "CHECK ({})", expr), 187 | } 188 | } 189 | } 190 | 191 | fn display_constraint_name<'a>(name: &'a Option) -> impl fmt::Display + 'a { 192 | struct ConstraintName<'a>(&'a Option); 193 | impl<'a> fmt::Display for ConstraintName<'a> { 194 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 195 | if let Some(name) = self.0 { 196 | write!(f, "CONSTRAINT {} ", name)?; 197 | } 198 | Ok(()) 199 | } 200 | } 201 | ConstraintName(name) 202 | } 203 | -------------------------------------------------------------------------------- /src/ast/operator.rs: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. 12 | 13 | use std::fmt; 14 | 15 | /// Unary operators 16 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 17 | pub enum UnaryOperator { 18 | Plus, 19 | Minus, 20 | Not, 21 | } 22 | 23 | impl fmt::Display for UnaryOperator { 24 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 25 | f.write_str(match self { 26 | UnaryOperator::Plus => "+", 27 | UnaryOperator::Minus => "-", 28 | UnaryOperator::Not => "NOT", 29 | }) 30 | } 31 | } 32 | 33 | /// Binary operators 34 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 35 | pub enum BinaryOperator { 36 | Plus, 37 | Minus, 38 | Multiply, 39 | Divide, 40 | Modulus, 41 | Gt, 42 | Lt, 43 | GtEq, 44 | LtEq, 45 | Eq, 46 | NotEq, 47 | And, 48 | Or, 49 | Like, 50 | NotLike, 51 | JsonGet, 52 | JsonGetAsText, 53 | JsonGetPath, 54 | JsonGetPathAsText, 55 | JsonContainsJson, 56 | JsonContainedInJson, 57 | JsonContainsField, 58 | JsonContainsAnyFields, 59 | JsonContainsAllFields, 60 | JsonConcat, 61 | JsonDeletePath, 62 | JsonContainsPath, 63 | JsonApplyPathPredicate, 64 | } 65 | 66 | impl fmt::Display for BinaryOperator { 67 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 68 | f.write_str(match self { 69 | BinaryOperator::Plus => "+", 70 | BinaryOperator::Minus => "-", 71 | BinaryOperator::Multiply => "*", 72 | BinaryOperator::Divide => "/", 73 | BinaryOperator::Modulus => "%", 74 | BinaryOperator::Gt => ">", 75 | BinaryOperator::Lt => "<", 76 | BinaryOperator::GtEq => ">=", 77 | BinaryOperator::LtEq => "<=", 78 | BinaryOperator::Eq => "=", 79 | BinaryOperator::NotEq => "<>", 80 | BinaryOperator::And => "AND", 81 | BinaryOperator::Or => "OR", 82 | BinaryOperator::Like => "LIKE", 83 | BinaryOperator::NotLike => "NOT LIKE", 84 | BinaryOperator::JsonGet => "->", 85 | BinaryOperator::JsonGetAsText => "->>", 86 | BinaryOperator::JsonGetPath => "#>", 87 | BinaryOperator::JsonGetPathAsText => "#>>", 88 | BinaryOperator::JsonContainsJson => "@>", 89 | BinaryOperator::JsonContainedInJson => "<@", 90 | BinaryOperator::JsonContainsField => "?", 91 | BinaryOperator::JsonContainsAnyFields => "?|", 92 | BinaryOperator::JsonContainsAllFields => "?&", 93 | BinaryOperator::JsonConcat => "||", 94 | BinaryOperator::JsonDeletePath => "#-", 95 | BinaryOperator::JsonContainsPath => "@?", 96 | BinaryOperator::JsonApplyPathPredicate => "@@", 97 | }) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/ast/query.rs: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); 2 | // you may not use this file except in compliance with the License. 3 | // You may obtain a copy of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, 9 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | // See the License for the specific language governing permissions and 11 | // limitations under the License. 12 | 13 | use super::*; 14 | 15 | /// The most complete variant of a `SELECT` query expression, optionally 16 | /// including `WITH`, `UNION` / other set operations, and `ORDER BY`. 17 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 18 | pub struct Query { 19 | /// WITH (common table expressions, or CTEs) 20 | pub ctes: Vec, 21 | /// SELECT or UNION / EXCEPT / INTECEPT 22 | pub body: SetExpr, 23 | /// ORDER BY 24 | pub order_by: Vec, 25 | /// `LIMIT { | ALL }` 26 | pub limit: Option, 27 | /// `OFFSET { ROW | ROWS }` 28 | pub offset: Option, 29 | /// `FETCH { FIRST | NEXT } [ PERCENT ] { ROW | ROWS } | { ONLY | WITH TIES }` 30 | pub fetch: Option, 31 | } 32 | 33 | impl fmt::Display for Query { 34 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 35 | if !self.ctes.is_empty() { 36 | write!(f, "WITH {} ", display_comma_separated(&self.ctes))?; 37 | } 38 | write!(f, "{}", self.body)?; 39 | if !self.order_by.is_empty() { 40 | write!(f, " ORDER BY {}", display_comma_separated(&self.order_by))?; 41 | } 42 | if let Some(ref limit) = self.limit { 43 | write!(f, " LIMIT {}", limit)?; 44 | } 45 | if let Some(ref offset) = self.offset { 46 | write!(f, " OFFSET {} ROWS", offset)?; 47 | } 48 | if let Some(ref fetch) = self.fetch { 49 | write!(f, " {}", fetch)?; 50 | } 51 | Ok(()) 52 | } 53 | } 54 | 55 | /// A node in a tree, representing a "query body" expression, roughly: 56 | /// `SELECT ... [ {UNION|EXCEPT|INTERSECT} SELECT ...]` 57 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 58 | pub enum SetExpr { 59 | /// Restricted SELECT .. FROM .. HAVING (no ORDER BY or set operations) 60 | Select(Box