From 9e582b7e7ba9d24a7fd0abd0d3b1f59b9da0f251 Mon Sep 17 00:00:00 2001 From: Andy Grove Date: Wed, 18 Nov 2026 09:02:29 -0700 Subject: [PATCH 1/2] Add the v2 lexer, parser and AST to the workspace as sqlparser_v2 Adds the lexer, parser and AST of the v2 parser from the 2.0 proposal (#2893) as a separate crate, sqlparser_v2, without its serde, visitor and comment support. sqlparser does not depend on it yet. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 + Cargo.toml | 2 +- sqlparser_v2/.github/workflows/ci.yml | 37 + sqlparser_v2/.gitignore | 2 + sqlparser_v2/Cargo.toml | 37 + sqlparser_v2/LICENSE | 201 + sqlparser_v2/NOTICE | 12 + sqlparser_v2/src/ast.rs | 2863 ++++++++++++++ sqlparser_v2/src/dialect/bigquery.rs | 2564 +++++++++++++ sqlparser_v2/src/dialect/builtin.rs | 392 ++ sqlparser_v2/src/dialect/clickhouse.rs | 2910 ++++++++++++++ sqlparser_v2/src/dialect/databricks.rs | 455 +++ sqlparser_v2/src/dialect/duckdb.rs | 1591 ++++++++ sqlparser_v2/src/dialect/hive.rs | 1226 ++++++ sqlparser_v2/src/dialect/mod.rs | 876 +++++ sqlparser_v2/src/dialect/mssql.rs | 2830 ++++++++++++++ sqlparser_v2/src/dialect/mysql.rs | 1703 +++++++++ sqlparser_v2/src/dialect/mysql/statements.rs | 1491 ++++++++ sqlparser_v2/src/dialect/oracle.rs | 883 +++++ sqlparser_v2/src/dialect/postgres.rs | 2833 ++++++++++++++ sqlparser_v2/src/dialect/postgres/ddl.rs | 3207 ++++++++++++++++ sqlparser_v2/src/dialect/postgres/table.rs | 712 ++++ sqlparser_v2/src/dialect/postgres/utility.rs | 1130 ++++++ sqlparser_v2/src/dialect/redshift.rs | 753 ++++ sqlparser_v2/src/dialect/snowflake.rs | 2585 +++++++++++++ sqlparser_v2/src/dialect/snowflake/ddl.rs | 1405 +++++++ sqlparser_v2/src/dialect/spark.rs | 1378 +++++++ sqlparser_v2/src/dialect/sqlite.rs | 2113 ++++++++++ sqlparser_v2/src/dialect/teradata.rs | 735 ++++ sqlparser_v2/src/display.rs | 3599 ++++++++++++++++++ sqlparser_v2/src/grammar.rs | 271 ++ sqlparser_v2/src/grammar/admin.rs | 440 +++ sqlparser_v2/src/grammar/ddl.rs | 1145 ++++++ sqlparser_v2/src/grammar/dml.rs | 203 + sqlparser_v2/src/grammar/expr.rs | 1435 +++++++ sqlparser_v2/src/grammar/pattern.rs | 241 ++ sqlparser_v2/src/grammar/pipe.rs | 249 ++ sqlparser_v2/src/grammar/pivot.rs | 148 + sqlparser_v2/src/grammar/query.rs | 1226 ++++++ sqlparser_v2/src/grammar/session.rs | 678 ++++ sqlparser_v2/src/grammar/xml.rs | 125 + sqlparser_v2/src/lexer.rs | 392 ++ sqlparser_v2/src/lib.rs | 86 + sqlparser_v2/src/parser.rs | 516 +++ 44 files changed, 47683 insertions(+), 1 deletion(-) create mode 100644 sqlparser_v2/.github/workflows/ci.yml create mode 100644 sqlparser_v2/.gitignore create mode 100644 sqlparser_v2/Cargo.toml create mode 100644 sqlparser_v2/LICENSE create mode 100644 sqlparser_v2/NOTICE create mode 100644 sqlparser_v2/src/ast.rs create mode 100644 sqlparser_v2/src/dialect/bigquery.rs create mode 100644 sqlparser_v2/src/dialect/builtin.rs create mode 100644 sqlparser_v2/src/dialect/clickhouse.rs create mode 100644 sqlparser_v2/src/dialect/databricks.rs create mode 100644 sqlparser_v2/src/dialect/duckdb.rs create mode 100644 sqlparser_v2/src/dialect/hive.rs create mode 100644 sqlparser_v2/src/dialect/mod.rs create mode 100644 sqlparser_v2/src/dialect/mssql.rs create mode 100644 sqlparser_v2/src/dialect/mysql.rs create mode 100644 sqlparser_v2/src/dialect/mysql/statements.rs create mode 100644 sqlparser_v2/src/dialect/oracle.rs create mode 100644 sqlparser_v2/src/dialect/postgres.rs create mode 100644 sqlparser_v2/src/dialect/postgres/ddl.rs create mode 100644 sqlparser_v2/src/dialect/postgres/table.rs create mode 100644 sqlparser_v2/src/dialect/postgres/utility.rs create mode 100644 sqlparser_v2/src/dialect/redshift.rs create mode 100644 sqlparser_v2/src/dialect/snowflake.rs create mode 100644 sqlparser_v2/src/dialect/snowflake/ddl.rs create mode 100644 sqlparser_v2/src/dialect/spark.rs create mode 100644 sqlparser_v2/src/dialect/sqlite.rs create mode 100644 sqlparser_v2/src/dialect/teradata.rs create mode 100644 sqlparser_v2/src/display.rs create mode 100644 sqlparser_v2/src/grammar.rs create mode 100644 sqlparser_v2/src/grammar/admin.rs create mode 100644 sqlparser_v2/src/grammar/ddl.rs create mode 100644 sqlparser_v2/src/grammar/dml.rs create mode 100644 sqlparser_v2/src/grammar/expr.rs create mode 100644 sqlparser_v2/src/grammar/pattern.rs create mode 100644 sqlparser_v2/src/grammar/pipe.rs create mode 100644 sqlparser_v2/src/grammar/pivot.rs create mode 100644 sqlparser_v2/src/grammar/query.rs create mode 100644 sqlparser_v2/src/grammar/session.rs create mode 100644 sqlparser_v2/src/grammar/xml.rs create mode 100644 sqlparser_v2/src/lexer.rs create mode 100644 sqlparser_v2/src/lib.rs create mode 100644 sqlparser_v2/src/parser.rs diff --git a/Cargo.lock b/Cargo.lock index cd4477f97f..df2b32ae9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -666,6 +666,10 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "sqlparser_v2" +version = "2.0.0" + [[package]] name = "stacker" version = "0.1.25" diff --git a/Cargo.toml b/Cargo.toml index 97b4612c3d..2c1cbe50dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,7 @@ should_panic_without_expect = "deny" todo = "deny" [workspace] -members = ["sqlparser_bench"] +members = ["sqlparser_bench", "sqlparser_v2"] [features] default = ["std", "recursive-protection"] diff --git a/sqlparser_v2/.github/workflows/ci.yml b/sqlparser_v2/.github/workflows/ci.yml new file mode 100644 index 0000000000..bc4a0d9e29 --- /dev/null +++ b/sqlparser_v2/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --check + - run: cargo clippy --all-targets -- -D warnings + - run: cargo test + - run: cargo test --release diff --git a/sqlparser_v2/.gitignore b/sqlparser_v2/.gitignore new file mode 100644 index 0000000000..96ef6c0b94 --- /dev/null +++ b/sqlparser_v2/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/sqlparser_v2/Cargo.toml b/sqlparser_v2/Cargo.toml new file mode 100644 index 0000000000..0b2b16996c --- /dev/null +++ b/sqlparser_v2/Cargo.toml @@ -0,0 +1,37 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +[package] +name = "sqlparser_v2" +description = "Extensible SQL Lexer and Parser with composable dialects" +version = "2.0.0" +authors = ["Apache DataFusion "] +documentation = "https://docs.rs/sqlparser_v2/" +keywords = ["ansi", "sql", "lexer", "parser"] +repository = "https://github.com/apache/datafusion-sqlparser-rs" +license = "Apache-2.0" +include = [ + "src/**/*.rs", + "Cargo.toml", + "LICENSE", + "NOTICE", +] +edition = "2024" + +[lib] +name = "sqlparser_v2" +path = "src/lib.rs" diff --git a/sqlparser_v2/LICENSE b/sqlparser_v2/LICENSE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/sqlparser_v2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/sqlparser_v2/NOTICE b/sqlparser_v2/NOTICE new file mode 100644 index 0000000000..225e78af4e --- /dev/null +++ b/sqlparser_v2/NOTICE @@ -0,0 +1,12 @@ +sqlparser + +This product includes software derived from Apache DataFusion sqlparser-rs +(https://github.com/apache/datafusion-sqlparser-rs): tests/corpus/v1.corpus +is generated from its test suite, and the benchmark queries come from its +sqlparser_bench. That project carries the following notice: + +Apache DataFusion sqlparser-rs +Copyright 2024-2026 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/sqlparser_v2/src/ast.rs b/sqlparser_v2/src/ast.rs new file mode 100644 index 0000000000..ff90fba13c --- /dev/null +++ b/sqlparser_v2/src/ast.rs @@ -0,0 +1,2863 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The syntax tree. Every string in it borrows from the SQL text. +//! +//! The tree is generic over an [`AstExt`], which supplies the types stored +//! in the extension slots ([`ExprKind::Ext`] and [`Select::modifiers`]). + +use std::borrow::Cow; +use std::fmt; + +use crate::dialect::AstExt; + +/// A byte range in the SQL text. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Span { + pub start: u32, + pub end: u32, +} + +impl Span { + /// The SQL text this span covers. `sql` must be the text that was parsed. + pub fn text(self, sql: &str) -> &str { + &sql[self.start as usize..self.end as usize] + } + + /// The line and column where the span starts. + pub fn start_location(self, sql: &str) -> Location { + Location::at(sql, self.start) + } + + /// The line and column just after the span's last character. + pub fn end_location(self, sql: &str) -> Location { + Location::at(sql, self.end) + } +} + +/// A position in SQL text, for error messages and editors. Both numbers start at +/// 1, and `column` counts characters rather than bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct Location { + pub line: u32, + pub column: u32, +} + +impl Location { + /// The location of byte `offset` in `sql`, found by scanning from the start. + fn at(sql: &str, offset: u32) -> Self { + let before = &sql[..offset as usize]; + let line_start = before.rfind('\n').map_or(0, |newline| newline + 1); + Self { + line: before.matches('\n').count() as u32 + 1, + column: before[line_start..].chars().count() as u32 + 1, + } + } +} + +/// A node that knows which part of the SQL text it came from. +pub trait Spanned { + /// The node's position, or an empty span if it did not come from the parser. + fn span(&self) -> Span; +} + +/// An identifier. `text` is the source text between any quotes, with escapes +/// left in place; use [`Ident::value`] to resolve them. +#[derive(Debug, Clone)] +pub struct Ident<'a> { + pub text: Cow<'a, str>, + pub quote: Option, + pub span: Span, +} + +impl<'a> DataType<'a> { + /// A column or cast with no type written, in dialects that allow that. + pub fn unspecified(span: Span) -> Self { + Self { + qualifier: Vec::new(), + name: Ident { + text: "".into(), + quote: None, + span, + }, + angle: None, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: ArrayType::None, + } + } + + pub fn is_unspecified(&self) -> bool { + self.name.text.is_empty() + } +} + +impl<'a> Ident<'a> { + /// The identifier's value. Only allocates if it contains an escaped quote. + pub fn value(&self) -> Cow<'a, str> { + lend(&self.text, |text| match self.quote { + Some(quote) => unescape(text, quote), + None => Cow::Borrowed(text), + }) + } +} + +/// Applies `f` to `text`, keeping the result borrowed for `'a` when `text` +/// borrows from the source. Owned text gives an owned result. +fn lend<'a>(text: &Cow<'a, str>, f: impl for<'b> FnOnce(&'b str) -> Cow<'b, str>) -> Cow<'a, str> { + match text { + Cow::Borrowed(text) => f(text), + Cow::Owned(text) => Cow::Owned(f(text).into_owned()), + } +} + +/// Spans are ignored so that trees can be compared by structure. +impl PartialEq for Ident<'_> { + fn eq(&self, other: &Self) -> bool { + self.text == other.text && self.quote == other.quote + } +} + +/// A string literal. `text` is the source text between the quotes, with +/// escapes left in place; use [`StringLiteral::value`] to resolve them. +#[derive(Debug, Clone, PartialEq)] +pub struct StringLiteral<'a> { + pub text: Cow<'a, str>, + /// The quote character, or `$` for text between `$$` markers. + pub quote: char, + /// True if a backslash introduces an escape sequence in this dialect. + pub backslash_escapes: bool, + /// True for a national character string, written `N'text'`. + pub national: bool, + pub prefix: StringPrefix, + /// True if the quotes were tripled, as in `'''text'''`. + pub triple: bool, +} + +/// A letter written directly before a string's opening quote. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum StringPrefix { + #[default] + None, + /// `B'text'` + Byte, + /// `R'text'`, in which backslashes have no meaning. + Raw, + /// `E'text'`, in which a backslash introduces an escape. + Escape, + /// `U&'text'`, in which `\\XXXX` writes a Unicode code point. + Unicode, + /// `B'text'` as a bit string, which holds only `0` and `1`. + Bit, +} + +impl<'a> StringLiteral<'a> { + /// The string's value. Only allocates if it contains an escape. + pub fn value(&self) -> Cow<'a, str> { + lend(&self.text, |text| { + if self.prefix == StringPrefix::Raw || (self.triple && !self.backslash_escapes) { + Cow::Borrowed(text) + } else if self.prefix == StringPrefix::Escape { + // The lexer has checked the escapes; an invalid one is kept as written. + match unescape_escape_string(text, self.quote) { + Ok(value) => value, + Err(_) => Cow::Borrowed(text), + } + } else if self.backslash_escapes && text.contains('\\') { + // Inside triple quotes, a doubled quote is just two quotes. + let quote = if self.triple { '\0' } else { self.quote }; + Cow::Owned(unescape_backslashes(text, quote)) + } else if self.triple { + Cow::Borrowed(text) + } else { + unescape(text, self.quote) + } + }) + } +} + +/// Resolves the escapes of PostgreSQL's `E'text'`: `\b`, `\f`, `\n`, `\r` +/// and `\t`, one to three octal digits, `\x` and one or two hex digits, which +/// write bytes, `\uXXXX` and `\UXXXXXXXX`, which write code points, and a +/// backslash before any other character, which writes that character. Fails if +/// the bytes are not UTF-8, or the string would contain a NUL. +pub fn unescape_escape_string(text: &str, quote: char) -> Result, &'static str> { + if !text.contains('\\') { + return Ok(unescape(text, quote)); + } + let mut value = Vec::with_capacity(text.len()); + let bytes = text.as_bytes(); + let mut i = 0; + // Reads up to `max` digits in `radix` from `bytes[i..]`. + let digits = |i: &mut usize, radix: u32, max: usize| -> Option { + let start = *i; + let mut n = 0u32; + while *i < bytes.len() && *i - start < max { + let Some(d) = char::from(bytes[*i]).to_digit(radix) else { + break; + }; + n = n * radix + d; + *i += 1; + } + (*i > start).then_some(n) + }; + while i < bytes.len() { + let b = bytes[i]; + i += 1; + if char::from(b) == quote && bytes.get(i) == Some(&b) { + i += 1; + value.push(b); + continue; + } + if b != b'\\' { + value.push(b); + continue; + } + let Some(&escaped) = bytes.get(i) else { + return Err("unterminated escape in string"); + }; + i += 1; + match escaped { + b'b' => value.push(8), + b'f' => value.push(12), + b'n' => value.push(b'\n'), + b'r' => value.push(b'\r'), + b't' => value.push(b'\t'), + b'0'..=b'7' => { + i -= 1; + let n = digits(&mut i, 8, 3).unwrap_or(0); + value.push((n & 0xff) as u8); + } + b'x' if bytes.get(i).is_some_and(u8::is_ascii_hexdigit) => { + let n = digits(&mut i, 16, 2).unwrap_or(0); + value.push(n as u8); + } + b'u' | b'U' => { + let len = if escaped == b'u' { 4 } else { 8 }; + let start = i; + let mut code = digits(&mut i, 16, len).filter(|_| i - start == len); + // A UTF-16 surrogate pair is written as two `\u` escapes. + if let Some(high @ 0xD800..=0xDBFF) = code { + code = None; + if bytes.get(i) == Some(&b'\\') && bytes.get(i + 1) == Some(&b'u') { + i += 2; + let start = i; + if let Some(low @ 0xDC00..=0xDFFF) = + digits(&mut i, 16, 4).filter(|_| i - start == 4) + { + code = Some(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)); + } + } + } + let c = code + .and_then(char::from_u32) + .ok_or("invalid Unicode escape in string")?; + value.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()); + } + other => { + // Another character, which may be more than one byte. + value.push(other); + } + } + } + if value.contains(&0) { + return Err("a string cannot contain a NUL character"); + } + String::from_utf8(value) + .map(Cow::Owned) + .map_err(|_| "invalid byte sequence in string") +} + +fn unescape_backslashes(text: &str, quote: char) -> String { + let mut value = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c == quote && chars.peek() == Some("e) { + chars.next(); + value.push(quote); + } else if c != '\\' { + value.push(c); + } else { + match chars.next() { + Some('0') => value.push('\0'), + Some('b') => value.push('\u{8}'), + Some('n') => value.push('\n'), + Some('r') => value.push('\r'), + Some('t') => value.push('\t'), + Some('Z') => value.push('\u{1a}'), + // These keep their backslash so that `LIKE` sees them as literals. + Some(wildcard @ ('%' | '_')) => { + value.push('\\'); + value.push(wildcard); + } + Some(other) => value.push(other), + None => {} + } + } + } + value +} + +fn unescape(text: &str, quote: char) -> Cow<'_, str> { + // A `[name]` identifier escapes its closing bracket. + let quote = if quote == '[' { ']' } else { quote }; + if text.contains(quote) { + let doubled: String = [quote, quote].iter().collect(); + Cow::Owned(text.replace(&doubled, quote.encode_utf8(&mut [0; 4]))) + } else { + Cow::Borrowed(text) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Literal<'a> { + Number(Cow<'a, str>), + String(StringLiteral<'a>), + /// The digits of `X'AB'` or `0xAB`. + HexString(Cow<'a, str>), + /// `$tag$text$tag$`, where `tag` may be empty. + DollarQuoted { + tag: Cow<'a, str>, + text: Cow<'a, str>, + }, + Null, + Boolean(bool), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UnaryOp { + Neg, + Plus, + Not, + /// `!expr`, which means the same as `NOT expr`. + BangNot, + /// `~expr` + BitNot, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BinaryOp<'a> { + Or, + And, + Eq, + NotEq, + Lt, + LtEq, + Gt, + GtEq, + Add, + Sub, + Mul, + Div, + Mod, + /// `||` + StringConcat, + /// `|` + BitOr, + /// `&` + BitAnd, + /// `^` + BitXor, + /// `<<` + ShiftLeft, + /// `>>` + ShiftRight, + /// An operator a dialect adds, rendered as this text. + Named(Cow<'a, str>), +} + +/// The keyword of a quantified comparison. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Quantifier { + Any, + Some, + All, +} + +/// How a cast was written in the source. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CastStyle { + /// `CAST(expr AS ty)` + Function, + /// `TRY_CAST(expr AS ty)` + TryFunction, + /// `SAFE_CAST(expr AS ty)` + SafeFunction, + /// `expr::ty` + DoubleColon, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ExprKind<'a, X: AstExt> { + Ident(Ident<'a>), + Literal(Literal<'a>), + Unary { + op: UnaryOp, + expr: Box>, + }, + Binary { + left: Box>, + op: BinaryOp<'a>, + right: Box>, + }, + Cast { + expr: Box>, + /// Boxed so that the common expressions stay small. + ty: Box>, + style: CastStyle, + }, + /// A bind parameter, as written: `?`, `$1` or `:name`. + Placeholder(Cow<'a, str>), + /// `INTERVAL value unit` + Interval(Box>), + /// A literal introduced by its type: `DATE '2020-01-01'`. + TypedString(Box>), + /// Less common syntax. Boxed so that it adds no size to [`Expr`], and + /// no locals to the derived traits that recurse through every level. + Special(Box>), + /// A qualified name such as `t.a`, with at least two parts. + Compound(ObjectName<'a>), + Function { + name: ObjectName<'a>, + args: Vec>, + /// Boxed so that plain calls do not pay for syntax they do not use. + options: Option>>, + }, + /// A scalar subquery: `(SELECT ...)`. + Subquery(Box>), + /// `EXISTS (SELECT ...)` + Exists(Box>), + /// `expr [NOT] IN (a, b, ...)` + InList { + expr: Box>, + list: Vec>, + negated: bool, + }, + /// `expr [NOT] IN (SELECT ...)` + InSubquery { + expr: Box>, + subquery: Box>, + negated: bool, + }, + /// `expr IS [NOT] test` + Is { + expr: Box>, + test: IsTest<'a, X>, + negated: bool, + }, + /// `expr [NOT] LIKE pattern [ESCAPE escape]` + Like { + expr: Box>, + pattern: Box>, + negated: bool, + kind: LikeKind<'a>, + escape: Option>>, + }, + /// `expr [NOT] BETWEEN low AND high` + Between { + expr: Box>, + low: Box>, + high: Box>, + negated: bool, + }, + Case(Box>), + /// A parenthesized expression. + Nested(Box>), + /// Syntax that only the dialect knows about. + Ext(X::Expr<'a>), +} + +/// An expression, and the source text it covers. +/// +/// `span` is ignored by `==`, like the span of an [`Ident`]. +pub struct Expr<'a, X: AstExt> { + pub kind: ExprKind<'a, X>, + pub span: Span, +} + +impl<'a, X: AstExt> Expr<'a, X> { + pub fn new(kind: ExprKind<'a, X>, span: Span) -> Self { + Self { kind, span } + } +} + +/// A node that did not come from the parser has an empty span. +impl<'a, X: AstExt> From> for Expr<'a, X> { + fn from(kind: ExprKind<'a, X>) -> Self { + Self::new(kind, Span::default()) + } +} + +// Written by hand so that each level of a deep tree adds no stack frames. +impl Clone for Expr<'_, X> { + #[inline(always)] + fn clone(&self) -> Self { + Self { + kind: self.kind.clone(), + span: self.span, + } + } +} + +impl fmt::Debug for Expr<'_, X> { + #[inline(always)] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.kind, f)?; + write!(f, "@{}..{}", self.span.start, self.span.end) + } +} + +impl PartialEq for Expr<'_, X> { + #[inline(always)] + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + } +} + +impl Spanned for Expr<'_, X> { + fn span(&self) -> Span { + self.span + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TypedString<'a> { + pub ty: DataType<'a>, + pub value: StringLiteral<'a>, +} + +/// `INTERVAL value [unit [(precision)] [TO unit [(precision)]]]`. Units are +/// the source text; rendering upper-cases them. +#[derive(Debug, Clone, PartialEq)] +pub struct Interval<'a, X: AstExt> { + pub value: Expr<'a, X>, + pub leading_field: Option>, + pub leading_precision: Option>, + pub last_field: Option>, + pub fractional_seconds_precision: Option>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrimSide { + Both, + Leading, + Trailing, +} + +/// Expressions rare enough to live behind a box. A `field` is the source text +/// of a date or time unit, which rendering upper-cases. +#[derive(Debug, Clone, PartialEq)] +pub enum SpecialExpr<'a, X: AstExt> { + /// `left op ANY (right)`, and likewise for `SOME` and `ALL`. + Quantified { + left: Expr<'a, X>, + op: BinaryOp<'a>, + quantifier: Quantifier, + /// An [`ExprKind::Subquery`], or whatever was in the parentheses. + right: Expr<'a, X>, + }, + /// `(expr).field` + FieldAccess { expr: Expr<'a, X>, field: Ident<'a> }, + /// `ANY (a, b)`, the right side of a `LIKE`. + QuantifiedList { + quantifier: Quantifier, + items: Vec>, + }, + /// `{d '2020-01-01'}` or `{fn f()}`: an ODBC escape sequence. + OdbcEscape { + kind: Cow<'a, str>, + expr: Expr<'a, X>, + }, + /// `expr[lower:upper]` or `expr[lower:upper:step]`, any bound optional. + Slice { + expr: Expr<'a, X>, + lower: Option>, + upper: Option>, + step: Option>, + }, + /// `expr AT TIME ZONE zone` + AtTimeZone { + expr: Expr<'a, X>, + zone: Expr<'a, X>, + }, + /// `expr COLLATE name` + Collate { + expr: Expr<'a, X>, + collation: ObjectName<'a>, + }, + /// `expr[index]` + Subscript { + expr: Expr<'a, X>, + index: Expr<'a, X>, + }, + /// `ARRAY[a, b]` + Array(Vec>), + /// `(a, b)`, with at least two elements. + Tuple(Vec>), + /// `PRIOR expr`, inside `CONNECT BY`. + Prior(Expr<'a, X>), + /// `x -> body` or `(x, y) -> body`. + Lambda { + params: Vec>, + parenthesized: bool, + body: Expr<'a, X>, + }, + /// `CONNECT_BY_ROOT expr` + ConnectByRoot(Expr<'a, X>), + /// `expr (+)`, marking the outer side of a join. + OuterJoinMark(Expr<'a, X>), + /// `EXTRACT(field FROM expr)` + Extract { + field: Cow<'a, str>, + expr: Expr<'a, X>, + }, + /// `CEIL(expr TO field)` or `FLOOR(expr TO field)` + Round { + ceil: bool, + expr: Expr<'a, X>, + field: Cow<'a, str>, + }, + /// `POSITION(needle IN haystack)` + Position { + needle: Expr<'a, X>, + haystack: Expr<'a, X>, + }, + /// `SUBSTRING(expr FROM start FOR length)` + Substring { + /// True if spelled `SUBSTR`. + shorthand: bool, + expr: Expr<'a, X>, + from: Option>, + length: Option>, + }, + /// `TRIM(side what FROM expr)` + Trim { + side: Option, + what: Option>, + expr: Expr<'a, X>, + }, + /// `OVERLAY(expr PLACING what FROM start FOR length)` + Overlay { + expr: Expr<'a, X>, + what: Expr<'a, X>, + from: Expr<'a, X>, + length: Option>, + }, + /// `ROLLUP (...)`, `CUBE (...)` or `GROUPING SETS (...)` in `GROUP BY`. + Grouping { + kind: GroupingKind, + /// Each set's expressions. A set of one is written without parentheses + /// in `ROLLUP` and `CUBE`. + sets: Vec>>, + }, + /// A function called without parentheses, such as `CURRENT_DATE`. Which + /// words these are is up to the dialect: see + /// [`Dialect::is_niladic_function`](crate::dialect::Dialect::is_niladic_function). + Niladic(Ident<'a>), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GroupingKind { + Rollup, + Cube, + Sets, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SelectItemKind<'a, X: AstExt> { + Wildcard, + /// `t.*` + QualifiedWildcard(ObjectName<'a>), + /// A wildcard with options such as `* EXCLUDE (a)`. + WildcardWithOptions { + qualifier: Option>, + options: Box>, + }, + Expr { + expr: Expr<'a, X>, + alias: Option>, + }, + /// `expr AS (a, b)`, for expressions that produce several columns. + ExprWithAliases { + expr: Expr<'a, X>, + aliases: Vec>, + }, +} + +/// An item in a select list, and the source text it covers. +/// +/// `span` is ignored by `==`, like the span of an [`Ident`]. +pub struct SelectItem<'a, X: AstExt> { + pub kind: SelectItemKind<'a, X>, + pub span: Span, +} + +impl<'a, X: AstExt> SelectItem<'a, X> { + pub fn new(kind: SelectItemKind<'a, X>, span: Span) -> Self { + Self { kind, span } + } +} + +/// A node that did not come from the parser has an empty span. +impl<'a, X: AstExt> From> for SelectItem<'a, X> { + fn from(kind: SelectItemKind<'a, X>) -> Self { + Self::new(kind, Span::default()) + } +} + +// Written by hand so that each level of a deep tree adds no stack frames. +impl Clone for SelectItem<'_, X> { + #[inline(always)] + fn clone(&self) -> Self { + Self { + kind: self.kind.clone(), + span: self.span, + } + } +} + +impl fmt::Debug for SelectItem<'_, X> { + #[inline(always)] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.kind, f)?; + write!(f, "@{}..{}", self.span.start, self.span.end) + } +} + +impl PartialEq for SelectItem<'_, X> { + #[inline(always)] + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + } +} + +impl Spanned for SelectItem<'_, X> { + fn span(&self) -> Span { + self.span + } +} + +/// What can follow a `*` in dialects that extend it. +#[derive(Debug, Clone, PartialEq)] +pub struct WildcardOptions<'a, X: AstExt> { + pub ilike: Option>, + pub exclude: Vec>, + /// True if the `EXCLUDE` columns were written in parentheses. + pub exclude_parens: bool, + /// True if `exclude` was written with the keyword `EXCEPT`. + pub except_keyword: bool, + /// `REPLACE (expr AS name, ...)` + pub replace: Vec<(Expr<'a, X>, Ident<'a>)>, + /// `RENAME from AS to` + pub rename: Vec<(Ident<'a>, Ident<'a>)>, + /// True if the `RENAME` pairs were written in parentheses. + pub rename_parens: bool, +} + +/// A possibly qualified name such as `schema.table`. Always has a part. +#[derive(Debug, Clone, PartialEq)] +pub struct ObjectName<'a> { + pub parts: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FunctionArg<'a, X: AstExt> { + /// `*`, as in `COUNT(*)`. + Wildcard, + /// `t.*` + QualifiedWildcard(ObjectName<'a>), + Expr(Expr<'a, X>), + /// `name => value` + Named { + name: Ident<'a>, + value: Expr<'a, X>, + }, + /// A named argument written with another operator, such as `name := value`. + NamedWith { + name: Ident<'a>, + operator: Cow<'a, str>, + value: Expr<'a, X>, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TableFactor<'a, X: AstExt> { + /// A table factor that only one dialect has. + Ext(X::TableFactor<'a>), + Named(ObjectName<'a>), + /// A subquery in `FROM`. + Derived(Box>), + /// `VALUES (...), (...)` used directly as a table. + Values(Vec>>), + /// `(a JOIN b)` + NestedJoin(Box>), + /// A table-valued function. `call` is an [`ExprKind::Function`], or an + /// [`ExprKind::Ext`] for a call a dialect extends. + Function { + call: Box>, + with_ordinality: bool, + }, + /// `LATERAL` before a subquery or function. + Lateral(Box>), + /// A table read as of a version or time: `t VERSION AS OF 1`. + TimeTravel(Box>), + /// A table read as of another point in time: `t AT(TIMESTAMP => x)`. + Versioned { + name: ObjectName<'a>, + /// The calls after the name, each an [`ExprKind::Function`]. + calls: Vec>, + }, + /// `table SAMPLE (10)` + Sampled(Box>), + /// `XMLTABLE(...)` + XmlTable(Box>), + Pivot(Box>), + Unpivot(Box>), + MatchRecognize(Box>), +} + +/// `XMLTABLE([XMLNAMESPACES(...),] row [PASSING ...] COLUMNS ...)` +#[derive(Debug, Clone, PartialEq)] +pub struct XmlTable<'a, X: AstExt> { + pub namespaces: Vec>, + pub row_expression: Expr<'a, X>, + pub passing: Vec>, + pub columns: Vec>, +} + +/// `uri AS name` in `XMLNAMESPACES`. +#[derive(Debug, Clone, PartialEq)] +pub struct XmlNamespace<'a, X: AstExt> { + pub uri: Expr<'a, X>, + pub name: Ident<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct XmlPassingArgument<'a, X: AstExt> { + pub by_value: bool, + pub expr: Expr<'a, X>, + pub alias: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct XmlTableColumn<'a, X: AstExt> { + pub name: Ident<'a>, + pub kind: XmlColumnKind<'a, X>, +} + +/// What an `XMLTABLE` column reads. +#[derive(Debug, Clone, PartialEq)] +pub enum XmlColumnKind<'a, X: AstExt> { + ForOrdinality, + Data { + data_type: Box>, + path: Option>, + default: Option>, + not_null: bool, + }, +} + +/// `name kind AS OF at` +#[derive(Debug, Clone, PartialEq)] +pub struct TimeTravel<'a, X: AstExt> { + pub name: ObjectName<'a>, + /// `TIMESTAMP` or `VERSION`. + pub kind: Cow<'a, str>, + pub at: Expr<'a, X>, +} + +/// `table MATCH_RECOGNIZE(...)` +#[derive(Debug, Clone, PartialEq)] +pub struct MatchRecognize<'a, X: AstExt> { + pub table: TableRef<'a, X>, + pub partition_by: Vec>, + pub order_by: Vec>, + /// `expr AS alias`, each with its alias. + pub measures: Vec<(Expr<'a, X>, Ident<'a>)>, + pub rows_per_match: Option, + pub after_match_skip: Option>, + pub pattern: MatchPattern<'a>, + /// `symbol AS definition` + pub symbols: Vec<(Ident<'a>, Expr<'a, X>)>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RowsPerMatch { + OneRow, + AllRows(Option), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EmptyMatches { + Show, + Omit, + WithUnmatchedRows, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum AfterMatchSkip<'a> { + PastLastRow, + ToNextRow, + ToFirst(Ident<'a>), + ToLast(Ident<'a>), +} + +/// A regular expression over row symbols. +#[derive(Debug, Clone, PartialEq)] +pub enum MatchPattern<'a> { + Symbol(Ident<'a>), + /// `^` + Start, + /// `$` + End, + /// `{- symbol -}` + Exclude(Ident<'a>), + /// `PERMUTE(a, b)` + Permute(Vec>), + /// Patterns in sequence. + Concat(Vec>), + /// `( pattern )` + Group(Box>), + /// `a | b` + Alternation(Vec>), + Repetition { + pattern: Box>, + quantifier: PatternQuantifier<'a>, + /// True if followed by `?`, matching as little as possible. + reluctant: bool, + }, +} + +/// Bounds are the source text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PatternQuantifier<'a> { + /// `*` + ZeroOrMore, + /// `+` + OneOrMore, + /// `?` + AtMostOne, + /// `{n}` + Exactly(Cow<'a, str>), + /// `{n,}` + AtLeast(Cow<'a, str>), + /// `{,m}` + AtMost(Cow<'a, str>), + /// `{n,m}` + Range(Cow<'a, str>, Cow<'a, str>), +} + +/// An expression with an optional alias, as in a `PIVOT` value list. +#[derive(Debug, Clone, PartialEq)] +pub struct ExprWithAlias<'a, X: AstExt> { + pub expr: Expr<'a, X>, + pub alias: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TableSample<'a, X: AstExt> { + pub table: TableRef<'a, X>, + pub sample: SampleClause<'a, X>, +} + +/// What a sample asks for, apart from the table it applies to. +#[derive(Debug, Clone, PartialEq)] +pub struct SampleClause<'a, X: AstExt> { + /// True if written `TABLESAMPLE`, false if `SAMPLE`. + pub long_form: bool, + /// `BERNOULLI`, `ROW`, `SYSTEM` or `BLOCK`. + pub method: Option>, + pub amount: SampleAmount<'a, X>, + pub parenthesized: bool, + pub seed: Option>, + /// The start of the sample: `SAMPLE 0.1 OFFSET 0.5`. + pub offset: Option>>, +} + +/// How much of a table a sample takes. +#[derive(Debug, Clone, PartialEq)] +pub enum SampleAmount<'a, X: AstExt> { + Quantity { + value: Expr<'a, X>, + unit: Option, + }, + /// `BUCKET 3 OUT OF 16 [ON expr]` + Bucket { + bucket: Cow<'a, str>, + total: Cow<'a, str>, + on: Option>>, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SampleUnit { + Rows, + Percent, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SampleSeed<'a> { + /// True if written `REPEATABLE`, false if `SEED`. + pub repeatable: bool, + pub value: Cow<'a, str>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Pivot<'a, X: AstExt> { + pub table: TableRef<'a, X>, + pub clause: PivotClause<'a, X>, +} + +/// `PIVOT(...)`, apart from the table it applies to. +#[derive(Debug, Clone, PartialEq)] +pub struct PivotClause<'a, X: AstExt> { + pub aggregates: Vec>, + /// More than one is written in parentheses. + pub columns: Vec>, + pub source: PivotSource<'a, X>, + pub default_on_null: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum PivotSource<'a, X: AstExt> { + List(Vec>), + /// `ANY [ORDER BY ...]` + Any(Vec>), + Query(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Unpivot<'a, X: AstExt> { + pub table: TableRef<'a, X>, + pub clause: UnpivotClause<'a, X>, +} + +/// `UNPIVOT(...)`, apart from the table it applies to. +#[derive(Debug, Clone, PartialEq)] +pub struct UnpivotClause<'a, X: AstExt> { + /// `Some(true)` for `INCLUDE NULLS`, `Some(false)` for `EXCLUDE NULLS`. + pub include_nulls: Option, + pub value: Expr<'a, X>, + pub name: Ident<'a>, + pub columns: Vec>, +} + +/// The alias of a table in `FROM`. +#[derive(Debug, Clone, PartialEq)] +pub struct TableAlias<'a> { + pub name: Ident<'a>, + /// True if written with `AS`. + pub explicit: bool, + /// Names for the table's columns: `AS t (a, b)`. + pub columns: Vec>, + /// The type of each column, or empty if the columns have none. + pub column_types: Vec>, +} + +#[derive(Debug, Clone)] +pub struct TableRef<'a, X: AstExt> { + pub factor: TableFactor<'a, X>, + pub alias: Option>, + /// Ignored by `==`, like the span of an [`Ident`]. + pub span: Span, +} + +impl PartialEq for TableRef<'_, X> { + fn eq(&self, other: &Self) -> bool { + self.factor == other.factor && self.alias == other.alias + } +} + +impl Spanned for TableRef<'_, X> { + fn span(&self) -> Span { + self.span + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JoinKind<'a> { + /// A join that only one dialect has, holding all of its keywords, such as + /// `"KEEP JOIN"`. + Custom(Cow<'a, str>), + Inner, + Left, + Right, + Full, + Cross, + /// `ASOF JOIN` + AsOf, + /// `SEMI JOIN` + Semi, + /// `LEFT SEMI JOIN` + LeftSemi, + /// `ANTI JOIN` + Anti, + /// `LEFT ANTI JOIN` + LeftAnti, + /// `RIGHT SEMI JOIN` + RightSemi, + /// `RIGHT ANTI JOIN` + RightAnti, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum JoinConstraint<'a, X: AstExt> { + /// A join condition that only one dialect has. + Ext(X::JoinConstraint<'a>), + None, + On(Expr<'a, X>), + Using(Vec>), + /// `NATURAL`, which is written before the join keywords. + Natural, + /// `MATCH_CONDITION (condition)`, for an `ASOF JOIN`, followed by + /// `constraint`: [`JoinConstraint::None`], [`JoinConstraint::On`] or + /// [`JoinConstraint::Using`]. + AsOf { + condition: Expr<'a, X>, + constraint: Box>, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Join<'a, X: AstExt> { + pub kind: JoinKind<'a>, + /// True if the optional `INNER` or `OUTER` keyword was written. + pub spelled_out: bool, + pub table: TableRef<'a, X>, + pub constraint: JoinConstraint<'a, X>, +} + +/// One comma-separated item of a `FROM` clause. +#[derive(Debug, Clone, PartialEq)] +pub struct TableWithJoins<'a, X: AstExt> { + pub relation: TableRef<'a, X>, + pub joins: Vec>, +} + +/// A `WITH` clause. +#[derive(Debug, Clone, PartialEq)] +pub struct With<'a, X: AstExt> { + /// True for `WITH RECURSIVE`. + pub recursive: bool, + pub ctes: Vec>, +} + +/// A common table expression: `name AS (query)`. +#[derive(Debug, Clone, PartialEq)] +pub struct Cte<'a, X: AstExt> { + pub name: Ident<'a>, + /// The column names listed after the name. + pub columns: Vec>, + /// `Some(true)` for `MATERIALIZED`, `Some(false)` for `NOT MATERIALIZED`. + pub materialized: Option, + pub query: Query<'a, X>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OrderByItem<'a, X: AstExt> { + pub expr: Expr<'a, X>, + /// `Some(true)` for `ASC`, `Some(false)` for `DESC`, `None` if unspecified. + pub asc: Option, + /// `Some(true)` for `NULLS FIRST`, `Some(false)` for `NULLS LAST`. + pub nulls_first: Option, + /// The operator in `USING op`, instead of `ASC` or `DESC`. + pub using: Option>>, + /// What a dialect adds after the sort options. + pub ext: X::OrderByItem<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Limit<'a, X: AstExt> { + /// `None` for an `OFFSET` with no `LIMIT`. + pub count: Option>, + pub offset: Option>, + /// The optional word after the offset. + pub offset_rows: OffsetRows, + /// True if written as `LIMIT offset, count`. + pub offset_comma: bool, + /// True for `LIMIT ALL`, in which case `count` is `None`. + pub all: bool, + /// The columns in `LIMIT count BY columns`. + pub by: Vec>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OffsetRows { + None, + Row, + Rows, +} + +/// `FETCH FIRST [quantity [PERCENT]] ROWS {ONLY | WITH TIES}` +#[derive(Debug, Clone, PartialEq)] +pub struct Fetch<'a, X: AstExt> { + pub quantity: Option>, + pub percent: bool, + pub with_ties: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LockType { + Update, + Share, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NonBlock { + Nowait, + SkipLocked, +} + +/// `FOR {UPDATE | SHARE} [OF name] [NOWAIT | SKIP LOCKED]` +#[derive(Debug, Clone, PartialEq)] +pub struct LockClause<'a> { + pub lock_type: LockType, + pub of: Option>, + pub nonblock: Option, +} + +/// A complete query. `WITH`, `ORDER BY` and `LIMIT` apply to the whole body, +/// including every branch of a `UNION`. +#[derive(Debug, Clone, PartialEq)] +pub struct Query<'a, X: AstExt> { + /// Boxed, like other rare syntax, to keep every query small. + pub with: Option>>, + pub body: SetExpr<'a, X>, + pub order_by: Vec>, + /// Spark's `CLUSTER BY`, `DISTRIBUTE BY` and `SORT BY`. + pub distribution: Option>>, + pub limit: Option>>, + /// Boxed, like other rare syntax, to keep every query small. + pub fetch: Option>>, + pub locks: Vec>, + /// Dialect-specific syntax at the end of the query. + pub tail: X::QueryTail<'a>, + /// The `|> ...` steps after everything else, in order. + pub pipes: Vec>, +} + +impl<'a, X: AstExt> Query<'a, X> { + /// The common table expressions of the `WITH` clause, if any. + pub fn ctes(&self) -> &[Cte<'a, X>] { + self.with.as_deref().map_or(&[], |with| &with.ctes) + } +} + +/// One `|> ...` step, which takes the table so far as its input. +#[derive(Debug, Clone, PartialEq)] +pub enum PipeOperator<'a, X: AstExt> { + Select(Vec>), + Extend(Vec>), + Set(Vec>), + Drop(Vec>), + As(Ident<'a>), + Where(Expr<'a, X>), + Limit { + count: Expr<'a, X>, + offset: Option>, + }, + OrderBy(Vec>), + Aggregate { + aggregates: Vec>, + group_by: Vec>, + }, + TableSample(Box>), + Rename(Vec>), + /// `UNION`, `INTERSECT` or `EXCEPT` with parenthesized queries. + SetOperation { + op: SetOperator, + quantifier: SetQuantifier, + by_name: bool, + queries: Vec>, + }, + Call { + function: Expr<'a, X>, + alias: Option>, + }, + Pivot { + clause: Box>, + alias: Option>, + }, + Unpivot { + clause: Box>, + alias: Option>, + }, + Join(Box>), +} + +/// An item of `|> AGGREGATE`, or of its `GROUP BY`. +#[derive(Debug, Clone, PartialEq)] +pub struct PipeAggregate<'a, X: AstExt> { + pub expr: ExprWithAlias<'a, X>, + /// `Some(true)` for `ASC`, `Some(false)` for `DESC`, `None` if unspecified. + pub asc: Option, +} + +/// `name AS new_name` in `|> RENAME`. +#[derive(Debug, Clone, PartialEq)] +pub struct PipeRename<'a> { + pub name: Ident<'a>, + pub new_name: Ident<'a>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SetOperator { + Union, + Except, + Intersect, + /// A synonym for `EXCEPT` in some dialects. + Minus, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SetQuantifier { + None, + All, + Distinct, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SetExpr<'a, X: AstExt> { + Select(Box>), + /// A parenthesized query, which can have its own `ORDER BY` and `LIMIT`. + Query(Box>), + /// `VALUES (a, b), (c, d)` + Values(Vec>>), + /// `VALUES ROW(a, b), ROW(c, d)` + RowValues(Vec>>), + /// `TABLE name`, which selects every column of a table. + Table(ObjectName<'a>), + /// An `INSERT`, `UPDATE` or `DELETE` used as a query, in `WITH`. + Statement(Box>), + SetOperation { + left: Box>, + op: SetOperator, + quantifier: SetQuantifier, + /// True if `BY NAME` followed the quantifier. + by_name: bool, + right: Box>, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GroupByModifier { + Rollup, + Cube, + /// `WITH TOTALS` + Totals, + /// Several modifiers, in the order written. + Chain(Vec), +} + +#[derive(Debug, Clone)] +pub struct Select<'a, X: AstExt> { + /// Dialect-specific syntax directly after `SELECT`. + pub modifiers: X::Select<'a>, + pub quantifier: SetQuantifier, + pub projection: Vec>, + /// `INTO` after the select list. + pub into: Option>>, + pub from: Vec>, + /// `LATERAL VIEW` clauses after `FROM`. + pub lateral_views: Vec>, + /// `PREWHERE condition`, read before `WHERE`. + pub prewhere: Option>>, + pub selection: Option>, + pub connect_by: Vec>, + pub group_by: Vec>, + /// True for `GROUP BY ALL`, in which case `group_by` is empty. + pub group_by_all: bool, + /// `WITH ROLLUP` or `WITH CUBE` after `GROUP BY`. + pub group_by_modifier: Option, + /// `GROUPING SETS (...)` after a `GROUP BY` list, holding an + /// [`SpecialExpr::Grouping`]. + pub grouping_sets: Option>>, + pub having: Option>, + /// `QUALIFY condition`, in dialects that have it. + pub qualify: Option>, + /// `WINDOW name AS (...)` + pub windows: Vec>, + /// True if `FROM` was written before `SELECT`, which can then be left out. + pub from_first: bool, + /// Ignored by `==`, like the span of an [`Ident`]. + pub span: Span, +} + +impl PartialEq for Select<'_, X> { + fn eq(&self, other: &Self) -> bool { + // Destructured so that a new field cannot be left out. + let Select { + modifiers, + quantifier, + projection, + into, + from, + lateral_views, + prewhere, + selection, + connect_by, + group_by, + group_by_all, + group_by_modifier, + grouping_sets, + having, + qualify, + windows, + from_first, + span: _, + } = self; + *modifiers == other.modifiers + && *quantifier == other.quantifier + && *projection == other.projection + && *into == other.into + && *from == other.from + && *lateral_views == other.lateral_views + && *prewhere == other.prewhere + && *selection == other.selection + && *connect_by == other.connect_by + && *group_by == other.group_by + && *group_by_all == other.group_by_all + && *group_by_modifier == other.group_by_modifier + && *grouping_sets == other.grouping_sets + && *having == other.having + && *qualify == other.qualify + && *windows == other.windows + && *from_first == other.from_first + } +} + +impl Spanned for Select<'_, X> { + fn span(&self) -> Span { + self.span + } +} + +impl Spanned for SetExpr<'_, X> { + /// The span of a `SELECT`, or of both sides of a set operation. Other + /// bodies, such as `VALUES`, have an empty span. + fn span(&self) -> Span { + match self { + SetExpr::Select(select) => select.span, + SetExpr::Query(query) => query.body.span(), + SetExpr::Statement(statement) => statement.span, + SetExpr::SetOperation { left, right, .. } => { + let (left, right) = (left.span(), right.span()); + if left == Span::default() || right == Span::default() { + Span::default() + } else { + Span { + start: left.start, + end: right.end, + } + } + } + SetExpr::Values(_) | SetExpr::RowValues(_) | SetExpr::Table(_) => Span::default(), + } + } +} + +/// `INTO [TEMPORARY | TEMP | UNLOGGED] [TABLE] targets` +#[derive(Debug, Clone, PartialEq)] +pub struct SelectInto<'a, X: AstExt> { + /// `TEMPORARY`, `TEMP` or `UNLOGGED`, as written. + pub modifier: Option>, + pub table_keyword: bool, + /// The table or variables, each a name or placeholder. + pub targets: Vec>, +} + +/// `LATERAL VIEW [OUTER] function name [AS] a, b` +#[derive(Debug, Clone, PartialEq)] +pub struct LateralView<'a, X: AstExt> { + pub outer: bool, + pub function: Expr<'a, X>, + pub name: ObjectName<'a>, + pub columns: Vec>, +} + +/// How a query's rows are spread between and ordered within partitions. +#[derive(Debug, Clone, PartialEq)] +pub struct QueryDistribution<'a, X: AstExt> { + pub cluster_by: Vec>, + pub distribute_by: Vec>, + pub sort_by: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ConnectBy<'a, X: AstExt> { + /// `CONNECT BY [NOCYCLE] relationships` + ConnectBy { + nocycle: bool, + relationships: Vec>, + }, + /// `START WITH condition` + StartWith(Expr<'a, X>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct NamedWindow<'a, X: AstExt> { + pub name: Ident<'a>, + pub window: WindowOver<'a, X>, +} + +/// `OUTPUT items [INTO target]` on `INSERT`, `UPDATE`, `DELETE` or `MERGE`. +#[derive(Debug, Clone, PartialEq)] +pub struct OutputClause<'a, X: AstExt> { + pub items: Vec>, + pub into: Option>, +} + +/// A single SQL statement. +#[derive(Debug, Clone, PartialEq)] +pub enum StatementKind<'a, X: AstExt> { + Query(Box>), + Insert(Box>), + Update(Box>), + Delete(Box>), + CreateTable(Box>), + CreateView(Box>), + CreateIndex(Box>), + CreateSchema(Box>), + CreateDatabase(Box>), + Drop(Box>), + Truncate(Box>), + AlterTable(Box>), + Grant(Box>), + Revoke(Box>), + Merge(Box>), + /// `DROP FUNCTION` or `DROP PROCEDURE`. + DropRoutine(Box>), + Show(Box>), + CreateSequence(Box>), + /// `ALTER VIEW name [(columns)] AS query` + AlterView(Box>), + /// `ALTER INDEX name RENAME TO new_name` + AlterIndexRename { + name: ObjectName<'a>, + new_name: ObjectName<'a>, + }, + /// `CREATE ROLE [IF NOT EXISTS] names` + CreateRole(Box>), + /// `ANALYZE [TABLE] [names]` + Analyze(Box>), + Transaction(Box>), + /// `USE name` + Use(Box>), + /// `EXPLAIN`, `DESCRIBE` or `DESC`. + Explain(Box>), + Set(Box>), + Comment(Box>), + /// `CALL name [(args)]`, holding an [`ExprKind::Function`] or [`ExprKind::Compound`]. + Call(Box>), + /// A statement that only the dialect knows about. + Ext(X::Statement<'a>), +} + +/// A statement, and the source text it covers. +/// +/// `span` is ignored by `==`, like the span of an [`Ident`]. +pub struct Statement<'a, X: AstExt> { + pub kind: StatementKind<'a, X>, + pub span: Span, +} + +impl<'a, X: AstExt> Statement<'a, X> { + pub fn new(kind: StatementKind<'a, X>, span: Span) -> Self { + Self { kind, span } + } +} + +/// A node that did not come from the parser has an empty span. +impl<'a, X: AstExt> From> for Statement<'a, X> { + fn from(kind: StatementKind<'a, X>) -> Self { + Self::new(kind, Span::default()) + } +} + +// Written by hand so that each level of a deep tree adds no stack frames. +impl Clone for Statement<'_, X> { + #[inline(always)] + fn clone(&self) -> Self { + Self { + kind: self.kind.clone(), + span: self.span, + } + } +} + +impl fmt::Debug for Statement<'_, X> { + #[inline(always)] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.kind, f)?; + write!(f, "@{}..{}", self.span.start, self.span.end) + } +} + +impl PartialEq for Statement<'_, X> { + #[inline(always)] + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + } +} + +impl Spanned for Statement<'_, X> { + fn span(&self) -> Span { + self.span + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum InsertSource<'a, X: AstExt> { + Values(Vec>>), + /// `VALUES ROW(a, b), ROW(c, d)` + RowValues(Vec>>), + /// `SET a = 1, b = 2` + Set(Vec>), + Query(Box>), + DefaultValues, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Insert<'a, X: AstExt> { + /// Dialect-specific syntax directly after `INSERT`. + pub modifiers: X::Insert<'a>, + /// False if `INTO` was left out, in dialects where it is optional. + pub into: bool, + pub table: ObjectName<'a>, + pub columns: Vec>, + pub output: Option>>, + pub source: InsertSource<'a, X>, + pub returning: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Assignment<'a, X: AstExt> { + pub target: ObjectName<'a>, + pub value: Expr<'a, X>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Update<'a, X: AstExt> { + pub table: TableRef<'a, X>, + /// Joins written before `SET`, in dialects that have them. + pub joins: Vec>, + pub assignments: Vec>, + /// `FROM` tables, after the assignments or before `SET`. + pub from: Vec>, + /// True if `FROM` was written before `SET`. + pub from_before_set: bool, + pub output: Option>>, + pub selection: Option>, + /// `ORDER BY` after the assignments, in dialects that have it. + pub order_by: Vec>, + /// `LIMIT` after the assignments, in dialects that have it. + pub limit: Option>>, + pub returning: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Delete<'a, X: AstExt> { + /// The table deleted from. In a multi-table form, the first of `targets`. + pub table: TableRef<'a, X>, + /// The tables of a multi-table `DELETE`. + pub multi: Option>>, + /// The tables after `USING`, or after `FROM` in a multi-table form. + pub using: Vec>, + pub output: Option>>, + pub selection: Option>, + /// `ORDER BY` after the table, in dialects that have it. + pub order_by: Vec>, + /// `LIMIT` after the table, in dialects that have it. + pub limit: Option>>, + pub returning: Vec>, +} + +/// The tables a multi-table `DELETE` removes rows from. +#[derive(Debug, Clone, PartialEq)] +pub struct MultiTableDelete<'a> { + pub targets: Vec>, + /// True for `DELETE a, b FROM ...`, false for `DELETE FROM a, b USING ...`. + pub from_keyword: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DataType<'a> { + /// The schema of a qualified name: `public.mood` has `public` here. + pub qualifier: Vec>, + pub name: Ident<'a>, + /// The arguments in `ARRAY` and `Array(Int)`. + pub angle: Option>>, + /// The numbers in `decimal(10, 2)`. + pub args: Vec>, + pub suffix: DataTypeSuffix, + pub array: ArrayType<'a>, +} + +/// What is between the angle brackets of a complex type. +#[derive(Debug, Clone, PartialEq)] +pub enum AngleArguments<'a> { + Types(Vec>), + Fields(Vec>), + /// The same, written in parentheses: `Array(Int16)`. + ParenTypes(Vec>), + /// `Tuple(a Int8)`, or a struct definition written in parentheses. + ParenFields(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct StructField<'a> { + /// `None` for a field written as just its type. + pub name: Option>, + /// True if written `name: type`. + pub colon: bool, + pub data_type: DataType<'a>, + pub not_null: bool, + pub comment: Option>, + /// `OPTIONS(key = value, ...)`, which only literal values can fill. + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct StructFieldOption<'a> { + pub key: Ident<'a>, + pub value: Literal<'a>, +} + +/// How a data type is made into an array. Sizes are the source text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ArrayType<'a> { + None, + /// `INT[]` or `INT[3][4]`, with one entry per dimension. + Brackets(Vec>>), + /// `INT ARRAY` or `INT ARRAY[3]`. + Keyword(Option>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ColumnOption<'a, X: AstExt> { + /// `COLLATE name` + Collate(ObjectName<'a>), + /// `IDENTITY` or `AUTOINCREMENT`, with its parameters. + Identity { + autoincrement: bool, + params: Option>, + /// `Some(true)` for `ORDER`, `Some(false)` for `NOORDER`. + order: Option, + }, + /// `[WITH] {MASKING | PROJECTION} POLICY name [USING (columns)]` + Policy { + with: bool, + masking: bool, + name: ObjectName<'a>, + using: Vec>, + }, + /// `[WITH] TAG (name = 'value', ...)` + Tags { + with: bool, + tags: Vec>, + }, + /// `COMMENT 'text'` + Comment(StringLiteral<'a>), + /// `OPTIONS(key = value, ...)` + Options(Vec>), + /// `OPTIONS (name 'value', ...)` + GenericOptions(Vec>), + /// `NULLS DISTINCT` or `NULLS NOT DISTINCT` after `UNIQUE`. + NullsDistinct(bool), + /// `GENERATED ... AS ...` + Generated(Box>), + /// An attribute of the constraint before it, such as `DEFERRABLE`. + Attribute(ConstraintAttribute), + NotNull, + Null, + PrimaryKey, + Unique, + Default(Expr<'a, X>), + /// A keyword a dialect adds before an optional expression, such as + /// `MATERIALIZED expr`. + Keyword { + keyword: Cow<'a, str>, + expr: Option>, + }, + AutoIncrement, + Check(Expr<'a, X>), + References(ForeignKeyRef<'a>), + /// `CONSTRAINT name` before another option. + Named { + name: Ident<'a>, + option: Box>, + }, +} + +/// `key = value`, in an `OPTIONS(...)` list. +#[derive(Debug, Clone, PartialEq)] +pub struct ExprOption<'a, X: AstExt> { + pub name: Ident<'a>, + pub value: Expr<'a, X>, +} + +/// Numbers are the source text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityParams<'a> { + pub seed: Cow<'a, str>, + pub increment: Cow<'a, str>, + /// True if written `START seed INCREMENT step`, false if `(seed, step)`. + pub start_form: bool, +} + +/// A number with the sign it was written with, if any. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignedNumber<'a> { + /// `-`, `+`, or empty. + pub sign: Cow<'a, str>, + pub digits: Cow<'a, str>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SequenceOption<'a> { + Increment { + by: bool, + value: SignedNumber<'a>, + }, + /// `None` for `NO MINVALUE`. + MinValue(Option>), + /// `None` for `NO MAXVALUE`. + MaxValue(Option>), + Start { + with: bool, + value: SignedNumber<'a>, + }, + Cache(SignedNumber<'a>), + /// `false` for `NO CYCLE`. + Cycle(bool), + /// `OWNED BY name`, where the name can be `NONE`. + OwnedBy(ObjectName<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateSequence<'a> { + pub temporary: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub data_type: Option>, + pub options: Vec>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GeneratedWhen { + Always, + ByDefault, + /// `AS (expr)` with `GENERATED` left out. + Omitted, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GeneratedStorage { + Stored, + Virtual, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum GeneratedKind<'a, X: AstExt> { + /// `AS IDENTITY [(options)]` + Identity(Option>>), + /// `AS (expr) [STORED | VIRTUAL]` + Expr { + expr: Expr<'a, X>, + storage: Option, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Generated<'a, X: AstExt> { + pub when: Option, + pub kind: GeneratedKind<'a, X>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConstraintAttribute { + /// `false` for `NOT DEFERRABLE`. + Deferrable(bool), + /// `true` for `INITIALLY DEFERRED`, `false` for `INITIALLY IMMEDIATE`. + InitiallyDeferred(bool), + /// `false` for `NOT ENFORCED`. + Enforced(bool), + NotValid, + NoInherit, +} + +/// A `name = 'value'` tag on an object. +#[derive(Debug, Clone, PartialEq)] +pub struct Tag<'a> { + pub name: ObjectName<'a>, + pub value: StringLiteral<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ColumnDef<'a, X: AstExt> { + pub name: Ident<'a>, + pub data_type: DataType<'a>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TableConstraintKind<'a, X: AstExt> { + PrimaryKey(Vec>), + /// `PRIMARY KEY USING INDEX name` + PrimaryKeyUsingIndex(Ident<'a>), + Unique(Vec>), + /// `UNIQUE USING INDEX name` + UniqueUsingIndex(Ident<'a>), + Check(Expr<'a, X>), + ForeignKey { + /// The name in `FOREIGN KEY name (columns)`, in dialects that have it. + index_name: Option>, + columns: Vec>, + references: ForeignKeyRef<'a>, + }, + /// A key or index that a dialect adds to a table: `KEY name (a, b)`. + Key { + /// All of its keywords, such as `"FULLTEXT INDEX"`. + keyword: Cow<'a, str>, + name: Option>, + /// The method in `USING name`, before the columns. + using: Option>, + columns: Vec>, + options: Vec>, + }, + /// `NOT NULL column` + NotNull(Ident<'a>), + /// `EXCLUDE [USING method] (element, ...)` + Exclude(Box>), +} + +/// Text after the columns of a [`TableConstraintKind::Key`]. +#[derive(Debug, Clone, PartialEq)] +pub enum KeyOption<'a> { + /// `USING name` + Using(Ident<'a>), + /// `COMMENT 'text'` + Comment(StringLiteral<'a>), +} + +/// `EXCLUDE [USING method] (element, ...)`, with its predicate if any. +#[derive(Debug, Clone, PartialEq)] +pub struct ExcludeConstraint<'a, X: AstExt> { + pub using: Option>, + pub elements: Vec>, + /// The `WHERE (condition)`, which follows any `INCLUDE`. + pub predicate: Option>, +} + +/// `column WITH operator`, in an exclusion constraint. +#[derive(Debug, Clone, PartialEq)] +pub struct ExcludeElement<'a, X: AstExt> { + pub column: IndexColumn<'a, X>, + pub operator: ExcludeOperator<'a>, +} + +/// The operator of an exclusion constraint element. +#[derive(Debug, Clone, PartialEq)] +pub enum ExcludeOperator<'a> { + Plain(Cow<'a, str>), + /// `OPERATOR(schema.op)` + Qualified(OperatorName<'a>), +} + +/// `[schema.]operator` +#[derive(Debug, Clone, PartialEq)] +pub struct OperatorName<'a> { + pub schema: Vec>, + pub operator: Cow<'a, str>, +} + +/// `FOR VALUES ...`, or `DEFAULT`, on a partition. +#[derive(Debug, Clone, PartialEq)] +pub enum PartitionBound<'a, X: AstExt> { + Default, + /// `FOR VALUES IN (a, b)` + In(Vec>), + /// `FOR VALUES FROM (a) TO (b)` + Range { + from: Vec>, + to: Vec>, + }, + /// `FOR VALUES WITH (MODULUS m, REMAINDER r)` + Hash { + modulus: Cow<'a, str>, + remainder: Cow<'a, str>, + }, +} + +/// A value in `FOR VALUES FROM (...) TO (...)`. +#[derive(Debug, Clone, PartialEq)] +pub enum RangeBound<'a, X: AstExt> { + MinValue, + MaxValue, + Value(Expr<'a, X>), +} + +/// `name 'value'`, in an `OPTIONS (...)` list. In `ALTER` it may be prefixed +/// with `ADD`, `SET` or `DROP`, and `DROP` takes no value. +#[derive(Debug, Clone, PartialEq)] +pub struct GenericOption<'a> { + pub action: Option>, + pub name: Ident<'a>, + pub value: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TableConstraint<'a, X: AstExt> { + pub name: Option>, + pub kind: TableConstraintKind<'a, X>, + /// The columns in `INCLUDE (a, b)`. + pub include: Vec>, + /// `Some(true)` for `NULLS DISTINCT`, `Some(false)` for `NULLS NOT DISTINCT`. + pub nulls_distinct: Option, + pub attributes: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateTable<'a, X: AstExt> { + pub or_replace: bool, + pub temporary: bool, + pub name: ObjectName<'a>, + pub if_not_exists: bool, + pub columns: Vec>, + pub constraints: Vec>, + /// The query in `CREATE TABLE t AS SELECT ...`. + pub query: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum IsTest<'a, X: AstExt> { + Null, + True, + False, + Unknown, + DistinctFrom(Box>), + /// `IS JSON [type] [{WITH | WITHOUT} UNIQUE [KEYS]]` + Json { + kind: Option, + unique_keys: Option, + }, + /// `IS [form] NORMALIZED` + Normalized(Option), +} + +/// The type an `IS JSON` predicate tests for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JsonPredicateType { + Value, + Array, + Object, + Scalar, +} + +/// `{WITH | WITHOUT} UNIQUE [KEYS]` in an `IS JSON` predicate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct JsonUniqueKeys { + pub with: bool, + /// True if `KEYS` was written. + pub keys: bool, +} + +/// A Unicode normalization form. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NormalForm { + Nfc, + Nfd, + Nfkc, + Nfkd, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LikeKind<'a> { + Like, + ILike, + SimilarTo, + /// A keyword a dialect adds, such as a regular expression match. + Named(Cow<'a, str>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CaseWhen<'a, X: AstExt> { + pub condition: Expr<'a, X>, + pub result: Expr<'a, X>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CaseExpr<'a, X: AstExt> { + pub operand: Option>, + pub branches: Vec>, + pub else_result: Option>, +} + +/// The less common parts of a function call. +#[derive(Debug, Clone, PartialEq)] +pub struct FunctionOptions<'a, X: AstExt> { + /// The first argument list of a parametric call: `f(0.5)(x)`. + pub parameters: Vec>, + pub quantifier: SetQuantifier, + pub order_by: Vec>, + /// `WITHIN GROUP (ORDER BY ...)` + pub within_group: Vec>, + pub filter: Option>, + pub null_treatment: Option, + /// `IGNORE NULLS` or `RESPECT NULLS` inside the parentheses. + pub inner_null_treatment: Option, + /// `SEPARATOR 'text'` after the arguments, in dialects that have it. + pub separator: Option>, + /// `ON OVERFLOW ...` after the arguments, in dialects that have it. + pub on_overflow: Option>>, + pub over: Option>, +} + +/// `ON OVERFLOW ERROR` or `ON OVERFLOW TRUNCATE [filler] {WITH | WITHOUT} COUNT`. +#[derive(Debug, Clone, PartialEq)] +pub enum ListAggOnOverflow<'a, X: AstExt> { + Error, + Truncate { + filler: Option>, + with_count: bool, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NullTreatment { + Ignore, + Respect, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum WindowOver<'a, X: AstExt> { + Named(Ident<'a>), + Spec(WindowSpec<'a, X>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct WindowSpec<'a, X: AstExt> { + /// The window this one extends: `OVER (w ORDER BY a)`. + pub base: Option>, + pub partition_by: Vec>, + pub order_by: Vec>, + pub frame: Option>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameUnits { + Rows, + Range, + Groups, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FrameBound<'a, X: AstExt> { + CurrentRow, + UnboundedPreceding, + UnboundedFollowing, + Preceding(Expr<'a, X>), + Following(Expr<'a, X>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct WindowFrame<'a, X: AstExt> { + pub units: FrameUnits, + pub start: FrameBound<'a, X>, + /// Present in the `BETWEEN start AND end` form. + pub end: Option>, +} + +/// The words that complete a multi-word data type. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DataTypeSuffix { + None, + /// `DOUBLE PRECISION` + Precision, + /// `CHARACTER VARYING` + Varying, + /// `TIMESTAMP WITH TIME ZONE` + WithTimeZone, + /// `TIMESTAMP WITHOUT TIME ZONE` + WithoutTimeZone, + /// The unit range of an `INTERVAL` type, such as `DAY TO HOUR`. Any + /// precision is in the type's arguments. + IntervalFields(IntervalFields), + /// `INT UNSIGNED` + Unsigned, + /// `INT ZEROFILL` + Zerofill, + /// `INT UNSIGNED ZEROFILL` + UnsignedZerofill, + /// `DOUBLE PRECISION UNSIGNED` + PrecisionUnsigned, + /// `SIGNED INTEGER` or `UNSIGNED INTEGER`, with the first word as the name. + Integer, + /// Arguments written with signs or as non-integers, such as `CHAR(-1)`, + /// which render separated by `, `. Holds the sign byte (`+`, `-` or 0) of + /// the first two arguments. + SignedArgs([u8; 2]), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IntervalFields { + Year, + Month, + Day, + Hour, + Minute, + Second, + YearToMonth, + DayToHour, + DayToMinute, + DayToSecond, + HourToMinute, + HourToSecond, + MinuteToSecond, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReferentialAction { + Cascade, + Restrict, + SetNull, + SetDefault, + NoAction, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ForeignKeyRef<'a> { + pub table: ObjectName<'a>, + pub columns: Vec>, + /// `FULL`, `PARTIAL` or `SIMPLE`. + pub match_kind: Option>, + pub on_delete: Option, + pub on_update: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ObjectType<'a> { + Table, + View, + MaterializedView, + Index, + Schema, + Database, + Sequence, + /// A kind of object a dialect adds, rendered as this text. + Named(Cow<'a, str>), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DropBehavior { + Cascade, + Restrict, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DropObject<'a> { + /// True if `TEMPORARY` follows `DROP`. + pub temporary: bool, + pub object_type: ObjectType<'a>, + pub if_exists: bool, + pub names: Vec>, + /// The table in `DROP INDEX i ON t`. + pub on: Option>, + pub behavior: Option, + /// `PURGE`, for dialects that have it. + pub purge: bool, +} + +/// What is granted. Words are the source text; rendering upper-cases them. +#[derive(Debug, Clone, PartialEq)] +pub enum Privileges<'a> { + /// `ALL [PRIVILEGES]` + All { + privileges: bool, + }, + List(Vec>), + /// `[DATABASE] ROLE name` + Role { + database: bool, + name: ObjectName<'a>, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Privilege<'a> { + pub words: Vec>, + /// The columns in `UPDATE (a, b)`. + pub columns: Vec>, +} + +/// What a grant applies to. +#[derive(Debug, Clone, PartialEq)] +pub struct GrantObjects<'a> { + /// The words before the names, such as `ALL TABLES IN SCHEMA`. + pub kind: Vec>, + pub names: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct GrantName<'a> { + pub name: ObjectName<'a>, + /// The argument types of a function. + pub args: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Grantee<'a> { + /// The words before the name, such as `DATABASE ROLE`. + pub kind: Vec>, + pub name: ObjectName<'a>, + /// The host in `user@host`, in dialects that have it. + pub host: Option>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurrentGrants { + Copy, + Revoke, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Grant<'a> { + pub privileges: Privileges<'a>, + /// `None` when granting a role. + pub objects: Option>, + pub grantees: Vec>, + pub with_grant_option: bool, + pub current_grants: Option, + pub as_grantor: Option>, + pub granted_by: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Revoke<'a> { + pub grant_option_for: bool, + pub privileges: Privileges<'a>, + pub objects: GrantObjects<'a>, + pub grantees: Vec>, + pub granted_by: Option>, + pub behavior: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Merge<'a, X: AstExt> { + pub into: bool, + pub table: TableRef<'a, X>, + pub source: TableRef<'a, X>, + pub on: Expr<'a, X>, + pub clauses: Vec>, + pub output: Option>>, + pub returning: Vec>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MergeClauseKind { + Matched, + NotMatched, + NotMatchedBySource, + NotMatchedByTarget, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MergeClause<'a, X: AstExt> { + pub kind: MergeClauseKind, + pub predicate: Option>, + pub action: MergeAction<'a, X>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MergeAction<'a, X: AstExt> { + Update { + /// `None` for `UPDATE SET *`. + assignments: Option>>, + predicate: Option>, + delete_predicate: Option>, + }, + Delete, + Insert { + columns: Vec>, + rows: Vec>>, + predicate: Option>, + }, + /// `INSERT *` + InsertAll, + /// `INSERT [(columns)] ROW` + InsertRow { + columns: Vec>, + predicate: Option>, + }, + DoNothing, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RoutineArg<'a, X: AstExt> { + /// `IN`, `OUT`, `INOUT` or `VARIADIC`. + pub mode: Option>, + pub name: Option>, + pub data_type: DataType<'a>, + /// The default value. The flag is true if written with `=`, false if + /// written with `DEFAULT`. + pub default: Option<(bool, Expr<'a, X>)>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RoutineSignature<'a, X: AstExt> { + pub name: ObjectName<'a>, + /// `None` if the name has no parentheses. + pub args: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DropRoutine<'a, X: AstExt> { + pub procedure: bool, + pub if_exists: bool, + pub routines: Vec>, + pub behavior: Option, +} + +/// `SHOW ...`. What can be shown differs widely between databases, so the +/// object is the words as written. +#[derive(Debug, Clone, PartialEq)] +pub struct Show<'a, X: AstExt> { + /// Words such as `TERSE` and `FULL`. + pub modifiers: Vec>, + /// What is shown, such as `TABLES` or `MATERIALIZED VIEWS`. + pub object: Vec>, + /// The object in `SHOW CREATE TABLE name`. + pub name: Option>, + /// In the order written. + pub clauses: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ShowClause<'a, X: AstExt> { + History, + Like(StringLiteral<'a>), + Where(Expr<'a, X>), + StartsWith(StringLiteral<'a>), + Limit(Expr<'a, X>), + /// A bare string filter: `SHOW CATALOGS 'a*'`. + Pattern(StringLiteral<'a>), + /// `FROM 'value'`, the position to continue listing from. + FromValue(StringLiteral<'a>), + /// `{IN | FROM} [scope] [name]` + Location { + from: bool, + scope: Option>, + name: Option>, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IsolationLevel { + ReadUncommitted, + ReadCommitted, + RepeatableRead, + Serializable, + Snapshot, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TransactionMode { + IsolationLevel(IsolationLevel), + ReadOnly, + ReadWrite, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FinishKind { + Commit, + End, + Rollback, + /// `ABORT`, which is `ROLLBACK` by another name. + Abort, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Transaction<'a> { + Start(Vec), + /// `BEGIN [TRAN | TRANSACTION | WORK]` + Begin(Option>), + Finish { + kind: FinishKind, + chain: bool, + savepoint: Option>, + }, + Savepoint(Ident<'a>), + Release(Ident<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ExplainFormat<'a> { + /// True if written `FORMAT=name`. + pub equals: bool, + pub name: Cow<'a, str>, +} + +/// An option in `EXPLAIN (name value, ...)`. +#[derive(Debug, Clone, PartialEq)] +pub struct ExplainOption<'a> { + pub name: Ident<'a>, + /// `-`, `+`, or empty. + pub sign: Cow<'a, str>, + /// The value's source text. + pub value: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ExplainTarget<'a, X: AstExt> { + Statement(Box>), + Table { + /// True for `DESCRIBE TABLE t`. + table_keyword: bool, + name: ObjectName<'a>, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Explain<'a, X: AstExt> { + /// `EXPLAIN`, `DESCRIBE` or `DESC`. + pub keyword: Cow<'a, str>, + pub options: Vec>, + /// `EXTENDED` or `FORMATTED`. + pub detail: Option>, + pub analyze: bool, + pub verbose: bool, + pub estimate: bool, + pub query_plan: bool, + pub format: Option>, + /// True if the keyword `TABLE` was written before the table's name. + pub target: ExplainTarget<'a, X>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct SetAssignment<'a, X: AstExt> { + pub scope: Option>, + pub name: ObjectName<'a>, + pub value: Expr<'a, X>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SetStatement<'a, X: AstExt> { + Variable { + /// `LOCAL`, `SESSION` or `GLOBAL`. + scope: Option>, + name: ObjectName<'a>, + values: Vec>, + }, + /// Several variables set at once. + Assignments(Vec>), + Role { + scope: Option>, + role: Expr<'a, X>, + }, + Authorization { + scope: Option>, + user: Expr<'a, X>, + }, + TimeZone { + scope: Option>, + value: Expr<'a, X>, + }, + Transaction { + /// True for `SET SESSION CHARACTERISTICS AS TRANSACTION`. + characteristics: bool, + modes: Vec, + snapshot: Option>, + }, + Names { + charset: Expr<'a, X>, + collate: Option>, + }, +} + +/// `COMMENT [IF EXISTS] ON kind name IS comment` +#[derive(Debug, Clone, PartialEq)] +pub struct CommentOn<'a> { + pub if_exists: bool, + pub kind: Vec>, + pub name: ObjectName<'a>, + /// `None` for `IS NULL`. + pub comment: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Truncate<'a> { + pub table_keyword: bool, + pub if_exists: bool, + pub names: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum AlterColumnAction<'a, X: AstExt> { + SetNotNull, + DropNotNull, + SetDefault(Expr<'a, X>), + DropDefault, + /// `TYPE ty`, or `SET DATA TYPE ty` when `set_data` is true. + SetType { + data_type: DataType<'a>, + set_data: bool, + /// The conversion in `USING expr`. + using: Option>, + }, + AddGenerated(Box>), + /// `OPTIONS (...)` + GenericOptions(Vec>), +} + +/// Where `FIRST` or `AFTER name` puts a column. +#[derive(Debug, Clone, PartialEq)] +pub enum ColumnPosition<'a> { + First, + After(Ident<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum AlterTableOp<'a, X: AstExt> { + /// `SET TBLPROPERTIES (key = value, ...)` + SetTblProperties(Vec<(Expr<'a, X>, Expr<'a, X>)>), + /// `ADD [IF NOT EXISTS] PARTITION (...) [PARTITION (...)]...` + AddPartitions { + if_not_exists: bool, + partitions: Vec>>, + }, + /// `DROP [IF EXISTS] PARTITION (...)` + DropPartition { + if_exists: bool, + partition: Vec>, + }, + /// `PARTITION (...) RENAME TO PARTITION (...) [[SET] LOCATION 'path']` + RenamePartition { + old: Vec>, + new: Vec>, + /// The path, and whether `SET` was written before `LOCATION`. + location: Option<(bool, StringLiteral<'a>)>, + }, + AddColumn { + column_keyword: bool, + if_not_exists: bool, + column: ColumnDef<'a, X>, + position: Option>, + }, + /// A fixed phrase, such as `SET LOGGED`. + Phrase(Cow<'a, str>), + /// A fixed phrase and a name, such as `ENABLE TRIGGER name`. + PhraseName { + phrase: Cow<'a, str>, + name: Ident<'a>, + }, + /// A fixed phrase and a qualified name, such as `INHERIT parent`. + PhraseObject { + phrase: Cow<'a, str>, + name: ObjectName<'a>, + }, + /// `ATTACH PARTITION name bound` + AttachPartition { + name: ObjectName<'a>, + bound: PartitionBound<'a, X>, + }, + /// `DETACH PARTITION name [CONCURRENTLY | FINALIZE]` + DetachPartition { + name: ObjectName<'a>, + mode: Option>, + }, + /// `OPTIONS (...)`, in `ALTER FOREIGN TABLE`. + GenericOptions(Vec>), + /// `RESET (name, ...)` + ResetOptions(Vec>), + /// `name [=] value`, such as `ALGORITHM = COPY`. + Setting { + name: Cow<'a, str>, + equals: bool, + value: Cow<'a, str>, + }, + /// `RENAME CONSTRAINT old TO new` + RenameConstraint { + old: Ident<'a>, + new: Ident<'a>, + }, + /// `RENAME AS name` + RenameAs(ObjectName<'a>), + /// `CHANGE COLUMN old definition` + ChangeColumn { + old: Ident<'a>, + column: ColumnDef<'a, X>, + position: Option>, + }, + /// `MODIFY COLUMN definition` + ModifyColumn { + column: ColumnDef<'a, X>, + position: Option>, + }, + /// `SWAP WITH name` + SwapWith(ObjectName<'a>), + /// `CLUSTER BY (exprs)` + ClusterBy(Vec>), + /// `ALTER SORTKEY(columns)` + AlterSortKey(Vec>), + /// `SET (name = value, ...)` + SetOptions(IndexStorage<'a, X>), + DropColumn { + column_keyword: bool, + if_exists: bool, + name: Ident<'a>, + behavior: Option, + }, + /// `DROP [COLUMN] [IF EXISTS] a, b` in dialects that list several columns. + DropColumns { + column_keyword: bool, + if_exists: bool, + names: Vec>, + behavior: Option, + }, + /// `DROP FOREIGN KEY name [behavior]` + DropForeignKey { + name: Ident<'a>, + behavior: Option, + }, + RenameColumn { + old: Ident<'a>, + new: Ident<'a>, + }, + RenameTable(ObjectName<'a>), + AlterColumn { + column_keyword: bool, + name: Ident<'a>, + action: AlterColumnAction<'a, X>, + }, + AddConstraint(TableConstraint<'a, X>), + DropConstraint { + if_exists: bool, + name: Ident<'a>, + behavior: Option, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct AlterTable<'a, X: AstExt> { + pub if_exists: bool, + /// `ALTER TABLE ONLY`, for dialects that have it. + pub only: bool, + pub name: ObjectName<'a>, + pub operations: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateView<'a, X: AstExt> { + pub or_replace: bool, + pub temporary: bool, + pub materialized: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub columns: Vec>, + /// Storage parameters: `WITH (name = value, name)`. + pub with: IndexStorage<'a, X>, + pub query: Box>, + /// True if `WITH NO SCHEMA BINDING` followed the query. + pub no_schema_binding: bool, +} + +/// `CREATE [OR REPLACE] ROLE [IF NOT EXISTS] name, ...` +#[derive(Debug, Clone, PartialEq)] +pub struct CreateRole<'a> { + pub or_replace: bool, + pub if_not_exists: bool, + pub names: Vec>, +} + +/// `ANALYZE [TABLE] [names]` +#[derive(Debug, Clone, PartialEq)] +pub struct Analyze<'a> { + pub table_keyword: bool, + pub names: Vec>, +} + +/// `ALTER VIEW name [(columns)] AS query` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterView<'a, X: AstExt> { + pub name: ObjectName<'a>, + pub columns: Vec>, + pub query: Box>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateIndex<'a, X: AstExt> { + pub unique: bool, + pub concurrently: bool, + /// `CREATE INDEX ASYNC` + pub asynchronous: bool, + pub if_not_exists: bool, + pub name: Option>, + pub using_before_on: Option>, + pub table: ObjectName<'a>, + pub using: Option>, + pub columns: Vec>, + /// `USING` written after the column list. + pub trailing_using: Option>, + pub include: Vec>, + /// `Some(true)` for `NULLS DISTINCT`, `Some(false)` for `NULLS NOT DISTINCT`. + pub nulls_distinct: Option, + /// Storage parameters: `WITH (name = value, name)`. + pub with: IndexStorage<'a, X>, + pub predicate: Option>, + /// `ALGORITHM = value` and `LOCK = value`, in the order written. + pub settings: Vec<(Cow<'a, str>, Cow<'a, str>)>, +} + +/// Modifiers written before an index's name. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct IndexFlags { + pub concurrently: bool, + pub asynchronous: bool, +} + +/// Index storage parameters: each a name and an optional value. +pub type IndexStorage<'a, X> = Vec<(ObjectName<'a>, Option>)>; + +#[derive(Debug, Clone, PartialEq)] +pub struct IndexColumn<'a, X: AstExt> { + pub item: OrderByItem<'a, X>, + pub operator_class: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateSchema<'a> { + pub or_replace: bool, + pub if_not_exists: bool, + /// `None` in `CREATE SCHEMA AUTHORIZATION owner`. + pub name: Option>, + pub authorization: Option>, + /// The schema in `CLONE source`. + pub clone: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateDatabase<'a> { + pub if_not_exists: bool, + pub name: ObjectName<'a>, +} + +/// The modifiers written between `CREATE` and the object type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct CreateFlags { + pub or_replace: bool, + pub temporary: bool, +} diff --git a/sqlparser_v2/src/dialect/bigquery.rs b/sqlparser_v2/src/dialect/bigquery.rs new file mode 100644 index 0000000000..41c181efdb --- /dev/null +++ b/sqlparser_v2/src/dialect/bigquery.rs @@ -0,0 +1,2564 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Google BigQuery. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + AngleArguments, CastStyle, ColumnOption, CreateSchema, CreateTable, CreateView, DataType, + DataTypeSuffix, Delete, Expr, ExprKind, ExprOption, ExprWithAlias, FunctionArg, + FunctionOptions, Ident, Insert, Literal, NullTreatment, ObjectName, OrderByItem, PipeOperator, + Query, SelectItem, SelectItemKind, SetQuantifier, Span, SpecialExpr, Statement, StatementKind, + StringLiteral, StringPrefix, StructField, StructFieldOption, TableFactor, TableRef, + TableWithJoins, TimeTravel, TypedString, WildcardOptions, WindowOver, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinSelect, BuiltinStatement, BuiltinTableFactor}; +use crate::dialect::{Builtin, Dialect, databricks, snowflake, spark}; +use crate::display::{ + Indent, SpaceOrNewline, comma, write_columns, write_create_flags, write_if_not_exists, + write_where_clause, +}; +use crate::grammar::{self, prec}; +use crate::lexer::{self, LexResult, Lexeme, Token, TokenKind, quoted}; +use crate::parser::{InfixRule, Parser}; + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQuery; + +/// Statements only Google BigQuery has. +#[derive(Debug, Clone, PartialEq)] +pub enum BigQueryStatement<'a> { + CreateTable(Box>), + CreateView(Box>), + CreateFunction(Box>), + CreateSnapshot(Box>), + CreateSchema(Box>), + /// `DELETE table [WHERE ...]`, with no `FROM`. + DeleteWithoutFrom(Box>), + /// `INSERT table ...`, with no `INTO`. + InsertWithoutInto(Box>), + ExportData(Box>), + AlterSchema(Box>), + Block(Box>), + Declare(Box>), + /// `RAISE [USING MESSAGE = message]`, or `RAISE value`. + Raise(Option>), + /// `SET (a, b) = (x, y)` + SetTuple { + names: Vec>, + values: Vec>, + }, + ExecuteImmediate(Box>), + /// `ASSERT condition [AS message]` + Assert { + condition: Expr<'a, Builtin>, + message: Option>, + }, +} + +/// `CREATE [OR REPLACE] [TEMPORARY] [EXTERNAL] TABLE` with clauses only +/// BigQuery has. Without them, the statement is the core [`CreateTable`]. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + pub external: bool, + /// `LIKE` or `CLONE`, with its table. + pub source: Option<(Cow<'a, str>, ObjectName<'a>)>, + pub connection: Option>, + pub partition_by: Option>, + pub cluster_by: Vec>, + pub options: Option>>, +} + +/// `CREATE VIEW` with `OPTIONS`. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCreateView<'a> { + pub or_replace: bool, + pub temporary: bool, + pub materialized: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub columns: Vec>, + pub options: Option>>, + pub query: Box>, +} + +/// A view column and any `OPTIONS` written after it. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryViewColumn<'a> { + pub name: Ident<'a>, + pub options: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryFunctionArg<'a> { + pub name: Ident<'a>, + pub data_type: DataType<'a>, +} + +/// `CREATE [OR REPLACE] [TEMPORARY] FUNCTION`. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCreateFunction<'a> { + pub or_replace: bool, + pub temporary: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub args: Vec>, + pub returns: Option>, + /// `Some(false)` for `NOT DETERMINISTIC`. + pub deterministic: Option, + pub language: Option>, + pub remote_connection: Option>, + pub options: Option>>, + /// True if `OPTIONS` was written after the body. + pub options_after_body: bool, + pub body: Option>, +} + +/// `CREATE SNAPSHOT TABLE name CLONE source ...`. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCreateSnapshot<'a> { + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub clone: ObjectName<'a>, + pub for_system_time: Option>, + pub options: Option>>, +} + +/// `CREATE SCHEMA` with `DEFAULT COLLATE` or `OPTIONS`. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCreateSchema<'a> { + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub default_collate: Option>, + pub options: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryExportData<'a> { + pub connection: Option>, + pub options: Vec>, + pub query: Box>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryAlterSchema<'a> { + pub if_exists: bool, + pub name: ObjectName<'a>, + pub operation: BigQueryAlterSchemaOp<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum BigQueryAlterSchemaOp<'a> { + SetDefaultCollate(Expr<'a, Builtin>), + AddReplica { + replica: Ident<'a>, + options: Option>>, + }, + DropReplica(Ident<'a>), + SetOptions(Vec>), +} + +/// `BEGIN ...; [EXCEPTION WHEN name THEN ...;] END` +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryBlock<'a> { + pub statements: Vec>, + /// True if `EXCEPTION` was written, even with no handlers after it. + pub has_exception: bool, + pub handlers: Vec>, +} + +/// `WHEN name [OR name ...] THEN statements`. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryHandler<'a> { + pub conditions: Vec>, + pub statements: Vec>, +} + +/// `DECLARE a, b type [DEFAULT expr]` +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryDeclare<'a> { + pub names: Vec>, + pub data_type: Option>, + pub default: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum BigQueryRaise<'a> { + UsingMessage(Expr<'a, Builtin>), + Value(Expr<'a, Builtin>), +} + +/// `EXECUTE IMMEDIATE expr [INTO a, b] [USING x [AS y], ...]` +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryExecuteImmediate<'a> { + pub query: Expr<'a, Builtin>, + pub into: Vec>, + pub using: Vec>, +} + +/// Expressions only Google BigQuery has. +#[derive(Debug, Clone, PartialEq)] +pub enum BigQueryExpr<'a> { + /// `[a, b]` + Array(Vec>), + Struct(Box>), + /// `expr.*`, with what can follow a wildcard. + Star(Box>), + InUnnest(Box>), + /// `CAST(expr AS ty FORMAT 'f' [AT TIME ZONE 'z'])` + CastFormat(Box>), + /// `EXTRACT(WEEK(weekday) FROM expr)` + ExtractWeek(Box>), + /// A call with clauses inside the parentheses that the core has no place for. + Call(Box>), + /// A call whose single argument is a query: `ARRAY(SELECT ...)`. + SubqueryCall(Box>), +} + +/// `STRUCT<...>(values)` or `STRUCT(values)`. +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryStruct<'a> { + pub ty: Option>, + /// Field names can only be given with `AS` in the typeless form. + pub values: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryStar<'a> { + pub expr: Expr<'a, Builtin>, + pub options: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryInUnnest<'a> { + pub expr: Expr<'a, Builtin>, + pub array: Expr<'a, Builtin>, + pub negated: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCastFormat<'a> { + pub expr: Expr<'a, Builtin>, + pub ty: DataType<'a>, + pub safe: bool, + pub format: StringLiteral<'a>, + pub time_zone: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryExtractWeek<'a> { + pub weekday: Ident<'a>, + pub expr: Expr<'a, Builtin>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryCall<'a> { + pub name: ObjectName<'a>, + pub quantifier: SetQuantifier, + pub args: Vec>, + /// Written inside the parentheses. + pub null_treatment: Option, + pub order_by: Vec>, + pub limit: Option>, + /// `HAVING MAX expr` (true) or `HAVING MIN expr` (false). + pub having: Option<(bool, Expr<'a, Builtin>)>, + pub over: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQuerySubqueryCall<'a> { + pub name: ObjectName<'a>, + pub query: Query<'a, Builtin>, +} + +/// Table factors only Google BigQuery has. +#[derive(Debug, Clone, PartialEq)] +pub enum BigQueryTableFactor<'a> { + /// `UNNEST(...) [AS alias] WITH OFFSET [AS alias]` + WithOffset(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BigQueryWithOffset<'a> { + pub table: TableRef<'a, Builtin>, + pub alias: Option>, +} + +impl<'a> From> for BuiltinExpr<'a> { + fn from(expr: BigQueryExpr<'a>) -> Self { + Self::BigQuery(expr) + } +} + +fn ext<'a>(expr: BigQueryExpr<'a>) -> Expr<'a, Builtin> { + ExprKind::Ext(BuiltinExpr::BigQuery(expr)).into() +} + +fn statement<'a>(statement: BigQueryStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::BigQuery(statement)).into() +} + +#[inline] +fn is_name_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} + +/// Lexes text in tripled quotes, starting at offset `start` of `rest`. +fn triple_quoted(rest: &str, start: usize, quote: u8, backslash: bool) -> LexResult { + let bytes = rest.as_bytes(); + let mut i = start + 3; + while i + 2 < bytes.len() { + if backslash && bytes[i] == b'\\' { + i += 2; + } else if bytes[i..i + 3] == [quote, quote, quote] { + return Ok(Lexeme { + kind: TokenKind::String, + len: i + 3, + }); + } else { + i += 1; + } + } + Err("unterminated quoted text") +} + +/// Lexes a string whose opening quote is at offset `start` of `rest`, leaving +/// any prefix before it in the token. +fn string_after(rest: &str, start: usize, backslash: bool) -> LexResult { + let bytes = rest.as_bytes(); + let quote = bytes[start]; + if bytes.get(start + 1) == Some("e) && bytes.get(start + 2) == Some("e) { + return triple_quoted(rest, start, quote, backslash); + } + let lex = if backslash { + lexer::quoted_with_backslash + } else { + quoted + }; + lex(&rest[start..], TokenKind::String).map(|lexeme| Lexeme { + kind: TokenKind::String, + len: start + lexeme.len, + }) +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) + }; + let bytes = rest.as_bytes(); + match bytes { + [b'`', ..] => Some(quoted(rest, TokenKind::QuotedIdent)), + [b'\'' | b'"', ..] => Some(string_after(rest, 0, true)), + [b'b' | b'B', b'\'' | b'"', ..] => Some(string_after(rest, 1, true)), + [b'r' | b'R', b'\'' | b'"', ..] => Some(string_after(rest, 1, false)), + // `@name` and `@@name` are variables, read as names. + [b'@', ..] => { + let ats = bytes.iter().take_while(|b| **b == b'@').count(); + let len = bytes[ats..] + .iter() + .take_while(|b| is_name_byte(**b)) + .count(); + (len > 0).then_some(Ok(Lexeme { + kind: TokenKind::Word, + len: ats + len, + })) + } + [b'|', b'>', ..] => op(2), + // Type arguments close one at a time, as in `ARRAY>`. + [b'>', b'>', ..] => op(1), + [b':', next, ..] if !next.is_ascii_alphanumeric() && *next != b'_' && *next != b':' => { + op(1) + } + [b, ..] if !b.is_ascii() => Some(Err("unexpected character")), + [b, ..] if b.is_ascii_alphabetic() || *b == b'_' => { + let len = bytes.iter().take_while(|b| is_name_byte(**b)).count(); + if bytes.get(len).is_some_and(|b| !b.is_ascii()) { + return Some(Err("unexpected character")); + } + None + } + _ => None, + } +} + +/// Parses the tripled or prefixed strings that [`lex_token`] accepts. +pub fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + let text = token.text; + let (prefix, body) = match text.as_bytes()[0] { + b'b' | b'B' => (StringPrefix::Byte, &text[1..]), + b'r' | b'R' => (StringPrefix::Raw, &text[1..]), + _ => (StringPrefix::None, text), + }; + let quote = char::from(body.as_bytes()[0]); + let triple = body.len() >= 6 + && body.as_bytes()[1] == body.as_bytes()[0] + && body.as_bytes()[2] == body.as_bytes()[0]; + let len = if triple { 3 } else { 1 }; + StringLiteral { + national: false, + text: Cow::Borrowed(&body[len..body.len() - len]), + quote, + backslash_escapes: prefix != StringPrefix::Raw, + prefix, + triple, + } +} + +/// Words that cannot be a table alias without `AS`. +const RESERVED_FOR_TABLE_ALIAS: [&str; 59] = [ + "WITH", + "EXPLAIN", + "ANALYZE", + "SELECT", + "WHERE", + "GROUP", + "SORT", + "HAVING", + "ORDER", + "PIVOT", + "UNPIVOT", + "TOP", + "LATERAL", + "VIEW", + "LIMIT", + "OFFSET", + "FETCH", + "UNION", + "EXCEPT", + "INTERSECT", + "MINUS", + "ON", + "JOIN", + "INNER", + "CROSS", + "FULL", + "LEFT", + "RIGHT", + "NATURAL", + "USING", + "CLUSTER", + "DISTRIBUTE", + "GLOBAL", + "ANTI", + "SEMI", + "RETURNING", + "OUTPUT", + "ASOF", + "MATCH_CONDITION", + "OUTER", + "SET", + "QUALIFY", + "WINDOW", + "END", + "FOR", + "PARTITION", + "ARRAY", + "PREWHERE", + "SETTINGS", + "FORMAT", + "START", + "CONNECT", + "MATCH_RECOGNIZE", + "SAMPLE", + "TABLESAMPLE", + "FROM", + "OPEN", + "AS", + "INTO", +]; + +/// Words that cannot be a column alias without `AS`. +const RESERVED_FOR_COLUMN_ALIAS: [&str; 15] = [ + "WITH", + "SELECT", + "WHERE", + "GROUP", + "HAVING", + "ORDER", + "LATERAL", + "LIMIT", + "FETCH", + "UNION", + "EXCEPT", + "INTERSECT", + "FROM", + "INTO", + "END", +]; + +fn is_reserved_for_column_alias(word: &str) -> bool { + RESERVED_FOR_COLUMN_ALIAS + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) +} + +fn is_name(token: Token<'_>) -> bool { + matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +/// An identifier written as a string: `'name'`, in a place a name is expected. +fn ident_from_string(token: Token<'_>) -> Ident<'_> { + let literal = string_literal(token); + Ident { + text: literal.text, + quote: Some(literal.quote), + span: token.span, + } +} + +/// Parses a name that can also be written as a string. +fn parse_name_or_string<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::String { + p.advance(); + return Ok(ident_from_string(token)); + } + p.parse_name_part() +} + +/// Parses a part of a name after a dot, which can be written as a string. +fn parse_name_or_string_part<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::String { + p.advance(); + return Ok(ident_from_string(token)); + } + grammar::parse_name_part(p) +} + +fn expect_adjacent<'a, D: Dialect>(p: &Parser<'a, D>, end: u32) -> PResult<()> { + if p.peek().span.start == end { + Ok(()) + } else { + Err(p.expected("continuation of hyphenated identifier")) + } +} + +/// Parses one part of a table name, which can hold hyphens when unquoted: +/// `my-project`. +fn parse_table_name_part<'a, D: Dialect>( + p: &mut Parser<'a, D>, + first_part: bool, +) -> PResult> { + if p.peek().kind == TokenKind::String { + return parse_name_or_string(p); + } + if p.peek().kind != TokenKind::Word { + return if first_part { + p.parse_ident() + } else { + p.parse_name_part() + }; + } + let first = if first_part { + p.parse_ident()? + } else { + p.parse_name_part()? + }; + let (start, mut end) = (first.span.start, first.span.end); + while p.at_op("-") && p.peek().span.start == end { + end = p.advance().span.end; + expect_adjacent(p, end)?; + let token = p.peek(); + let continues = token.kind == TokenKind::Word + || (token.kind == TokenKind::Number && token.text.bytes().all(|b| b.is_ascii_digit())); + if !continues { + return Err(p.expected("continuation of hyphenated identifier")); + } + end = p.advance().span.end; + } + if end == first.span.end { + return Ok(first); + } + let span = Span { start, end }; + Ok(Ident { + text: p.text(span).into(), + quote: None, + span, + }) +} + +/// Parses a table's name, splitting quoted parts on the dots inside them. +pub fn parse_table_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut parts = vec![parse_table_name_part(p, true)?]; + while p.eat_op(".") { + parts.push(parse_table_name_part(p, false)?); + } + if parts.iter().any(|part| part.text.contains('.')) { + parts = parts + .into_iter() + .flat_map(|part| { + let pieces: Vec> = match part.text { + Cow::Borrowed(text) => text.split('.').map(Cow::Borrowed).collect(), + Cow::Owned(text) => text.split('.').map(|t| Cow::Owned(t.to_owned())).collect(), + }; + pieces.into_iter().map(move |text| Ident { + text, + quote: part.quote, + span: part.span, + }) + }) + .collect(); + } + Ok(ObjectName { parts }) +} + +fn parse_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_name_part()?; + p.expect_op("=")?; + let value = p.parse_expr()?; + Ok(ExprOption { name, value }) +} + +/// Parses `(key = value, ...)`, which can be empty only if `allow_empty`. +fn parse_option_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, + allow_empty: bool, +) -> PResult>> { + p.expect_op("(")?; + if allow_empty && p.eat_op(")") { + return Ok(Vec::new()); + } + let options = p.parse_comma_separated(parse_option)?; + p.expect_op(")")?; + Ok(options) +} + +/// Parses `OPTIONS(...)` if it is here. +fn parse_optional_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if !(p.at_keyword("OPTIONS") && p.peek_nth(1).is_op("(")) { + return Ok(None); + } + p.advance(); + parse_option_list(p, true).map(Some) +} + +/// Parses a column's `OPTIONS(...)`, and otherwise the core's column options. +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if let Some(options) = parse_optional_options(p)? { + return Ok(Some(ColumnOption::Options(options))); + } + grammar::parse_column_option(p) +} + +/// Parses the elements of a column list, which can end with a comma. +fn parse_column_elements<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("(")?; + let mut columns = Vec::new(); + let mut constraints = Vec::new(); + if p.eat_op(")") { + return Ok((columns, constraints)); + } + loop { + if let Some(constraint) = D::parse_table_constraint(p)? { + constraints.push(constraint); + } else { + columns.push(D::parse_column_def(p)?); + } + if !p.eat_op(",") || p.at_op(")") { + break; + } + } + p.expect_op(")")?; + Ok((columns, constraints)) +} + +/// Parses a data type, in which `STRUCT<...>` and `ARRAY<...>` nest. +pub fn parse_data_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + // `ANY TYPE`, the type of a templated function parameter. + if name.quote.is_none() && name.text.eq_ignore_ascii_case("ANY") && p.at_keyword("TYPE") { + p.advance(); + return Ok(DataType { + qualifier: Vec::new(), + name: Ident { + text: "ANY TYPE".into(), + quote: None, + span: name.span, + }, + angle: None, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: crate::ast::ArrayType::None, + }); + } + let mut data_type = grammar::parse_data_type_after_name(p, name.clone())?; + let is_array = name.quote.is_none() && name.text.eq_ignore_ascii_case("ARRAY"); + let is_struct = name.quote.is_none() && name.text.eq_ignore_ascii_case("STRUCT"); + if is_array && !p.at_op("<") { + return Err(p.expected("< after ARRAY")); + } + if (is_array || is_struct) && p.at_op("<") { + p.advance(); + let arguments = if is_struct { + AngleArguments::Fields(p.parse_comma_separated(parse_struct_field)?) + } else { + AngleArguments::Types(vec![p.nested(D::parse_data_type)?]) + }; + p.expect_angle_close()?; + data_type.angle = Some(Box::new(arguments)); + } + Ok(data_type) +} + +/// True if a struct field's name comes before its type. +fn at_named_field<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let (first, second) = (p.peek(), p.peek_nth(1)); + if !is_name(first) { + return false; + } + if second.is_word("OPTIONS") && p.peek_nth(2).is_op("(") { + return false; + } + is_name(second) + || second.is_op(":") + || (second.kind == TokenKind::Placeholder && second.text.starts_with(':')) +} + +fn parse_struct_field<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let named = at_named_field(p); + let name = if named { + Some(p.parse_name_part()?) + } else { + None + }; + let token = p.peek(); + // With no space, the lexer reads `:INT` as a parameter. + // A colon is an accepted spelling, which is not kept: `x: INT` renders as `x INT`. + if named { + p.eat_op(":"); + } + let data_type = if named && token.kind == TokenKind::Placeholder && token.text.starts_with(':') + { + p.advance(); + let type_name = Ident { + text: Cow::Borrowed(&token.text[1..]), + quote: None, + span: Span { + start: token.span.start + 1, + end: token.span.end, + }, + }; + p.nested(|p| grammar::parse_data_type_after_name(p, type_name))? + } else { + p.nested(D::parse_data_type)? + }; + let options = parse_struct_field_options(p)?; + Ok(StructField { + not_null: false, + name, + colon: false, + data_type, + comment: None, + options, + }) +} + +/// Parses `OPTIONS(key = literal, ...)` on a struct field. +fn parse_struct_field_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !(p.at_keyword("OPTIONS") && p.peek_nth(1).is_op("(")) { + return Ok(Vec::new()); + } + p.advance(); + p.advance(); + if p.eat_op(")") { + return Ok(Vec::new()); + } + let options = p.parse_comma_separated(|p| { + let key = p.parse_name_part()?; + p.expect_op("=")?; + let value = parse_field_option_value(p)?; + Ok(StructFieldOption { key, value }) + })?; + p.expect_op(")")?; + Ok(options) +} + +fn parse_field_option_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + let literal = match token.kind { + TokenKind::String => Literal::String(D::string_literal(token)), + TokenKind::Number => Literal::Number(token.text.into()), + TokenKind::Word if token.is_word("TRUE") => Literal::Boolean(true), + TokenKind::Word if token.is_word("FALSE") => Literal::Boolean(false), + TokenKind::Word if token.is_word("NULL") => Literal::Null, + _ => return Err(p.expected("a literal option value")), + }; + p.advance(); + Ok(literal) +} + +/// Parses `(arg type, ...)` after a function's name. +fn parse_function_args<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + if p.eat_op(")") { + return Ok(Vec::new()); + } + let args = p.parse_comma_separated(|p| { + let name = parse_name_or_string_part(p)?; + let data_type = D::parse_data_type(p)?; + Ok(BigQueryFunctionArg { name, data_type }) + })?; + p.expect_op(")")?; + Ok(args) +} + +fn parse_create_flags<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<(bool, bool)> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + Ok((or_replace, temporary)) +} + +fn parse_create_function<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let (or_replace, temporary) = parse_create_flags(p)?; + p.expect_keyword("FUNCTION")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let args = parse_function_args(p)?; + let returns = if p.eat_keyword("RETURNS") { + Some(D::parse_data_type(p)?) + } else { + None + }; + let deterministic = if p.eat_keyword("DETERMINISTIC") { + Some(true) + } else if p.at_keyword("NOT") && p.peek_nth(1).is_word("DETERMINISTIC") { + p.advance(); + p.advance(); + Some(false) + } else { + None + }; + let language = if p.eat_keyword("LANGUAGE") { + Some(p.parse_ident()?) + } else { + None + }; + let remote_connection = if p.at_keyword("REMOTE") { + p.advance(); + p.expect_keyword("WITH")?; + p.expect_keyword("CONNECTION")?; + Some(grammar::parse_object_name(p)?) + } else { + None + }; + let mut options = parse_optional_options(p)?; + let mut options_after_body = false; + let body = if remote_connection.is_none() { + p.expect_keyword("AS")?; + let body = p.parse_expr()?; + if options.is_none() { + options = parse_optional_options(p)?; + options_after_body = options.is_some(); + } + Some(body) + } else { + None + }; + Ok(BigQueryCreateFunction { + or_replace, + temporary, + if_not_exists, + name, + args, + returns, + deterministic, + language, + remote_connection, + options, + options_after_body, + body, + }) +} + +fn parse_create_snapshot<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SNAPSHOT")?; + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_table_name(p)?; + p.expect_keyword("CLONE")?; + let clone = parse_table_name(p)?; + let for_system_time = if at_system_time(p) { + consume_system_time(p); + Some(p.parse_expr()?) + } else { + None + }; + let options = parse_optional_options(p)?; + Ok(BigQueryCreateSnapshot { + if_not_exists, + name, + clone, + for_system_time, + options, + }) +} + +fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let (or_replace, temporary) = parse_create_flags(p)?; + if p.at_keyword("SNAPSHOT") { + let snapshot = parse_create_snapshot(p)?; + return Ok(statement(BigQueryStatement::CreateSnapshot(Box::new( + snapshot, + )))); + } + let external = p.eat_keyword("EXTERNAL"); + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_table_name(p)?; + let source = ["LIKE", "CLONE"] + .into_iter() + .find(|keyword| p.at_keyword(keyword)); + let source = match source { + Some(keyword) => { + p.advance(); + Some((keyword, parse_table_name(p)?)) + } + None => None, + }; + let (columns, constraints) = if p.at_op("(") { + parse_column_elements(p)? + } else { + (Vec::new(), Vec::new()) + }; + let connection = if external && p.at_keyword("WITH") && p.peek_nth(1).is_word("CONNECTION") { + p.advance(); + p.advance(); + Some(grammar::parse_object_name(p)?) + } else { + None + }; + let partition_by = if p.at_keyword("PARTITION") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + Some(p.parse_expr()?) + } else { + None + }; + let cluster_by = if p.at_keyword("CLUSTER") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + let options = parse_optional_options(p)?; + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + let plain = !external + && source.is_none() + && connection.is_none() + && partition_by.is_none() + && cluster_by.is_empty() + && options.is_none(); + if plain && columns.is_empty() && query.is_none() { + return Err(p.expected("column definitions, table clauses or AS")); + } + let table = CreateTable { + or_replace, + temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + if plain { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + Ok(statement(BigQueryStatement::CreateTable(Box::new( + BigQueryCreateTable { + table, + external, + source: source.map(|(kind, name)| (kind.into(), name)), + connection, + partition_by, + cluster_by, + options, + }, + )))) +} + +fn parse_view_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let options = parse_optional_options(p)?; + Ok(BigQueryViewColumn { name, options }) +} + +fn parse_create_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let (or_replace, temporary) = parse_create_flags(p)?; + let materialized = p.eat_keyword("MATERIALIZED"); + p.expect_keyword("VIEW")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_table_name(p)?; + let columns = if p.eat_op("(") { + if p.eat_op(")") { + Vec::new() + } else { + let columns = grammar::parse_list_with_trailing_comma(p, parse_view_column)?; + p.expect_op(")")?; + columns + } + } else { + Vec::new() + }; + let options = parse_optional_options(p)?; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + let plain = options.is_none() && columns.iter().all(|column| column.options.is_none()); + if plain { + return Ok(StatementKind::CreateView(Box::new(CreateView { + or_replace, + temporary, + materialized, + if_not_exists, + name, + columns: columns.into_iter().map(|column| column.name).collect(), + with: Vec::new(), + query, + no_schema_binding: false, + })) + .into()); + } + Ok(statement(BigQueryStatement::CreateView(Box::new( + BigQueryCreateView { + or_replace, + temporary, + materialized, + if_not_exists, + name, + columns, + options, + query, + }, + )))) +} + +fn parse_create_schema<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + p.expect_keyword("SCHEMA")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_table_name(p)?; + let default_collate = if p.at_keyword("DEFAULT") { + p.advance(); + p.expect_keyword("COLLATE")?; + Some(p.parse_expr()?) + } else { + None + }; + let options = parse_optional_options(p)?; + if default_collate.is_none() && options.is_none() { + return Ok(StatementKind::CreateSchema(Box::new(CreateSchema { + or_replace: false, + if_not_exists, + name: Some(name), + authorization: None, + clone: None, + })) + .into()); + } + Ok(statement(BigQueryStatement::CreateSchema(Box::new( + BigQueryCreateSchema { + if_not_exists, + name, + default_collate, + options, + }, + )))) +} + +/// Parses `CREATE`, handling BigQuery's tables, views and functions. +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + if p.peek_nth(n).is_word("TEMPORARY") || p.peek_nth(n).is_word("TEMP") { + n += 1; + } + let object = p.peek_nth(n); + if object.is_word("FUNCTION") { + let function = parse_create_function(p)?; + return Ok(statement(BigQueryStatement::CreateFunction(Box::new( + function, + )))); + } + if object.is_word("TABLE") || object.is_word("EXTERNAL") || object.is_word("SNAPSHOT") { + return parse_create_table(p); + } + if object.is_word("VIEW") || object.is_word("MATERIALIZED") { + return parse_create_view(p); + } + if n == 1 && object.is_word("SCHEMA") { + return parse_create_schema(p); + } + grammar::parse_create(p) +} + +/// Parses `(a, b)` and an optional value list after `SET`. +fn parse_set_tuple<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SET")?; + let names = grammar::parse_ident_list(p)?; + if !p.eat_op("=") && !p.eat_keyword("TO") { + return Err(p.expected("= or TO")); + } + p.expect_op("(")?; + let values = p.parse_comma_separated(|p| { + if grammar::query_starts_at(p, 0) { + p.spanned_expr(|p| { + let query = p.nested(D::parse_query)?; + Ok(ExprKind::Subquery(Box::new(query)).into()) + }) + } else { + p.parse_expr() + } + })?; + p.expect_op(")")?; + Ok(BigQueryStatement::SetTuple { names, values }) +} + +/// Parses statements up to one of `terminators`, each ended by a semicolon. +fn parse_statement_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, + terminators: &[&str], +) -> PResult>> { + let mut statements = Vec::new(); + loop { + if p.at_eof() || terminators.iter().any(|word| p.at_keyword(word)) { + return Ok(statements); + } + statements.push(p.nested(Parser::parse_statement)?); + p.expect_op(";")?; + } +} + +/// Parses `BEGIN ...; [EXCEPTION WHEN ...] END`. +fn parse_block<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("BEGIN")?; + let statements = parse_statement_list(p, &["EXCEPTION", "END"])?; + let has_exception = p.eat_keyword("EXCEPTION"); + let mut handlers = Vec::new(); + if has_exception { + while !p.at_keyword("END") { + p.expect_keyword("WHEN")?; + let mut conditions = Vec::new(); + while !p.eat_keyword("THEN") { + conditions.push(p.parse_ident()?); + p.eat_keyword("OR"); + } + let statements = parse_statement_list(p, &["WHEN", "END"])?; + handlers.push(BigQueryHandler { + conditions, + statements, + }); + } + } + p.expect_keyword("END")?; + Ok(BigQueryBlock { + statements, + has_exception, + handlers, + }) +} + +fn parse_declare<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DECLARE")?; + let names = p.parse_comma_separated(Parser::parse_ident)?; + let data_type = if p.at_keyword("DEFAULT") { + None + } else { + Some(D::parse_data_type(p)?) + }; + let default = if data_type.is_none() || p.at_keyword("DEFAULT") { + p.expect_keyword("DEFAULT")?; + Some(p.parse_expr()?) + } else { + None + }; + Ok(BigQueryDeclare { + names, + data_type, + default, + }) +} + +fn parse_raise<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_keyword("RAISE")?; + if p.at_eof() || p.at_op(";") { + return Ok(None); + } + if p.at_keyword("USING") && p.peek_nth(1).is_word("MESSAGE") { + p.advance(); + p.advance(); + p.expect_op("=")?; + return Ok(Some(BigQueryRaise::UsingMessage(p.parse_expr()?))); + } + Ok(Some(BigQueryRaise::Value(p.parse_expr()?))) +} + +fn parse_export_data<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("EXPORT")?; + p.expect_keyword("DATA")?; + let connection = if p.at_keyword("WITH") && p.peek_nth(1).is_word("CONNECTION") { + p.advance(); + p.advance(); + Some(grammar::parse_object_name(p)?) + } else { + None + }; + p.expect_keyword("OPTIONS")?; + let options = parse_option_list(p, false)?; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + Ok(BigQueryExportData { + connection, + options, + query, + }) +} + +fn parse_alter_schema<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ALTER")?; + p.expect_keyword("SCHEMA")?; + let if_exists = p.at_keyword("IF") && p.peek_nth(1).is_word("EXISTS"); + if if_exists { + p.advance(); + p.advance(); + } + let name = grammar::parse_object_name(p)?; + let operation = if p.at_keyword("SET") && p.peek_nth(1).is_word("OPTIONS") { + p.advance(); + p.advance(); + BigQueryAlterSchemaOp::SetOptions(parse_option_list(p, true)?) + } else if p.at_keyword("SET") && p.peek_nth(1).is_word("DEFAULT") { + p.advance(); + p.advance(); + p.expect_keyword("COLLATE")?; + BigQueryAlterSchemaOp::SetDefaultCollate(p.parse_expr()?) + } else if p.at_keyword("ADD") && p.peek_nth(1).is_word("REPLICA") { + p.advance(); + p.advance(); + let replica = parse_name_or_string(p)?; + let options = parse_optional_options(p)?; + BigQueryAlterSchemaOp::AddReplica { replica, options } + } else if p.at_keyword("DROP") && p.peek_nth(1).is_word("REPLICA") { + p.advance(); + p.advance(); + BigQueryAlterSchemaOp::DropReplica(parse_name_or_string(p)?) + } else { + return Err(p.expected("an ALTER SCHEMA operation")); + }; + Ok(BigQueryAlterSchema { + if_exists, + name, + operation, + }) +} + +fn parse_execute_immediate<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("EXECUTE")?; + p.expect_keyword("IMMEDIATE")?; + let query = p.parse_expr()?; + let into = if p.eat_keyword("INTO") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + let using = if p.eat_keyword("USING") { + p.parse_comma_separated(|p| { + let expr = p.parse_expr()?; + let alias = grammar::parse_optional_alias(p)?; + Ok(ExprWithAlias { expr, alias }) + })? + } else { + Vec::new() + }; + Ok(BigQueryExecuteImmediate { query, into, using }) +} + +fn parse_assert<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ASSERT")?; + let condition = p.parse_expr()?; + let message = if p.eat_keyword("AS") { + Some(p.parse_expr()?) + } else { + None + }; + Ok(BigQueryStatement::Assert { condition, message }) +} + +/// Parses `DELETE table [WHERE ...]`, with no `FROM`. +fn parse_delete_without_from<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DELETE")?; + let table = p.parse_table_ref()?; + let selection = if p.eat_keyword("WHERE") { + Some(p.parse_expr()?) + } else { + None + }; + Ok(Delete { + output: None, + multi: None, + using: Vec::new(), + table, + selection, + order_by: Vec::new(), + limit: None, + returning: Vec::new(), + }) +} + +/// True at `BEGIN` that opens a block: not `BEGIN`, `BEGIN;` or `BEGIN TRANSACTION`. +fn at_block<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("BEGIN") && { + let next = p.peek_nth(1); + !(next.kind == TokenKind::Eof || next.is_op(";") || next.is_word("TRANSACTION")) + } +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let parsed = if at_block(p) { + Some(BigQueryStatement::Block(Box::new(parse_block(p)?))) + } else if p.at_keyword("DECLARE") { + Some(BigQueryStatement::Declare(Box::new(parse_declare(p)?))) + } else if p.at_keyword("RAISE") { + Some(BigQueryStatement::Raise(parse_raise(p)?)) + } else if p.at_keyword("EXPORT") { + Some(BigQueryStatement::ExportData(Box::new(parse_export_data( + p, + )?))) + } else if p.at_keyword("ALTER") && p.peek_nth(1).is_word("SCHEMA") { + Some(BigQueryStatement::AlterSchema(Box::new( + parse_alter_schema(p)?, + ))) + } else if p.at_keyword("EXECUTE") && p.peek_nth(1).is_word("IMMEDIATE") { + Some(BigQueryStatement::ExecuteImmediate(Box::new( + parse_execute_immediate(p)?, + ))) + } else if p.at_keyword("ASSERT") { + Some(parse_assert(p)?) + } else if p.at_keyword("SET") && p.peek_nth(1).is_op("(") { + Some(parse_set_tuple(p)?) + } else if p.at_keyword("DELETE") && !p.peek_nth(1).is_word("FROM") { + Some(BigQueryStatement::DeleteWithoutFrom(Box::new( + parse_delete_without_from(p)?, + ))) + } else if p.at_keyword("INSERT") && !p.peek_nth(1).is_word("INTO") { + return parse_insert_without_into(p); + } else { + None + }; + match parsed { + Some(parsed) => Ok(statement(parsed)), + None => grammar::parse_statement(p), + } +} + +/// Parses `INSERT` with its table straight after the keyword. +fn parse_insert_without_into<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INSERT")?; + let table = grammar::parse_object_name(p)?; + let columns = if grammar::at_column_list(p) { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let source = grammar::parse_insert_source(p)?; + let insert = Insert { + into: true, + output: None, + modifiers: Default::default(), + table, + columns, + source, + returning: Vec::new(), + }; + Ok(statement(BigQueryStatement::InsertWithoutInto(Box::new( + insert, + )))) +} + +/// Parses a `SELECT` head, which can end with `AS STRUCT` or `AS VALUE`. +pub fn parse_select_head<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + let mut modifiers = BuiltinSelect::default(); + let mut quantifier = grammar::parse_quantifier(p); + if p.at_keyword("AS") { + let next = p.peek_nth(1); + let word = if next.is_word("STRUCT") { + Some("STRUCT") + } else if next.is_word("VALUE") { + Some("VALUE") + } else { + None + }; + if let Some(word) = word { + p.advance(); + p.advance(); + modifiers.bigquery_as = Some(word.into()); + // `ALL` is the default and is not written back out. + if quantifier == SetQuantifier::All { + quantifier = SetQuantifier::None; + } + } + } + Ok((modifiers, quantifier)) +} + +/// Parses a select item, in which a wildcard can also exclude one bare column: +/// `* EXCEPT a`. +pub fn parse_select_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let item = databricks::parse_select_item(p)?; + let qualifier = match &item.kind { + SelectItemKind::Wildcard => None, + SelectItemKind::QualifiedWildcard(name) => Some(name.clone()), + _ => return Ok(item), + }; + let next = p.peek_nth(1); + let bare_exclude = p.at_keyword("EXCEPT") + && is_name(next) + && !["SELECT", "WITH", "VALUES", "ALL", "DISTINCT"] + .iter() + .any(|word| next.is_word(word)); + if !bare_exclude { + return Ok(item); + } + p.advance(); + let exclude = vec![p.parse_ident()?]; + Ok(SelectItemKind::WildcardWithOptions { + qualifier, + options: Box::new(WildcardOptions { + ilike: None, + exclude, + exclude_parens: true, + except_keyword: true, + replace: Vec::new(), + rename: Vec::new(), + rename_parens: false, + }), + } + .into()) +} + +/// Finishes a select item: `expr.*`, or an expression with any alias. +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, Builtin>, +) -> PResult> { + if p.at_op(".") && p.peek_nth(1).is_op("*") { + p.advance(); + p.advance(); + let options = parse_star_options(p)?; + let start = expr.span.start; + return Ok(SelectItemKind::Expr { + expr: Expr::new( + ext(BigQueryExpr::Star(Box::new(BigQueryStar { expr, options }))).kind, + p.span_since(start), + ), + alias: None, + } + .into()); + } + if p.eat_keyword("AS") { + let alias = parse_name_or_string(p)?; + return Ok(SelectItemKind::Expr { + expr, + alias: Some(alias), + } + .into()); + } + let token = p.peek(); + let implicit = token.kind == TokenKind::String + || token.kind == TokenKind::QuotedIdent + || (token.kind == TokenKind::Word && !is_reserved_for_column_alias(token.text)); + let alias = if implicit { + Some(parse_name_or_string(p)?) + } else { + None + }; + Ok(SelectItemKind::Expr { expr, alias }.into()) +} + +/// Parses `EXCEPT (...)` and `REPLACE (...)` after `expr.*`. +fn parse_star_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + let query_follows = ["SELECT", "WITH", "VALUES"] + .iter() + .any(|word| p.peek_nth(2).is_word(word)); + let exclude = if p.at_keyword("EXCEPT") && p.peek_nth(1).is_op("(") && !query_follows { + p.advance(); + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let replace = if p.at_keyword("REPLACE") && p.peek_nth(1).is_op("(") { + grammar::parse_wildcard_replace(p)? + } else { + Vec::new() + }; + if exclude.is_empty() && replace.is_empty() { + return Ok(None); + } + Ok(Some(Box::new(WildcardOptions { + ilike: None, + exclude, + exclude_parens: true, + except_keyword: true, + replace, + rename: Vec::new(), + rename_parens: false, + }))) +} + +fn at_system_time<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("FOR") + && p.peek_nth(1).is_word("SYSTEM_TIME") + && p.peek_nth(2).is_word("AS") + && p.peek_nth(3).is_word("OF") +} + +fn consume_system_time<'a, D: Dialect>(p: &mut Parser<'a, D>) { + for _ in 0..4 { + p.advance(); + } +} + +/// Parses a table: a name that can hold hyphens, optionally read as of a time. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_op("(") || p.at_keyword("LATERAL") { + return grammar::parse_table_factor(p); + } + let name = parse_table_name(p)?; + if p.at_op("(") { + let call = Box::new(p.parse_function_call(name)?); + let with_ordinality = p.at_keyword("WITH") && p.peek_nth(1).is_word("ORDINALITY"); + if with_ordinality { + p.advance(); + p.advance(); + } + return Ok(TableFactor::Function { + call, + with_ordinality, + }); + } + if at_system_time(p) { + consume_system_time(p); + let at = p.parse_expr()?; + return Ok(TableFactor::TimeTravel(Box::new(TimeTravel { + name, + kind: "FOR SYSTEM_TIME".into(), + at, + }))); + } + Ok(TableFactor::Named(name)) +} + +/// True if `table` is a call of `UNNEST`, with any alias. +fn is_unnest(table: &TableRef<'_, Builtin>) -> bool { + let TableFactor::Function { call, .. } = &table.factor else { + return false; + }; + let ExprKind::Function { name, .. } = &call.kind else { + return false; + }; + name.parts.len() == 1 && name.parts[0].text.eq_ignore_ascii_case("UNNEST") +} + +/// Parses a table with its alias, and any `WITH OFFSET` after them. +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let table = spark::parse_table_ref(p)?; + if !(p.at_keyword("WITH") && p.peek_nth(1).is_word("OFFSET") && is_unnest(&table)) { + return Ok(table); + } + p.advance(); + p.advance(); + let alias = grammar::parse_optional_alias(p)?; + let factor = BigQueryTableFactor::WithOffset(Box::new(BigQueryWithOffset { table, alias })); + Ok(TableRef { + factor: TableFactor::Ext(BuiltinTableFactor::BigQuery(factor)), + alias: None, + span: Span::default(), + }) +} + +/// Parses a call's arguments, which can hold clauses the core has no place for +/// inside the parentheses, or be a single query. +pub fn parse_function_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + p.expect_op("(")?; + let array = name.parts.len() == 1 && name.parts[0].text.eq_ignore_ascii_case("ARRAY"); + if array && grammar::query_starts_at(p, 0) { + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + return Ok(ext(BigQueryExpr::SubqueryCall(Box::new( + BigQuerySubqueryCall { name, query }, + )))); + } + let quantifier = grammar::parse_quantifier(p); + let args = if quantifier == SetQuantifier::None && p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(grammar::parse_function_arg)? + }; + let inner_nulls = grammar::parse_null_treatment(p); + let order_by = grammar::parse_optional_order_by(p)?; + let limit = if p.eat_keyword("LIMIT") { + Some(p.parse_expr()?) + } else { + None + }; + let having = if p.eat_keyword("HAVING") { + let max = p.eat_keyword("MAX"); + if !max { + p.expect_keyword("MIN")?; + } + Some((max, p.parse_expr()?)) + } else { + None + }; + p.expect_op(")")?; + + let within_group = if p.at_keyword("WITHIN") && p.peek_nth(1).is_word("GROUP") { + p.advance(); + p.advance(); + p.expect_op("(")?; + let items = grammar::parse_optional_order_by(p)?; + p.expect_op(")")?; + items + } else { + Vec::new() + }; + let filter = D::parse_function_filter(p)?; + let outer_nulls = grammar::parse_null_treatment(p); + let over = if p.eat_keyword("OVER") { + Some(grammar::parse_window_over(p)?) + } else { + None + }; + + if inner_nulls.is_some() || limit.is_some() || having.is_some() { + if !within_group.is_empty() || filter.is_some() || outer_nulls.is_some() { + return Err(p.expected("OVER, or nothing, after these call clauses")); + } + return Ok(ext(BigQueryExpr::Call(Box::new(BigQueryCall { + name, + quantifier, + args, + null_treatment: inner_nulls, + order_by, + limit, + having, + over, + })))); + } + let is_plain = quantifier == SetQuantifier::None + && order_by.is_empty() + && within_group.is_empty() + && filter.is_none() + && outer_nulls.is_none() + && over.is_none(); + let options = (!is_plain).then(|| { + Box::new(FunctionOptions { + parameters: Vec::new(), + inner_null_treatment: None, + quantifier, + order_by, + within_group, + filter, + null_treatment: outer_nulls, + separator: None, + on_overflow: None, + over, + }) + }); + Ok(ExprKind::Function { + name, + args, + options, + } + .into()) +} + +/// Parses `[a, b]`, with the cursor on the `[`. +fn parse_array_literal<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("[")?; + let items = if p.at_op("]") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op("]")?; + Ok(ext(BigQueryExpr::Array(items))) +} + +/// Parses `STRUCT<...>(values)` or `STRUCT(values)`, with the cursor on `STRUCT`. +/// In the typeless form, a value can be named with `AS name`. +pub fn parse_struct<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let ty = if p.peek_nth(1).is_op("<") { + Some(D::parse_data_type(p)?) + } else { + p.advance(); + None + }; + p.expect_op("(")?; + let typed = ty.is_some(); + let values = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(|p| { + let expr = p.parse_expr()?; + let alias = if !typed && p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + Ok(ExprWithAlias { expr, alias }) + })? + }; + p.expect_op(")")?; + Ok(ext(BigQueryExpr::Struct(Box::new(BigQueryStruct { + ty, + values, + })))) +} + +/// Parses a `CAST` or `SAFE_CAST`, whose type can be followed by `FORMAT`. +fn parse_cast<'a, D: Dialect>( + p: &mut Parser<'a, D>, + safe: bool, +) -> PResult> { + p.advance(); + p.expect_op("(")?; + let expr = p.parse_expr()?; + p.expect_keyword("AS")?; + let ty = D::parse_data_type(p)?; + if !p.eat_keyword("FORMAT") { + p.expect_op(")")?; + return Ok(ExprKind::Cast { + expr: Box::new(expr), + ty: Box::new(ty), + style: if safe { + CastStyle::SafeFunction + } else { + CastStyle::Function + }, + } + .into()); + } + let format = spark::parse_string(p)?; + let time_zone = if p.at_keyword("AT") { + p.advance(); + p.expect_keyword("TIME")?; + p.expect_keyword("ZONE")?; + Some(spark::parse_string(p)?) + } else { + None + }; + p.expect_op(")")?; + Ok(ext(BigQueryExpr::CastFormat(Box::new( + BigQueryCastFormat { + expr, + ty, + safe, + format, + time_zone, + }, + )))) +} + +/// The words after which a string literal has that type. +fn is_typed_literal_word(word: &str) -> bool { + [ + "JSON", + "NUMERIC", + "BIGNUMERIC", + "BIGDECIMAL", + "DECIMAL", + "DEC", + "BOOL", + "BOOLEAN", + "INT64", + "INT", + "INTEGER", + "SMALLINT", + "BIGINT", + "TINYINT", + "BYTEINT", + "FLOAT", + "FLOAT64", + "DOUBLE", + "STRING", + "BYTES", + "GEOGRAPHY", + ] + .iter() + .any(|name| name.eq_ignore_ascii_case(word)) +} + +/// Parses a prefix expression, adding BigQuery's literals and special calls. +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + let next = p.peek_nth(1); + if token.kind == TokenKind::Op && token.text == "[" { + return parse_array_literal(p); + } + if token.kind == TokenKind::Word { + // `INTERVAL` always introduces an interval here, never a column. + if token.is_word("INTERVAL") { + p.advance(); + return D::parse_interval(p); + } + if token.is_word("STRUCT") && (next.is_op("<") || next.is_op("(")) { + return parse_struct(p); + } + if next.is_op("(") { + if token.is_word("CAST") { + return parse_cast(p, false); + } + if token.is_word("SAFE_CAST") { + return parse_cast(p, true); + } + if token.is_word("EXTRACT") && p.peek_nth(2).is_word("WEEK") && p.peek_nth(3).is_op("(") + { + return parse_extract_week(p); + } + if token.is_word("LEFT") || token.is_word("RIGHT") { + let name = ObjectName { + parts: vec![p.parse_name_part()?], + }; + return p.parse_function_call(name); + } + } + if next.kind == TokenKind::String && is_typed_literal_word(token.text) { + p.advance(); + p.advance(); + let ty = DataType { + qualifier: Vec::new(), + name: Ident { + text: token.text.into(), + quote: None, + span: token.span, + }, + angle: None, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: crate::ast::ArrayType::None, + }; + return Ok(ExprKind::TypedString(Box::new(TypedString { + ty, + value: D::string_literal(next), + })) + .into()); + } + } + grammar::parse_prefix(p) +} + +fn parse_extract_week<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + for _ in 0..4 { + p.advance(); + } + let weekday = p.parse_ident()?; + p.expect_op(")")?; + p.expect_keyword("FROM")?; + let expr = p.parse_expr()?; + p.expect_op(")")?; + Ok(ext(BigQueryExpr::ExtractWeek(Box::new( + BigQueryExtractWeek { weekday, expr }, + )))) +} + +/// Levels of tree height for `.field` on a dialect node, whose wrappers take +/// more stack to clone than an ordinary level. +const FIELD_ACCESS_LEVELS: usize = 3; + +fn parse_field_access<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + let composite = match &left.kind { + ExprKind::Nested(_) | ExprKind::Function { .. } | ExprKind::Ext(_) => true, + ExprKind::Special(special) => matches!( + **special, + SpecialExpr::Subscript { .. } | SpecialExpr::FieldAccess { .. } + ), + _ => false, + }; + if !composite { + return Err(p.expected("a composite value before the field name")); + } + p.advance(); + let field = p.parse_name_part()?; + p.deepen_by(FIELD_ACCESS_LEVELS)?; + Ok(ExprKind::Special(Box::new(SpecialExpr::FieldAccess { expr: left, field })).into()) +} + +fn parse_in_unnest<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + negated: bool, +) -> PResult> { + p.expect_keyword("UNNEST")?; + p.expect_op("(")?; + let array = p.parse_expr()?; + p.expect_op(")")?; + Ok(ext(BigQueryExpr::InUnnest(Box::new(BigQueryInUnnest { + expr: left, + array, + negated, + })))) +} + +fn parse_in_unnest_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.advance(); + parse_in_unnest(p, left, false) +} + +fn parse_not_in_unnest_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + parse_in_unnest(p, left, true) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + if p.at_op(".") { + if p.peek_nth(1).is_op("*") { + return None; + } + return Some(InfixRule::custom(prec::POSTFIX, parse_field_access)); + } + if p.at_keyword("IN") && p.peek_nth(1).is_word("UNNEST") { + return Some(InfixRule::custom(prec::COMPARE, parse_in_unnest_op)); + } + if p.at_keyword("NOT") && p.peek_nth(1).is_word("IN") && p.peek_nth(2).is_word("UNNEST") { + return Some(InfixRule::custom(prec::COMPARE, parse_not_in_unnest_op)); + } + grammar::infix_rule(p) +} + +impl Dialect for BigQuery { + type Ext = Builtin; + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn parse_cte_columns<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(Vec::new()) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'#', ..] | [b'-', b'-', ..] => Some(Ok(lexer::line_comment(rest))), + [b'/', b'*', ..] => Some(lexer::block_comment(rest, false)), + _ => None, + } + } + + #[inline] + fn is_reserved(word: &str) -> bool { + grammar::is_reserved(word) && !word.eq_ignore_ascii_case("OFFSET") + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + RESERVED_FOR_TABLE_ALIAS + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + string_literal(token) + } + + fn at_from_first<'a>(p: &Parser<'a, Self>, n: usize) -> bool { + p.peek_nth(n).is_word("FROM") + } + + fn parse_select<'a>(p: &mut Parser<'a, Self>) -> PResult> { + databricks::parse_select(p) + } + + fn parse_select_head<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + parse_select_head(p) + } + + fn parse_projection<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_list_with_trailing_comma(p, Parser::parse_select_item) + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_name_part<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_name_or_string_part(p) + } + + fn parse_function_filter<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + fn parse_named_window_reference<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + if p.at_op("(") { + Ok(None) + } else { + p.parse_ident().map(Some) + } + } + + fn eat_merge_insert_row<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ROW") + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_function_call<'a>( + p: &mut Parser<'a, Self>, + name: ObjectName<'a>, + ) -> PResult> { + parse_function_call(p, name) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_pipe_operators<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_pipe_operators(p) + } + + fn parse_qualify<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + snowflake::parse_qualify(p) + } + + fn eat_group_by_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_add_column_if_not_exists<'a>(p: &mut Parser<'a, Self>) -> PResult { + grammar::parse_if_not_exists(p) + } +} + +fn write_opt_options( + f: &mut fmt::Formatter<'_>, + options: &Option>>, +) -> fmt::Result { + match options { + Some(options) => write!(f, " OPTIONS({})", comma(options)), + None => Ok(()), + } +} + +impl fmt::Display for BigQueryCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + write_create_flags(f, table.or_replace, table.temporary)?; + f.write_str(if self.external { + "EXTERNAL TABLE " + } else { + "TABLE " + })?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + if let Some((keyword, source)) = &self.source { + write!(f, " {keyword} {source}")?; + } + if self.external || !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + if let Some(connection) = &self.connection { + write!(f, " WITH CONNECTION {connection}")?; + } + if let Some(partition_by) = &self.partition_by { + write!(f, " PARTITION BY {partition_by}")?; + } + if !self.cluster_by.is_empty() { + write!(f, " CLUSTER BY {}", comma(&self.cluster_by))?; + } + write_opt_options(f, &self.options)?; + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} + +impl fmt::Display for BigQueryViewColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + write_opt_options(f, &self.options) + } +} + +impl fmt::Display for BigQueryCreateView<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_create_flags(f, self.or_replace, self.temporary)?; + f.write_str(if self.materialized { + "MATERIALIZED VIEW " + } else { + "VIEW " + })?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + write_opt_options(f, &self.options)?; + crate::display::write_view_query(f, &self.query) + } +} + +impl fmt::Display for BigQueryCreateFunction<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_create_flags(f, self.or_replace, self.temporary)?; + f.write_str("FUNCTION ")?; + write_if_not_exists(f, self.if_not_exists)?; + write!(f, "{}({})", self.name, comma(&self.args))?; + if let Some(returns) = &self.returns { + write!(f, " RETURNS {returns}")?; + } + match self.deterministic { + Some(true) => f.write_str(" DETERMINISTIC")?, + Some(false) => f.write_str(" NOT DETERMINISTIC")?, + None => {} + } + if let Some(language) = &self.language { + write!(f, " LANGUAGE {language}")?; + } + if let Some(connection) = &self.remote_connection { + write!(f, " REMOTE WITH CONNECTION {connection}")?; + } + if !self.options_after_body { + write_opt_options(f, &self.options)?; + } + if let Some(body) = &self.body { + write!(f, " AS {body}")?; + } + if self.options_after_body { + write_opt_options(f, &self.options)?; + } + Ok(()) + } +} + +impl fmt::Display for BigQueryFunctionArg<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {}", self.name, self.data_type) + } +} + +impl fmt::Display for BigQueryCreateSnapshot<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE SNAPSHOT TABLE ")?; + write_if_not_exists(f, self.if_not_exists)?; + write!(f, "{} CLONE {}", self.name, self.clone)?; + if let Some(at) = &self.for_system_time { + write!(f, " FOR SYSTEM_TIME AS OF {at}")?; + } + write_opt_options(f, &self.options) + } +} + +impl fmt::Display for BigQueryCreateSchema<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE SCHEMA ")?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if let Some(collate) = &self.default_collate { + write!(f, " DEFAULT COLLATE {collate}")?; + } + write_opt_options(f, &self.options) + } +} + +impl fmt::Display for BigQueryExportData<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("EXPORT DATA")?; + if let Some(connection) = &self.connection { + write!(f, " WITH CONNECTION {connection}")?; + } + write!(f, " OPTIONS({}) AS {}", comma(&self.options), self.query) + } +} + +impl fmt::Display for BigQueryAlterSchema<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ALTER SCHEMA ")?; + if self.if_exists { + f.write_str("IF EXISTS ")?; + } + write!(f, "{}", self.name)?; + match &self.operation { + BigQueryAlterSchemaOp::SetDefaultCollate(collate) => { + write!(f, " SET DEFAULT COLLATE {collate}") + } + BigQueryAlterSchemaOp::AddReplica { replica, options } => { + write!(f, " ADD REPLICA {replica}")?; + if let Some(options) = options { + write!(f, " OPTIONS ({})", comma(options))?; + } + Ok(()) + } + BigQueryAlterSchemaOp::DropReplica(replica) => write!(f, " DROP REPLICA {replica}"), + BigQueryAlterSchemaOp::SetOptions(options) => { + write!(f, " SET OPTIONS ({})", comma(options)) + } + } + } +} + +impl fmt::Display for BigQueryHandler<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("WHEN ")?; + for (i, condition) in self.conditions.iter().enumerate() { + if i > 0 { + f.write_str(" OR ")?; + } + condition.fmt(f)?; + } + f.write_str(" THEN")?; + for statement in &self.statements { + write!(f, " {statement};")?; + } + Ok(()) + } +} + +impl fmt::Display for BigQueryBlock<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BEGIN")?; + for statement in &self.statements { + write!(f, " {statement};")?; + } + if self.has_exception { + f.write_str(" EXCEPTION")?; + for handler in &self.handlers { + write!(f, " {handler}")?; + } + } + f.write_str(" END") + } +} + +impl fmt::Display for BigQueryDeclare<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "DECLARE {}", comma(&self.names))?; + if let Some(data_type) = &self.data_type { + write!(f, " {data_type}")?; + } + if let Some(default) = &self.default { + write!(f, " DEFAULT {default}")?; + } + Ok(()) + } +} + +impl fmt::Display for BigQueryExecuteImmediate<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "EXECUTE IMMEDIATE {}", self.query)?; + if !self.into.is_empty() { + write!(f, " INTO {}", comma(&self.into))?; + } + if !self.using.is_empty() { + write!(f, " USING {}", comma(&self.using))?; + } + Ok(()) + } +} + +impl fmt::Display for BigQueryStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CreateTable(create) => create.fmt(f), + Self::CreateView(view) => view.fmt(f), + Self::CreateFunction(function) => function.fmt(f), + Self::CreateSnapshot(snapshot) => snapshot.fmt(f), + Self::CreateSchema(schema) => schema.fmt(f), + Self::DeleteWithoutFrom(delete) => { + f.write_str("DELETE")?; + SpaceOrNewline.fmt(f)?; + Indent(&delete.table).fmt(f)?; + write_where_clause(f, &delete.selection) + } + Self::InsertWithoutInto(insert) => { + write!(f, "INSERT {}", insert.table)?; + if !insert.columns.is_empty() { + write!(f, " ({})", comma(&insert.columns))?; + } + crate::display::write_insert_source(f, &insert.source, !insert.columns.is_empty()) + } + Self::ExportData(export) => export.fmt(f), + Self::AlterSchema(alter) => alter.fmt(f), + Self::Block(block) => block.fmt(f), + Self::Declare(declare) => declare.fmt(f), + Self::Raise(None) => f.write_str("RAISE"), + Self::Raise(Some(BigQueryRaise::UsingMessage(message))) => { + write!(f, "RAISE USING MESSAGE = {message}") + } + Self::Raise(Some(BigQueryRaise::Value(value))) => write!(f, "RAISE {value}"), + Self::SetTuple { names, values } => { + write!(f, "SET ({}) = ({})", comma(names), comma(values)) + } + Self::ExecuteImmediate(execute) => execute.fmt(f), + Self::Assert { condition, message } => { + write!(f, "ASSERT {condition}")?; + if let Some(message) = message { + write!(f, " AS {message}")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for BigQueryCall<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}(", self.name)?; + match self.quantifier { + SetQuantifier::None => {} + SetQuantifier::All => f.write_str("ALL ")?, + SetQuantifier::Distinct => f.write_str("DISTINCT ")?, + } + comma(&self.args).fmt(f)?; + match self.null_treatment { + Some(NullTreatment::Ignore) => f.write_str(" IGNORE NULLS")?, + Some(NullTreatment::Respect) => f.write_str(" RESPECT NULLS")?, + None => {} + } + if !self.order_by.is_empty() { + write!(f, " ORDER BY {}", comma(&self.order_by))?; + } + if let Some(limit) = &self.limit { + write!(f, " LIMIT {limit}")?; + } + if let Some((max, having)) = &self.having { + let bound = if *max { "MAX" } else { "MIN" }; + write!(f, " HAVING {bound} {having}")?; + } + f.write_str(")")?; + if let Some(over) = &self.over { + write!(f, " OVER {over}")?; + } + Ok(()) + } +} + +impl fmt::Display for BigQueryExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Array(items) => write!(f, "[{}]", comma(items)), + Self::Struct(literal) => { + match &literal.ty { + Some(ty) => ty.fmt(f)?, + None => f.write_str("STRUCT")?, + } + write!(f, "({})", comma(&literal.values)) + } + Self::Star(star) => { + write!(f, "{}.*", star.expr)?; + if let Some(options) = &star.options { + options.fmt(f)?; + } + Ok(()) + } + Self::InUnnest(in_unnest) => { + let not = if in_unnest.negated { "NOT " } else { "" }; + write!(f, "{} {not}IN UNNEST({})", in_unnest.expr, in_unnest.array) + } + Self::CastFormat(cast) => { + let keyword = if cast.safe { "SAFE_CAST" } else { "CAST" }; + write!( + f, + "{keyword}({} AS {} FORMAT {}", + cast.expr, cast.ty, cast.format + )?; + if let Some(ref zone) = cast.time_zone { + write!(f, " AT TIME ZONE {}", zone)?; + } + f.write_str(")") + } + Self::ExtractWeek(extract) => { + write!( + f, + "EXTRACT(WEEK({}) FROM {})", + extract.weekday, extract.expr + ) + } + Self::Call(call) => call.fmt(f), + Self::SubqueryCall(call) => write!(f, "{}({})", call.name, call.query), + } + } +} + +impl fmt::Display for BigQueryTableFactor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::WithOffset(offset) => { + write!(f, "{} WITH OFFSET", offset.table)?; + if let Some(alias) = &offset.alias { + write!(f, " AS {alias}")?; + } + Ok(()) + } + } + } +} diff --git a/sqlparser_v2/src/dialect/builtin.rs b/sqlparser_v2/src/dialect/builtin.rs new file mode 100644 index 0000000000..60d343a065 --- /dev/null +++ b/sqlparser_v2/src/dialect/builtin.rs @@ -0,0 +1,392 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The AST shared by all built-in dialects, and choosing one at runtime. + +use std::borrow::Cow; +use std::fmt; + +use crate::ast::{Expr, Query, Statement}; +use crate::dialect::bigquery::{BigQueryExpr, BigQueryStatement, BigQueryTableFactor}; +use crate::dialect::clickhouse::{ + ClickHouseExpr, ClickHouseOrderByItem, ClickHouseQueryClauses, ClickHouseStatement, +}; +use crate::dialect::databricks::DatabricksStatement; +use crate::dialect::duckdb::{DuckDbExpr, DuckDbStatement}; +use crate::dialect::hive::HiveStatement; +use crate::dialect::mssql::{ + MsSqlExpr, MsSqlForClause, MsSqlStatement, MsSqlTableFactor, MsSqlTop, +}; +use crate::dialect::mysql::{MySqlExpr, MySqlStatement, MySqlTableFactor}; +use crate::dialect::oracle::{self, OptimizerHint, OracleExpr, OracleStatement}; +use crate::dialect::postgres::{ + PostgresExpr, PostgresStatement, PostgresTableFactor, PostgresUsingConstraint, +}; +use crate::dialect::redshift::{RedshiftExpr, RedshiftStatement, RedshiftTableFactor}; +use crate::dialect::snowflake::{SnowflakeExpr, SnowflakeStatement}; +use crate::dialect::spark::SparkStatement; +use crate::dialect::sqlite::{SqliteExpr, SqliteIndexedTable, SqliteStatement}; +use crate::dialect::teradata::{TeradataExpr, TeradataStatement, TeradataTop}; +use crate::dialect::{ + AstExt, BigQuery, ClickHouse, Core, Databricks, DuckDb, Hive, MsSql, MySql, Oracle, Postgres, + Redshift, Snowflake, Spark, Sqlite, Teradata, +}; +use crate::{PResult, parse_query, parse_sql}; + +/// The extensions used by every built-in dialect, so that they all produce +/// the same AST type. +#[derive(Debug, Clone, PartialEq)] +pub struct Builtin; + +impl AstExt for Builtin { + type TableFactor<'a> = BuiltinTableFactor<'a>; + type JoinConstraint<'a> = BuiltinJoinConstraint<'a>; + type QueryTail<'a> = BuiltinQueryTail<'a>; + type Expr<'a> = BuiltinExpr<'a>; + type Select<'a> = BuiltinSelect<'a>; + type Statement<'a> = BuiltinStatement<'a>; + type Insert<'a> = BuiltinInsert<'a>; + type OrderByItem<'a> = ClickHouseOrderByItem<'a>; + + fn modifiers_follow_quantifier(modifiers: &BuiltinSelect<'_>) -> bool { + modifiers.mysql != MySqlSelect::default() + || modifiers.mssql_top.is_some() + || modifiers.bigquery_as.is_some() + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum BuiltinExpr<'a> { + MySql(MySqlExpr<'a, Builtin>), + Snowflake(SnowflakeExpr<'a>), + Teradata(TeradataExpr<'a>), + Oracle(OracleExpr<'a>), + Sqlite(SqliteExpr<'a>), + MsSql(MsSqlExpr<'a>), + BigQuery(BigQueryExpr<'a>), + ClickHouse(ClickHouseExpr<'a>), + DuckDb(DuckDbExpr<'a>), + Postgres(PostgresExpr<'a>), + Redshift(RedshiftExpr<'a>), +} + +/// Join conditions that only some built-in dialects have. +#[derive(Debug, Clone, PartialEq)] +pub enum BuiltinJoinConstraint<'a> { + Postgres(PostgresUsingConstraint<'a>), +} + +impl fmt::Display for BuiltinJoinConstraint<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Postgres(constraint) => constraint.fmt(f), + } + } +} + +/// Table factors that only some built-in dialects have. +#[derive(Debug, Clone, PartialEq)] +pub enum BuiltinTableFactor<'a> { + MySql(Box>), + Sqlite(Box>), + MsSql(MsSqlTableFactor<'a>), + BigQuery(BigQueryTableFactor<'a>), + Postgres(Box>), + Redshift(Box>), +} + +impl fmt::Display for BuiltinTableFactor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MySql(factor) => factor.fmt(f), + Self::Sqlite(table) => table.fmt(f), + Self::MsSql(factor) => factor.fmt(f), + Self::BigQuery(factor) => factor.fmt(f), + Self::Postgres(factor) => factor.fmt(f), + Self::Redshift(factor) => factor.fmt(f), + } + } +} + +impl<'a> From> for BuiltinExpr<'a> { + fn from(expr: MySqlExpr<'a, Builtin>) -> Self { + Self::MySql(expr) + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct BuiltinSelect<'a> { + /// The number in `SELECT TOP n`. + pub top: Option>, + /// The expressions in PostgreSQL's `SELECT DISTINCT ON (...)`. + pub distinct_on: Option>>, + /// Teradata's `TOP` when it is more than a plain number. + pub teradata_top: Option>>, + pub mysql: MySqlSelect, + /// Optimizer hints written as comments after `SELECT`. + pub hints: Vec>, + /// `TOP` in Microsoft SQL Server, after any `DISTINCT`. + pub mssql_top: Option>>, + /// BigQuery's `AS STRUCT` or `AS VALUE`, holding the word after `AS`. + pub bigquery_as: Option>, +} + +/// MySQL's keywords between `SELECT` and the select list. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct MySqlSelect { + pub high_priority: bool, + pub straight_join: bool, + pub small_result: bool, + pub big_result: bool, + pub buffer_result: bool, + pub no_cache: bool, + pub calc_found_rows: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum BuiltinStatement<'a> { + MySql(MySqlStatement<'a>), + Snowflake(SnowflakeStatement<'a>), + Postgres(PostgresStatement<'a>), + Redshift(RedshiftStatement<'a>), + Spark(SparkStatement<'a>), + Databricks(DatabricksStatement<'a>), + Hive(HiveStatement<'a>), + BigQuery(BigQueryStatement<'a>), + ClickHouse(ClickHouseStatement<'a>), + DuckDb(DuckDbStatement<'a>), + MsSql(MsSqlStatement<'a>), + Oracle(OracleStatement<'a>), + Sqlite(SqliteStatement<'a>), + Teradata(TeradataStatement<'a>), +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct BuiltinInsert<'a> { + /// MySQL's `INSERT IGNORE`. + pub ignore: bool, + /// Snowflake's `INSERT OVERWRITE INTO`. + pub overwrite: bool, + /// MySQL's `LOW_PRIORITY`, `DELAYED` or `HIGH_PRIORITY`. + pub priority: Option>, +} + +/// Clauses at the end of a query that only a built-in dialect has. +/// +/// One pointer, to keep every query small. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct BuiltinQueryTail<'a>(pub Option>>); + +#[derive(Debug, Clone, PartialEq)] +pub enum BuiltinQueryClauses<'a> { + /// Microsoft SQL Server's `FOR XML`, `FOR JSON` or `FOR BROWSE`. + MsSql(MsSqlForClause<'a>), + /// ClickHouse's `SETTINGS` and `FORMAT`. + ClickHouse(ClickHouseQueryClauses<'a>), +} + +impl fmt::Display for BuiltinQueryTail<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0.as_deref() { + None => Ok(()), + Some(BuiltinQueryClauses::MsSql(clause)) => write!(f, " {clause}"), + Some(BuiltinQueryClauses::ClickHouse(clauses)) => clauses.fmt(f), + } + } +} + +/// A built-in dialect chosen at runtime. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DialectKind { + Core, + MySql, + Postgres, + Redshift, + Snowflake, + Spark, + Databricks, + Hive, + BigQuery, + ClickHouse, + DuckDb, + MsSql, + Oracle, + Sqlite, + Teradata, +} + +impl DialectKind { + /// Finds a dialect by name, ignoring case. + pub fn from_name(name: &str) -> Option { + const NAMES: [(&str, DialectKind); 18] = [ + ("core", DialectKind::Core), + ("mysql", DialectKind::MySql), + ("postgres", DialectKind::Postgres), + ("postgresql", DialectKind::Postgres), + ("redshift", DialectKind::Redshift), + ("snowflake", DialectKind::Snowflake), + ("spark", DialectKind::Spark), + ("databricks", DialectKind::Databricks), + ("hive", DialectKind::Hive), + ("bigquery", DialectKind::BigQuery), + ("clickhouse", DialectKind::ClickHouse), + ("duckdb", DialectKind::DuckDb), + ("mssql", DialectKind::MsSql), + ("sqlserver", DialectKind::MsSql), + ("oracle", DialectKind::Oracle), + ("sqlite", DialectKind::Sqlite), + ("teradata", DialectKind::Teradata), + ("tsql", DialectKind::MsSql), + ]; + NAMES + .iter() + .find(|(candidate, _)| candidate.eq_ignore_ascii_case(name)) + .map(|&(_, kind)| kind) + } +} + +/// Calls a generic function with the dialect type that `kind` names. +macro_rules! dispatch { + ($kind:expr, $function:ident($sql:expr)) => { + match $kind { + DialectKind::Core => $function::($sql), + DialectKind::MySql => $function::($sql), + DialectKind::Postgres => $function::($sql), + DialectKind::Redshift => $function::($sql), + DialectKind::Snowflake => $function::($sql), + DialectKind::Spark => $function::($sql), + DialectKind::Databricks => $function::($sql), + DialectKind::Hive => $function::($sql), + DialectKind::BigQuery => $function::($sql), + DialectKind::ClickHouse => $function::($sql), + DialectKind::DuckDb => $function::($sql), + DialectKind::MsSql => $function::($sql), + DialectKind::Oracle => $function::($sql), + DialectKind::Sqlite => $function::($sql), + DialectKind::Teradata => $function::($sql), + } + }; +} + +/// Parses statements using a dialect chosen at runtime. +/// +/// The choice is made once here. Parsing itself is statically dispatched. +pub fn parse_sql_as(kind: DialectKind, sql: &str) -> PResult>> { + dispatch!(kind, parse_sql(sql)) +} + +/// Parses a single query using a dialect chosen at runtime. +pub fn parse_query_as(kind: DialectKind, sql: &str) -> PResult> { + dispatch!(kind, parse_query(sql)) +} + +impl fmt::Display for BuiltinStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MySql(statement) => statement.fmt(f), + Self::Snowflake(statement) => statement.fmt(f), + Self::Postgres(statement) => statement.fmt(f), + Self::Redshift(statement) => statement.fmt(f), + Self::Spark(statement) => statement.fmt(f), + Self::Databricks(statement) => statement.fmt(f), + Self::Hive(statement) => statement.fmt(f), + Self::BigQuery(statement) => statement.fmt(f), + Self::ClickHouse(statement) => statement.fmt(f), + Self::DuckDb(statement) => statement.fmt(f), + Self::MsSql(statement) => statement.fmt(f), + Self::Oracle(statement) => statement.fmt(f), + Self::Sqlite(statement) => statement.fmt(f), + Self::Teradata(statement) => statement.fmt(f), + } + } +} + +impl fmt::Display for BuiltinExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BuiltinExpr::MySql(expr) => expr.fmt(f), + BuiltinExpr::Snowflake(expr) => expr.fmt(f), + BuiltinExpr::Teradata(expr) => expr.fmt(f), + BuiltinExpr::Oracle(expr) => expr.fmt(f), + BuiltinExpr::Sqlite(expr) => expr.fmt(f), + BuiltinExpr::MsSql(expr) => expr.fmt(f), + BuiltinExpr::BigQuery(expr) => expr.fmt(f), + BuiltinExpr::ClickHouse(expr) => expr.fmt(f), + BuiltinExpr::DuckDb(expr) => expr.fmt(f), + BuiltinExpr::Postgres(expr) => expr.fmt(f), + BuiltinExpr::Redshift(expr) => expr.fmt(f), + } + } +} + +impl fmt::Display for BuiltinSelect<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + oracle::write_hints(f, &self.hints)?; + if let Some(ref top) = self.top { + write!(f, "TOP {top} ")?; + } + if let Some(top) = &self.teradata_top { + write!(f, "{top} ")?; + } + if let Some(exprs) = &self.distinct_on { + f.write_str("DISTINCT ON (")?; + for (i, expr) in exprs.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{expr}")?; + } + f.write_str(") ")?; + } + if let Some(top) = &self.mssql_top { + write!(f, "{top} ")?; + } + if let Some(ref word) = self.bigquery_as { + write!(f, "AS {word} ")?; + } + let flags = [ + (self.mysql.high_priority, "HIGH_PRIORITY "), + (self.mysql.straight_join, "STRAIGHT_JOIN "), + (self.mysql.small_result, "SQL_SMALL_RESULT "), + (self.mysql.big_result, "SQL_BIG_RESULT "), + (self.mysql.buffer_result, "SQL_BUFFER_RESULT "), + (self.mysql.no_cache, "SQL_NO_CACHE "), + (self.mysql.calc_found_rows, "SQL_CALC_FOUND_ROWS "), + ]; + for (set, keyword) in flags { + if set { + f.write_str(keyword)?; + } + } + Ok(()) + } +} + +impl fmt::Display for BuiltinInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(ref priority) = self.priority { + write!(f, "{priority} ")?; + } + if self.ignore { + f.write_str("IGNORE ")?; + } + if self.overwrite { + f.write_str("OVERWRITE ")?; + } + Ok(()) + } +} diff --git a/sqlparser_v2/src/dialect/clickhouse.rs b/sqlparser_v2/src/dialect/clickhouse.rs new file mode 100644 index 0000000000..c4e68f7a50 --- /dev/null +++ b/sqlparser_v2/src/dialect/clickhouse.rs @@ -0,0 +1,2910 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! ClickHouse: its query clauses, table engines and administrative statements. + +use crate::ast::Span; +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + AlterTable, AlterTableOp, AngleArguments, Assignment, BinaryOp, ColumnDef, ColumnOption, + CreateFlags, CreateTable, CreateView, DataType, DataTypeSuffix, Delete, ExplainTarget, Expr, + ExprKind, FunctionOptions, GroupByModifier, Ident, Insert, InsertSource, IsTest, Join, + JoinConstraint, JoinKind, Limit, ObjectName, OffsetRows, OrderByItem, Query, SampleClause, + Select, SelectItem, SelectItemKind, SetQuantifier, SpecialExpr, Statement, StatementKind, + StringLiteral, StructField, TableConstraint, TableFactor, TableRef, TableSample, Truncate, + Update, WildcardOptions, +}; +use crate::dialect::builtin::{ + BuiltinExpr, BuiltinQueryClauses, BuiltinQueryTail, BuiltinStatement, +}; +use crate::dialect::snowflake; +use crate::dialect::{Builtin, Dialect, mysql, postgres, spark}; +use crate::display::{ + Indent, SpaceOrNewline, comma, write_columns, write_create_flags, write_if_exists, + write_if_not_exists, write_list_clause, write_where_clause, +}; +use crate::grammar::{self, prec}; +use crate::lexer::{self, LexResult, Lexeme, Token, TokenKind, quoted, quoted_with_backslash}; +use crate::parser::{InfixRule, Parser}; + +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouse; + +/// Statements only ClickHouse has, and forms of common ones with its clauses. +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseStatement<'a> { + /// `KILL [CONNECTION | QUERY | MUTATION] id` + Kill { + kind: Option>, + id: Cow<'a, str>, + }, + Optimize(Box>), + TruncateOnCluster(Box>), + AlterTable(Box>), + CreateTable(Box>), + CreateView(Box>), + Insert(Box>), + Update(Box>), + Delete(Box>), +} + +/// `OPTIMIZE TABLE name ...` +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseOptimize<'a> { + pub name: ObjectName<'a>, + pub on_cluster: Option>, + pub partition: Option>, + pub include_final: bool, + pub deduplicate: Option>, +} + +/// `PARTITION expr` or `PARTITION ID 'name'`. +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseOptimizePartition<'a> { + Expr(Expr<'a, Builtin>), + Id(Ident<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Deduplicate<'a> { + All, + By(Expr<'a, Builtin>), +} + +/// `ALTER TABLE` with clauses the core does not have. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseAlterTable<'a> { + pub if_exists: bool, + pub name: ObjectName<'a>, + pub on_cluster: Option>, + pub operations: Vec>, +} + +/// An operation of `ALTER TABLE`: a core one or one only ClickHouse has. +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseAlterOp<'a> { + Core(AlterTableOp<'a, Builtin>), + AddProjection(Box>), + DropProjection { + if_exists: bool, + name: Ident<'a>, + }, + ClearProjection { + if_exists: bool, + name: Ident<'a>, + partition: Option>, + }, + MaterializeProjection { + if_exists: bool, + name: Ident<'a>, + partition: Option>, + }, + Attach(ClickHousePartition<'a>), + Detach(ClickHousePartition<'a>), + Freeze { + partition: ClickHousePartition<'a>, + with_name: Option>, + }, + Unfreeze { + partition: ClickHousePartition<'a>, + with_name: Option>, + }, + ModifyOrderBy(ClickHouseSortingKey<'a>), +} + +/// `ADD PROJECTION [IF NOT EXISTS] name (SELECT ...)` +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseProjection<'a> { + pub if_not_exists: bool, + pub name: Ident<'a>, + pub projection: Vec>, + pub group_by: Vec>, + pub order_by: Vec>, +} + +/// `PARTITION expr` or `PART expr`. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHousePartition<'a> { + pub part: bool, + pub expr: Expr<'a, Builtin>, +} + +/// A single sorting key expression, or a list of them in parentheses. +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseSortingKey<'a> { + One(Expr<'a, Builtin>), + Many(Vec>), +} + +/// `CREATE TABLE` with clauses the core does not have. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + /// `LOCAL` or `GLOBAL`, written before `TEMPORARY`. + pub scope: Option>, + pub on_cluster: Option>, + pub engine: Option>, + pub primary_key: Option>, + pub order_by: Option>, + pub partition_by: Option>, + /// `DELETE ROWS`, `PRESERVE ROWS` or `DROP`. + pub on_commit: Option>, +} + +/// `ENGINE = name [(args)]` +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseEngine<'a> { + pub name: Ident<'a>, + /// Names and strings. A string keeps its quote. + pub args: Vec>, +} + +/// `CREATE [MATERIALIZED] VIEW` with typed columns or a target table. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseCreateView<'a> { + pub or_replace: bool, + pub materialized: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub columns: Vec>, + pub to: Option>, + pub query: Box>, +} + +/// `INSERT` into a table function, or with `SETTINGS` or `FORMAT`. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseInsert<'a> { + pub table_keyword: bool, + pub target: ClickHouseInsertTarget<'a>, + pub columns: Vec>, + pub source: Option>, + pub settings: Vec>, + pub format: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseInsertTarget<'a> { + Table(ObjectName<'a>), + /// `FUNCTION name(args)`, always an [`ExprKind::Function`]. + Function(Box>), +} + +/// `FORMAT name [values]`, in an `INSERT`. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseInputFormat<'a> { + pub name: Ident<'a>, + pub values: Vec>, +} + +/// `UPDATE` with `ON CLUSTER` or `SETTINGS`. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseUpdate<'a> { + pub table: TableRef<'a, Builtin>, + pub on_cluster: Option>, + pub assignments: Vec>, + pub selection: Option>, + pub settings: Vec>, +} + +/// `DELETE` with `ON CLUSTER` or `SETTINGS`. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseDelete<'a> { + pub table: TableRef<'a, Builtin>, + pub on_cluster: Option>, + pub selection: Option>, + pub settings: Vec>, +} + +/// `name = value`, in a `SETTINGS` clause. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseSetting<'a> { + pub name: Ident<'a>, + pub value: Expr<'a, Builtin>, +} + +/// The name in a `FORMAT` clause of a query. +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseFormat<'a> { + Name(Ident<'a>), + Null, +} + +/// `SETTINGS` and `FORMAT`, at the end of a query. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseQueryClauses<'a> { + pub settings: Vec>, + pub format: Option>, +} + +/// `WITH FILL` and `INTERPOLATE`, after an `ORDER BY` item. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ClickHouseOrderByItem<'a> { + pub with_fill: Option>>, + pub interpolate: Option>>, +} + +/// `TRUNCATE ... ON CLUSTER name` +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseTruncate<'a> { + pub truncate: Truncate<'a>, + pub on_cluster: Ident<'a>, +} + +/// `WITH FILL [FROM x] [TO y] [STEP z]` +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseWithFill<'a> { + pub from: Option>, + pub to: Option>, + pub step: Option>, +} + +/// `INTERPOLATE [(column [AS expr], ...)]`. `exprs` is `None` when the +/// parentheses are left out, and empty for `INTERPOLATE ()`. +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseInterpolate<'a> { + pub exprs: Option, Option>)>>, +} + +/// Expression syntax only ClickHouse has. +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseExpr<'a> { + /// `expr.1`, written `expr . 1` when rendered. + TupleElement { + expr: Box>, + index: Cow<'a, str>, + }, + /// `[a, b]` + Array(Vec>), + /// `{key: value, ...}`. A string key keeps its quote. + Dictionary(Vec<(Ident<'a>, Expr<'a, Builtin>)>), + /// `expr GLOBAL [NOT] IN ...` + GlobalIn(Box>), + /// A lambda with a type on at least one parameter: `x Int8 -> x`. + TypedLambda(Box>), + /// A table function call with settings: `f(a, SETTINGS b = 1)`. + SettingsCall(Box>), + /// `ORDER BY ALL` + All, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseGlobalIn<'a> { + pub expr: Expr<'a, Builtin>, + pub negated: bool, + pub target: ClickHouseInTarget<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ClickHouseInTarget<'a> { + List(Vec>), + Subquery(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseTypedLambda<'a> { + pub params: Vec<(Ident<'a>, Option>)>, + pub parenthesized: bool, + pub body: Expr<'a, Builtin>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ClickHouseSettingsCall<'a> { + pub name: ObjectName<'a>, + pub args: Vec>, + pub settings: Vec>, +} + +fn ext<'a>(expr: ClickHouseExpr<'a>) -> Expr<'a, Builtin> { + ExprKind::Ext(BuiltinExpr::ClickHouse(expr)).into() +} + +fn statement<'a>(statement: ClickHouseStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::ClickHouse(statement)).into() +} + +/// Set while parsing a column option's expression, where `NOT NULL` belongs to +/// the column unless parentheses enclose it. +const IN_COLUMN_OPTION: u32 = 1 << 8; + +#[inline] +fn is_name_start(byte: u8) -> bool { + byte.is_ascii_alphabetic() || byte == b'_' +} + +#[inline] +fn is_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') +} + +fn digits_with_separators(bytes: &[u8], from: usize) -> Result { + let mut len = 0; + while let Some(&byte) = bytes.get(from + len) { + if byte.is_ascii_digit() { + len += 1; + } else if byte == b'_' { + if len == 0 || !bytes.get(from + len + 1).is_some_and(u8::is_ascii_digit) { + return Err("misplaced underscore in number"); + } + len += 1; + } else { + break; + } + } + Ok(len) +} + +/// Lexes a number, in which underscores can separate digits. Leaves hex +/// numbers and text that does not start with a number to the core. +fn lex_number(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let leading_point = bytes[0] == b'.' && bytes.get(1).is_some_and(u8::is_ascii_digit); + if !leading_point && !bytes[0].is_ascii_digit() { + return None; + } + if bytes[0] == b'0' && bytes.get(1) == Some(&b'x') { + return Some(lex_hex_number(bytes)); + } + Some(lex_number_body(bytes)) +} + +fn lex_hex_number(bytes: &[u8]) -> LexResult { + let mut len = 2; + while let Some(&byte) = bytes.get(len) { + let separator = + byte == b'_' && len > 2 && bytes.get(len + 1).is_some_and(u8::is_ascii_hexdigit); + if !byte.is_ascii_hexdigit() && !separator { + break; + } + len += 1; + } + if bytes + .get(len) + .is_some_and(|&b| is_name_start(b) || b >= 0x80) + { + return Err("invalid number"); + } + Ok(Lexeme { + kind: TokenKind::HexString, + len, + }) +} + +fn lex_number_body(bytes: &[u8]) -> LexResult { + let mut len = digits_with_separators(bytes, 0)?; + if bytes.get(len) == Some(&b'.') + && !bytes + .get(len + 1) + .is_some_and(|&b| is_name_start(b) || b == b'.') + { + len += 1 + digits_with_separators(bytes, len + 1)?; + } + if matches!(bytes.get(len), Some(b'e' | b'E')) { + let sign = usize::from(matches!(bytes.get(len + 1), Some(b'+' | b'-'))); + let exponent = digits_with_separators(bytes, len + 1 + sign)?; + if exponent > 0 { + len += 1 + sign + exponent; + } + } + if bytes + .get(len) + .is_some_and(|&b| is_name_start(b) || b >= 0x80) + { + return Err("invalid number"); + } + Ok(Lexeme { + kind: TokenKind::Number, + len, + }) +} + +/// Reads backtick-quoted names, strings with backslash escapes, names holding +/// `$`, numbers with separators, and operators the core does not have. +#[inline] +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) + }; + let bytes = rest.as_bytes(); + match bytes { + [b'`', ..] => Some(quoted(rest, TokenKind::QuotedIdent)), + [b'\'', ..] => Some(quoted_with_backslash(rest, TokenKind::String)), + [b'=', b'=', ..] | [b'-', b'>', ..] | [b':', b':', ..] => op(2), + [b'{' | b'}', ..] => op(1), + [b'$', ..] => postgres::dollar_string(rest), + [b'x' | b'X', b'\'', ..] => None, + [b, ..] if is_name_start(*b) => Some(Ok(Lexeme { + kind: TokenKind::Word, + len: bytes.iter().take_while(|b| is_name_byte(**b)).count(), + })), + [b, ..] if *b >= 0x80 => Some(Err("unexpected character")), + _ => lex_number(rest), + } +} + +/// A point directly after a name, `)`, `]` or a tuple index starts an element +/// access such as `t.1`, never a number, and an element is a whole number. +/// A colon directly after a word or a string separates a dictionary key from +/// its value, even when a name follows it. +#[inline] +pub fn lex_after(prev: Option>, rest: &str) -> Option { + let prev = prev?; + let bytes = rest.as_bytes(); + match bytes { + [b'.', next, ..] if next.is_ascii_digit() => { + let continues_value = matches!(prev.kind, TokenKind::Word | TokenKind::QuotedIdent) + || prev.kind == TokenKind::Number + || prev.is_op(")") + || prev.is_op("]"); + continues_value.then_some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })) + } + [first, ..] if first.is_ascii_digit() && prev.is_op(".") => Some(Ok(Lexeme { + kind: TokenKind::Number, + len: bytes.iter().take_while(|b| b.is_ascii_digit()).count(), + })), + [b':', next, ..] + if *next != b':' + && matches!( + prev.kind, + TokenKind::Word | TokenKind::QuotedIdent | TokenKind::String + ) => + { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })) + } + _ => None, + } +} + +/// A `#` starts a comment only before a space or `!`. +#[inline] +pub fn lex_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'#', b' ' | b'!', ..] => Some(Ok(lexer::line_comment(rest))), + _ => lexer::lex_core_comment(rest), + } +} + +/// Words that start a clause after a table, on top of the core's. +#[inline] +pub fn is_reserved_for_alias(word: &str) -> bool { + if word.eq_ignore_ascii_case("QUALIFY") { + return true; + } + ["FORMAT", "SETTINGS", "PREWHERE", "SAMPLE", "GLOBAL"] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved_for_alias(word) +} + +fn at_dictionary_key_token(token: Token<'_>) -> bool { + matches!( + token.kind, + TokenKind::Word | TokenKind::QuotedIdent | TokenKind::String + ) +} + +/// Parses a name that can also be written as a string, keeping its quote. +fn parse_name_or_string<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + if token.kind != TokenKind::String { + return p.parse_name_part(); + } + p.advance(); + Ok(Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some('\''), + span: token.span, + }) +} + +pub fn parse_dictionary<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("{")?; + if p.eat_op("}") { + return Ok(ext(ClickHouseExpr::Dictionary(Vec::new()))); + } + let fields = p.parse_comma_separated(|p| { + if !at_dictionary_key_token(p.peek()) { + return Err(p.expected("a dictionary key")); + } + let key = parse_name_or_string(p)?; + p.expect_op(":")?; + Ok((key, p.parse_expr()?)) + })?; + p.expect_op("}")?; + Ok(ext(ClickHouseExpr::Dictionary(fields))) +} + +fn parse_array_literal<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("[")?; + let items = if p.at_op("]") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op("]")?; + Ok(ext(ClickHouseExpr::Array(items))) +} + +fn is_name(token: Token<'_>) -> bool { + matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +/// True at `name ... ) ->` for a parenthesized lambda with a typed parameter. +pub fn at_typed_lambda<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if is_name(p.peek()) { + return p.peek_nth(1).kind == TokenKind::Word && p.peek_nth(2).is_op("->"); + } + if !p.at_op("(") || !is_name(p.peek_nth(1)) { + return false; + } + let mut depth = 0usize; + let mut typed = false; + let mut n = 0; + loop { + let token = p.peek_nth(n); + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + depth -= 1; + if depth == 0 { + return typed && p.peek_nth(n + 1).is_op("->"); + } + } + TokenKind::Word | TokenKind::QuotedIdent if depth == 1 => { + let previous = p.peek_nth(n.wrapping_sub(1)); + typed |= n > 0 && is_name(previous); + } + _ => {} + } + n += 1; + } +} + +fn parse_typed_lambda_param<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(Ident<'a>, Option>)> { + let name = p.parse_ident()?; + let data_type = if p.at_op(",") || p.at_op(")") { + None + } else { + Some(D::parse_data_type(p)?) + }; + Ok((name, data_type)) +} + +pub fn parse_typed_lambda<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let parenthesized = p.eat_op("("); + let params = if parenthesized { + let params = p.parse_comma_separated(parse_typed_lambda_param)?; + p.expect_op(")")?; + params + } else { + vec![parse_typed_lambda_param(p)?] + }; + p.expect_op("->")?; + let body = p.parse_expr()?; + Ok(ext(ClickHouseExpr::TypedLambda(Box::new( + ClickHouseTypedLambda { + params, + parenthesized, + body, + }, + )))) +} + +/// True at a name followed by `.` and a tuple index, possibly after more names. +fn at_name_before_tuple_index<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if !is_name(p.peek()) || !p.peek_nth(1).is_op(".") { + return false; + } + let mut n = 1; + while p.peek_nth(n).is_op(".") { + let next = p.peek_nth(n + 1); + if next.kind == TokenKind::Number { + return true; + } + if !is_name(next) { + return false; + } + n += 2; + } + false +} + +/// Parses the name in `name.1`, leaving the point for the infix rule. +fn parse_name_before_tuple_index<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let first = p.parse_ident()?; + let mut parts = vec![first.clone()]; + while p.at_op(".") && p.peek_nth(1).kind != TokenKind::Number { + p.advance(); + parts.push(p.parse_name_part()?); + } + if parts.len() == 1 { + return Ok(ExprKind::Ident(first).into()); + } + Ok(ExprKind::Compound(ObjectName { parts }).into()) +} + +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_op("[") { + return p.without_context(IN_COLUMN_OPTION, parse_array_literal); + } + if p.at_op("{") { + return p.without_context(IN_COLUMN_OPTION, parse_dictionary); + } + if p.at_op("(") && p.has_context(IN_COLUMN_OPTION) { + return p.without_context(IN_COLUMN_OPTION, D::parse_prefix); + } + if at_typed_lambda(p) { + return parse_typed_lambda(p); + } + if at_name_before_tuple_index(p) { + return parse_name_before_tuple_index(p); + } + spark::parse_prefix(p) +} + +/// How deep a dialect node counts for, compared to a core one. +const EXT_LEVELS: usize = 2; + +fn parse_tuple_element<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.advance(); + let token = p.expect_kind(TokenKind::Number, "a tuple index")?; + p.deepen_by(EXT_LEVELS)?; + Ok(ext(ClickHouseExpr::TupleElement { + expr: Box::new(left), + index: token.text.into(), + })) +} + +fn parse_in_target<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.eat_op("(") { + return Ok(ClickHouseInTarget::List(vec![ + p.parse_expr_bp(prec::COMPARE)?, + ])); + } + if grammar::query_starts_at(p, 0) { + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + return Ok(ClickHouseInTarget::Subquery(Box::new(query))); + } + let list = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(ClickHouseInTarget::List(list)) +} + +fn parse_global_in<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.expect_keyword("GLOBAL")?; + let negated = p.eat_keyword("NOT"); + p.expect_keyword("IN")?; + let target = parse_in_target(p)?; + p.deepen_by(EXT_LEVELS)?; + Ok(ext(ClickHouseExpr::GlobalIn(Box::new( + ClickHouseGlobalIn { + expr: left, + negated, + target, + }, + )))) +} + +fn parse_bare_in<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + let negated = p.eat_keyword("NOT"); + p.expect_keyword("IN")?; + let item = p.parse_expr_bp(prec::COMPARE)?; + Ok(ExprKind::InList { + expr: Box::new(left), + list: vec![item], + negated, + } + .into()) +} + +fn parse_not_null<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.expect_keyword("NOT")?; + p.expect_keyword("NULL")?; + Ok(ExprKind::Is { + expr: Box::new(left), + test: IsTest::Null, + negated: true, + } + .into()) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + let token = p.peek(); + if token.kind == TokenKind::Op { + match token.text { + "==" => return Some(InfixRule::binary(prec::COMPARE, BinaryOp::Eq)), + "::" => { + return Some(InfixRule::custom( + prec::POSTFIX, + postgres::parse_double_colon, + )); + } + "." if p.peek_nth(1).kind == TokenKind::Number => { + return Some(InfixRule::custom(prec::POSTFIX, parse_tuple_element)); + } + _ => {} + } + } else if token.kind == TokenKind::Word { + let next = p.peek_nth(1); + if p.at_keyword("GLOBAL") + && (next.is_word("IN") || (next.is_word("NOT") && p.peek_nth(2).is_word("IN"))) + { + return Some(InfixRule::custom(prec::COMPARE, parse_global_in)); + } + if p.at_keyword("IN") && !next.is_op("(") { + return Some(InfixRule::custom(prec::COMPARE, parse_bare_in)); + } + if p.at_keyword("NOT") && next.is_word("IN") && !p.peek_nth(2).is_op("(") { + return Some(InfixRule::custom(prec::COMPARE, parse_bare_in)); + } + if p.at_keyword("NOT") && next.is_word("NULL") && !p.has_context(IN_COLUMN_OPTION) { + return Some(InfixRule::custom(prec::IS, parse_not_null)); + } + } + grammar::infix_rule(p) +} + +/// Parses `key = value, ...` after `SETTINGS`. +fn parse_settings_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.parse_comma_separated(|p| { + let name = p.parse_ident()?; + p.expect_op("=")?; + let value = p.parse_expr()?; + Ok(ClickHouseSetting { name, value }) + }) +} + +fn parse_optional_settings<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("SETTINGS") { + parse_settings_list(p) + } else { + Ok(Vec::new()) + } +} + +/// Parses `SETTINGS` and `FORMAT` at the end of a query. +pub fn parse_query_tail<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let settings = parse_optional_settings(p)?; + let format = if !p.eat_keyword("FORMAT") { + None + } else if p.eat_keyword("NULL") { + Some(ClickHouseFormat::Null) + } else { + Some(ClickHouseFormat::Name(p.parse_ident()?)) + }; + if settings.is_empty() && format.is_none() { + return Ok(BuiltinQueryTail(None)); + } + Ok(BuiltinQueryTail(Some(Box::new( + BuiltinQueryClauses::ClickHouse(ClickHouseQueryClauses { settings, format }), + )))) +} + +/// Parses what follows `LIMIT`: `n`, `offset, n`, `n BY columns` or +/// `n OFFSET m [BY columns]`. +pub fn parse_limit<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let count = p.parse_expr()?; + if p.eat_op(",") { + return Ok(Limit { + count: Some(p.parse_expr()?), + offset: Some(count), + offset_rows: OffsetRows::None, + offset_comma: true, + all: false, + by: Vec::new(), + }); + } + let mut by = if p.eat_keyword("BY") { + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + let mut limit = grammar::parse_limit_offset(p, count)?; + if by.is_empty() && limit.offset.is_some() && p.eat_keyword("BY") { + by = p.parse_comma_separated(Parser::parse_expr)?; + } + limit.by = by; + Ok(limit) +} + +fn parse_with_fill<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let from = if p.eat_keyword("FROM") { + Some(p.parse_expr()?) + } else { + None + }; + let to = if p.eat_keyword("TO") { + Some(p.parse_expr()?) + } else { + None + }; + let step = if p.eat_keyword("STEP") { + Some(p.parse_expr()?) + } else { + None + }; + Ok(ClickHouseWithFill { from, to, step }) +} + +fn parse_interpolate<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.eat_op("(") { + return Ok(ClickHouseInterpolate { exprs: None }); + } + if p.eat_op(")") { + return Ok(ClickHouseInterpolate { + exprs: Some(Vec::new()), + }); + } + let exprs = p.parse_comma_separated(|p| { + let column = p.parse_ident()?; + let expr = if p.eat_keyword("AS") { + Some(p.parse_expr()?) + } else { + None + }; + Ok((column, expr)) + })?; + p.expect_op(")")?; + Ok(ClickHouseInterpolate { exprs: Some(exprs) }) +} + +/// Parses an `ORDER BY` item, which can be `ALL` or end in `WITH FILL` and +/// `INTERPOLATE`. +pub fn parse_order_by_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let all = p.at_keyword("ALL") && !p.peek_nth(1).is_op("("); + let expr = if all { + let span = p.advance().span; + Expr::new(ext(ClickHouseExpr::All).kind, span) + } else { + p.parse_expr()? + }; + let (asc, nulls_first) = grammar::parse_order_by_modifiers(p)?; + if all && p.at_op(",") { + return Err(p.expected("nothing after ORDER BY ALL")); + } + let with_fill = if p.at_keyword("WITH") && p.peek_nth(1).is_word("FILL") { + p.advance(); + p.advance(); + Some(Box::new(parse_with_fill(p)?)) + } else { + None + }; + let interpolate = if p.eat_keyword("INTERPOLATE") { + let interpolate = parse_interpolate(p)?; + if p.at_op(",") { + return Err(p.expected("INTERPOLATE after the last item")); + } + Some(Box::new(interpolate)) + } else { + None + }; + Ok(OrderByItem { + using: None, + expr, + asc, + nulls_first, + ext: ClickHouseOrderByItem { + with_fill, + interpolate, + }, + }) +} + +/// Parses a `GROUP BY` item, which can be an empty `()`. +pub fn parse_group_by_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_op("(") && p.peek_nth(1).is_op(")") { + p.advance(); + p.advance(); + return Ok(ExprKind::Special(Box::new(SpecialExpr::Tuple(Vec::new()))).into()); + } + grammar::parse_grouping_item(p) +} + +fn at_group_by_modifier<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("WITH") + && (next.is_word("ROLLUP") || next.is_word("CUBE") || next.is_word("TOTALS")) +} + +/// Parses `WITH ROLLUP`, `WITH CUBE` and `WITH TOTALS`, any number of them. +pub fn parse_group_by_modifier<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option { + let mut modifiers = Vec::new(); + while at_group_by_modifier(p) { + p.advance(); + let word = p.advance(); + modifiers.push(if word.is_word("ROLLUP") { + GroupByModifier::Rollup + } else if word.is_word("CUBE") { + GroupByModifier::Cube + } else { + GroupByModifier::Totals + }); + } + match modifiers.len() { + 0 => None, + 1 => modifiers.pop(), + _ => Some(GroupByModifier::Chain(modifiers)), + } +} + +/// Parses a select item, in which a wildcard can have `EXCEPT` and `REPLACE`. +pub fn parse_select_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let item = grammar::parse_select_item(p)?; + let qualifier = match &item.kind { + SelectItemKind::Wildcard => None, + SelectItemKind::QualifiedWildcard(name) => Some(name.clone()), + _ => return Ok(item), + }; + let except_list = p.at_keyword("EXCEPT") && p.peek_nth(1).is_op("("); + let except_name = p.at_keyword("EXCEPT") + && !except_list + && is_name(p.peek_nth(1)) + && !p.peek_nth(1).is_word("SELECT"); + if !except_list && !except_name && !p.at_keyword("REPLACE") { + return Ok(item); + } + let mut options = WildcardOptions { + ilike: None, + exclude: Vec::new(), + exclude_parens: true, + except_keyword: true, + replace: Vec::new(), + rename: Vec::new(), + rename_parens: false, + }; + if except_list { + p.advance(); + options.exclude = grammar::parse_ident_list(p)?; + } else if except_name { + p.advance(); + options.exclude = vec![p.parse_ident()?]; + } + if p.at_keyword("REPLACE") { + options.replace = grammar::parse_wildcard_replace(p)?; + } + Ok(SelectItemKind::WildcardWithOptions { + qualifier, + options: Box::new(options), + } + .into()) +} + +/// True if the `(` that is `n` tokens ahead starts an argument list holding +/// `SETTINGS`. +fn call_has_settings<'a, D: Dialect>(p: &Parser<'a, D>, mut n: usize) -> bool { + let mut depth = 0usize; + loop { + let token = p.peek_nth(n); + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + depth -= 1; + if depth == 0 { + return false; + } + } + TokenKind::Word if depth == 1 && token.is_word("SETTINGS") => return true, + _ => {} + } + n += 1; + } +} + +/// True at a possibly qualified name whose arguments hold `SETTINGS`. +fn at_call_with_settings<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if !is_name(p.peek()) { + return false; + } + let mut n = 1; + while p.peek_nth(n).is_op(".") { + n += 2; + } + p.peek_nth(n).is_op("(") && call_has_settings(p, n) +} + +fn parse_settings_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + p.expect_op("(")?; + let mut args = Vec::new(); + let mut settings = Vec::new(); + loop { + if p.eat_keyword("SETTINGS") { + settings = parse_settings_list(p)?; + break; + } + args.push(p.parse_expr()?); + if !p.eat_op(",") { + break; + } + } + p.expect_op(")")?; + let span = p.span_since(name.parts[0].span.start); + let call = ext(ClickHouseExpr::SettingsCall(Box::new( + ClickHouseSettingsCall { + name, + args, + settings, + }, + ))); + Ok(Expr::new(call.kind, span)) +} + +/// Parses a table, whose name can be any word, and a call whose arguments can +/// end in `SETTINGS`. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + let reserved = token.kind == TokenKind::Word && D::is_reserved(token.text); + if !reserved && !at_call_with_settings(p) { + return grammar::parse_table_factor(p); + } + let mut parts = vec![p.parse_name_part()?]; + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + let name = ObjectName { parts }; + if !p.at_op("(") { + return Ok(TableFactor::Named(name)); + } + let call = if call_has_settings(p, 0) { + parse_settings_call(p, name)? + } else { + p.parse_function_call(name)? + }; + Ok(TableFactor::Function { + call: Box::new(call), + with_ordinality: false, + }) +} + +fn parse_sample<'a, D: Dialect>( + p: &mut Parser<'a, D>, + table: TableRef<'a, Builtin>, +) -> PResult> { + p.expect_keyword("SAMPLE")?; + let mut sample: SampleClause<'a, Builtin> = D::parse_sample_clause(p, false)?; + if p.eat_keyword("OFFSET") { + sample.offset = Some(Box::new(p.parse_expr()?)); + } + Ok(TableRef { + factor: TableFactor::Sampled(Box::new(TableSample { table, sample })), + alias: None, + span: Span::default(), + }) +} + +/// Parses a table with any alias and `SAMPLE` clause. +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let table = grammar::parse_table_ref(p)?; + if p.at_keyword("SAMPLE") { + return parse_sample(p, table); + } + Ok(table) +} + +/// Consumes the words of an array join, if one starts here. +fn parse_array_join_kind<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option> { + let (kind, words) = if p.at_keyword("ARRAY") && p.peek_nth(1).is_word("JOIN") { + ("ARRAY JOIN", 2) + } else if p.at_keyword("LEFT") + && p.peek_nth(1).is_word("ARRAY") + && p.peek_nth(2).is_word("JOIN") + { + ("LEFT ARRAY JOIN", 3) + } else if p.at_keyword("INNER") + && p.peek_nth(1).is_word("ARRAY") + && p.peek_nth(2).is_word("JOIN") + { + ("INNER ARRAY JOIN", 3) + } else { + return None; + }; + for _ in 0..words { + p.advance(); + } + Some(JoinKind::Custom(kind.into())) +} + +/// The keywords of a join after `GLOBAL`, which renders before them. +fn global_join_kind(kind: JoinKind, spelled_out: bool) -> Option<&'static str> { + Some(match (kind, spelled_out) { + (JoinKind::Inner, false) => "GLOBAL JOIN", + (JoinKind::Inner, true) => "GLOBAL INNER JOIN", + (JoinKind::Left, false) => "GLOBAL LEFT JOIN", + (JoinKind::Left, true) => "GLOBAL LEFT OUTER JOIN", + (JoinKind::Right, false) => "GLOBAL RIGHT JOIN", + (JoinKind::Right, true) => "GLOBAL RIGHT OUTER JOIN", + (JoinKind::Full, _) => "GLOBAL FULL JOIN", + (JoinKind::Cross, _) => "GLOBAL CROSS JOIN", + (JoinKind::Semi, _) => "GLOBAL SEMI JOIN", + (JoinKind::LeftSemi, _) => "GLOBAL LEFT SEMI JOIN", + (JoinKind::Anti, _) => "GLOBAL ANTI JOIN", + (JoinKind::LeftAnti, _) => "GLOBAL LEFT ANTI JOIN", + _ => return None, + }) +} + +/// Parses a join, which can be an `ARRAY JOIN` or start with `GLOBAL`. +pub fn parse_join<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.at_keyword("GLOBAL") { + p.advance(); + let Some(mut join) = spark::parse_join(p)? else { + return Err(p.expected("JOIN after GLOBAL")); + }; + let Some(kind) = global_join_kind(join.kind, join.spelled_out) else { + return Err(p.expected("a join type that GLOBAL can modify")); + }; + join.kind = JoinKind::Custom(kind.into()); + join.spelled_out = false; + return Ok(Some(join)); + } + if p.at_keyword("RIGHT") && p.peek_nth(2).is_word("JOIN") { + let kind = if p.peek_nth(1).is_word("SEMI") { + Some(JoinKind::RightSemi) + } else if p.peek_nth(1).is_word("ANTI") { + Some(JoinKind::RightAnti) + } else { + None + }; + if let Some(kind) = kind { + for _ in 0..3 { + p.advance(); + } + let table = p.parse_table_ref()?; + let constraint = grammar::parse_join_constraint(p)?; + return Ok(Some(Join { + kind, + spelled_out: false, + table, + constraint, + })); + } + } + let Some(kind) = parse_array_join_kind(p) else { + return spark::parse_join(p); + }; + let table = p.parse_table_ref()?; + Ok(Some(Join { + kind, + spelled_out: false, + table, + constraint: JoinConstraint::None, + })) +} + +/// Parses a call, which can have a second argument list: `quantile(0.5)(x)`. +pub fn parse_function_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + let first = grammar::parse_function_call(p, name)?; + if !p.at_op("(") { + return Ok(first); + } + let ExprKind::Function { + name, + args: parameters, + options: None, + } = first.kind + else { + return Ok(first); + }; + let second = grammar::parse_function_call(p, name)?; + let ExprKind::Function { + name, + args, + options, + } = second.kind + else { + return Err(p.expected("a function call")); + }; + let mut options = options.unwrap_or_else(|| { + Box::new(FunctionOptions { + inner_null_treatment: None, + parameters: Vec::new(), + quantifier: SetQuantifier::None, + order_by: Vec::new(), + within_group: Vec::new(), + filter: None, + null_treatment: None, + separator: None, + on_overflow: None, + over: None, + }) + }); + options.parameters = parameters; + Ok(ExprKind::Function { + name, + args, + options: Some(options), + } + .into()) +} + +/// Parses `ON CLUSTER name` if present; the name can be a string. +fn parse_on_cluster<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !(p.at_keyword("ON") && p.peek_nth(1).is_word("CLUSTER")) { + return Ok(None); + } + p.advance(); + p.advance(); + let token = p.peek(); + if !matches!( + token.kind, + TokenKind::Word | TokenKind::QuotedIdent | TokenKind::String + ) { + return Err(p.expected("a cluster name")); + } + parse_name_or_string(p).map(Some) +} + +fn parse_sorting_key<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.eat_op("(") { + return p.parse_expr().map(ClickHouseSortingKey::One); + } + if p.eat_op(")") { + return Ok(ClickHouseSortingKey::Many(Vec::new())); + } + let keys = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(ClickHouseSortingKey::Many(keys)) +} + +/// Types the original crate spells in a fixed case, whatever case they are +/// written in. Anything else keeps its source text. +const CANONICAL_TYPES: [&str; 53] = [ + "Array", + "Nullable", + "LowCardinality", + "Map", + "Tuple", + "Nested", + "Int16", + "Int32", + "Int128", + "Int256", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "UInt128", + "UInt256", + "Float32", + "Date32", + "DateTime64", + "FixedString", + "BOOL", + "BOOLEAN", + "INT", + "INTEGER", + "TINYINT", + "SMALLINT", + "MEDIUMINT", + "BIGINT", + "HUGEINT", + "INT2", + "INT4", + "INT8", + "INT64", + "FLOAT", + "REAL", + "FLOAT4", + "FLOAT8", + "FLOAT64", + "DOUBLE", + "UUID", + "DATE", + "DATETIME", + "TIMESTAMP", + "TIME", + "JSON", + "TEXT", + "STRING", + "VARCHAR", + "CHAR", + "NUMERIC", + "DECIMAL", + "BINARY", + "BLOB", +]; + +fn canonical_type_name(text: &str) -> Option<&'static str> { + CANONICAL_TYPES + .iter() + .copied() + .find(|name| name.eq_ignore_ascii_case(text)) +} + +/// Parses the fields in `Tuple(a Int8)` or `Nested(a Int8)`. +fn parse_type_fields<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.parse_comma_separated(|p| { + let name = p.parse_ident()?; + let data_type = p.nested(D::parse_data_type)?; + Ok(StructField { + options: Vec::new(), + name: Some(name), + colon: false, + data_type, + not_null: false, + comment: None, + }) + }) +} + +/// True if `(` at the cursor holds anything but numbers separated by commas, +/// which the core reads itself. +fn at_type_arguments<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if p.peek_nth(1).is_op(")") { + return true; + } + let mut depth = 0usize; + let mut n = 0; + loop { + let token = p.peek_nth(n); + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + depth -= 1; + if depth == 0 { + return false; + } + } + TokenKind::Number => {} + TokenKind::Op if depth == 1 && token.text == "," => {} + _ => return true, + } + n += 1; + } +} + +/// Parses `(...)` holding type modifiers or struct fields. +fn parse_type_arguments<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Ident<'a>, +) -> PResult> { + p.expect_op("(")?; + let mut data_type = bare_type(name); + if p.eat_op(")") { + data_type.angle = Some(Box::new(AngleArguments::ParenTypes(Vec::new()))); + return Ok(data_type); + } + let token = p.peek(); + let next = p.peek_nth(1); + if is_name(token) && !next.is_op(",") && !next.is_op(")") { + let fields = p.parse_comma_separated(|p| { + let field_name = p.parse_ident()?; + let field_type = p.nested(D::parse_data_type)?; + let not_null = p.eat_keyword("NOT"); + if not_null { + p.expect_keyword("NULL")?; + } + Ok(StructField { + options: Vec::new(), + name: Some(field_name), + colon: false, + data_type: field_type, + not_null, + comment: None, + }) + })?; + p.expect_op(")")?; + data_type.angle = Some(Box::new(AngleArguments::ParenFields(fields))); + return Ok(data_type); + } + data_type.args = p + .parse_comma_separated(|p| { + let token = p.peek(); + if !matches!( + token.kind, + TokenKind::Number | TokenKind::String | TokenKind::Word | TokenKind::QuotedIdent + ) { + return Err(p.expected("a type modifier")); + } + p.advance(); + Ok(token.text) + })? + .into_iter() + .map(Cow::Borrowed) + .collect(); + p.expect_op(")")?; + Ok(data_type) +} + +fn bare_type(name: Ident<'_>) -> DataType<'_> { + DataType { + qualifier: Vec::new(), + name, + angle: None, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: crate::ast::ArrayType::None, + } +} + +fn parse_container_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Ident<'a>, + canonical: &str, +) -> PResult> { + p.expect_op("(")?; + let mut data_type = bare_type(name); + let arguments = match canonical { + "Nested" => AngleArguments::ParenFields(parse_type_fields(p)?), + "Tuple" => { + let next = p.peek_nth(1); + if is_name(p.peek()) && !next.is_op(",") && !next.is_op(")") && !next.is_op("(") { + AngleArguments::ParenFields(parse_type_fields(p)?) + } else { + AngleArguments::ParenTypes( + p.parse_comma_separated(|p| p.nested(D::parse_data_type))?, + ) + } + } + _ => AngleArguments::ParenTypes(p.parse_comma_separated(|p| p.nested(D::parse_data_type))?), + }; + p.expect_op(")")?; + data_type.angle = Some(Box::new(arguments)); + Ok(data_type) +} + +/// Parses a data type, including the parenthesized containers and the known +/// types the original crate renders in a fixed case. +pub fn parse_data_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let written = p.parse_ident()?; + let canonical = written + .quote + .is_none() + .then(|| canonical_type_name(&written.text)) + .flatten(); + let name = match canonical { + Some(text) => Ident { + text: text.into(), + ..written + }, + None => written, + }; + match canonical { + Some( + container @ ("Array" | "Nullable" | "LowCardinality" | "Map" | "Tuple" | "Nested"), + ) => parse_container_type(p, name, container), + _ if p.at_op("(") && at_type_arguments(p) => parse_type_arguments(p, name), + _ => grammar::parse_data_type_after_name(p, name), + } +} + +/// Parses `DEFAULT`, `MATERIALIZED`, `ALIAS` and `EPHEMERAL` here, so that +/// their expressions leave a following `NOT NULL` to the column. +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let parse_expr = |p: &mut Parser<'a, D>| p.with_context(IN_COLUMN_OPTION, Parser::parse_expr); + if p.eat_keyword("DEFAULT") { + return parse_expr(p).map(|expr| Some(ColumnOption::Default(expr))); + } + for keyword in ["MATERIALIZED", "ALIAS"] { + if p.eat_keyword(keyword) { + let expr = parse_expr(p)?; + return Ok(Some(ColumnOption::Keyword { + keyword: keyword.into(), + expr: Some(expr), + })); + } + } + if p.eat_keyword("EPHEMERAL") { + let expr = if p.at_op(",") || p.at_op(")") { + None + } else { + Some(parse_expr(p)?) + }; + return Ok(Some(ColumnOption::Keyword { + keyword: "EPHEMERAL".into(), + expr, + })); + } + spark::parse_column_option(p) +} + +fn parse_engine<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ENGINE")?; + p.eat_op("="); + let name = p.parse_ident()?; + let args = if p.eat_op("(") { + if p.eat_op(")") { + Vec::new() + } else { + let args = p.parse_comma_separated(parse_name_or_string)?; + p.expect_op(")")?; + args + } + } else { + Vec::new() + }; + Ok(ClickHouseEngine { name, args }) +} + +fn parse_on_commit<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !(p.at_keyword("ON") && p.peek_nth(1).is_word("COMMIT")) { + return Ok(None); + } + p.advance(); + p.advance(); + if p.eat_keyword("DELETE") { + p.expect_keyword("ROWS")?; + return Ok(Some("DELETE ROWS")); + } + if p.eat_keyword("PRESERVE") { + p.expect_keyword("ROWS")?; + return Ok(Some("PRESERVE ROWS")); + } + p.expect_keyword("DROP")?; + Ok(Some("DROP")) +} + +/// Flags written before `TABLE` or `VIEW`. +struct CreateHead { + or_replace: bool, + scope: Option<&'static str>, + temporary: bool, +} + +fn parse_create_head<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let scope = if p.eat_keyword("LOCAL") { + Some("LOCAL") + } else if p.eat_keyword("GLOBAL") { + Some("GLOBAL") + } else { + None + }; + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + Ok(CreateHead { + or_replace, + scope, + temporary, + }) +} + +fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + head: CreateHead, +) -> PResult> { + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let on_cluster = parse_on_cluster(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let engine = if p.at_keyword("ENGINE") { + Some(parse_engine(p)?) + } else { + None + }; + let mut partition_by = if p.at_keyword("PARTITION") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + Some(p.parse_expr()?) + } else { + None + }; + let primary_key = if p.at_keyword("PRIMARY") && p.peek_nth(1).is_word("KEY") { + p.advance(); + p.advance(); + Some(p.parse_expr()?) + } else { + None + }; + let order_by = if p.at_keyword("ORDER") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + Some(parse_sorting_key(p)?) + } else { + None + }; + if partition_by.is_none() && p.at_keyword("PARTITION") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + partition_by = Some(p.parse_expr()?); + } + let on_commit = parse_on_commit(p)?; + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() && engine.is_none() { + return Err(p.expected("column definitions, ENGINE or AS")); + } + let table = CreateTable { + or_replace: head.or_replace, + temporary: head.temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + let plain = head.scope.is_none() + && on_cluster.is_none() + && engine.is_none() + && primary_key.is_none() + && order_by.is_none() + && partition_by.is_none() + && on_commit.is_none(); + if plain { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + Ok(statement(ClickHouseStatement::CreateTable(Box::new( + ClickHouseCreateTable { + table, + scope: head.scope.map(Cow::Borrowed), + on_cluster, + engine, + primary_key, + order_by, + partition_by, + on_commit: on_commit.map(Cow::Borrowed), + }, + )))) +} + +fn parse_create_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, + head: CreateHead, +) -> PResult> { + let materialized = p.eat_keyword("MATERIALIZED"); + p.expect_keyword("VIEW")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let columns = if p.at_op("(") { + p.advance(); + let columns = p.parse_comma_separated(D::parse_column_def)?; + p.expect_op(")")?; + columns + } else { + Vec::new() + }; + let to = if p.eat_keyword("TO") { + Some(grammar::parse_object_name(p)?) + } else { + None + }; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + if columns.is_empty() && to.is_none() { + return Ok(StatementKind::CreateView(Box::new(CreateView { + or_replace: head.or_replace, + temporary: head.temporary, + materialized, + if_not_exists, + name, + columns: Vec::new(), + with: Vec::new(), + query, + no_schema_binding: false, + })) + .into()); + } + Ok(statement(ClickHouseStatement::CreateView(Box::new( + ClickHouseCreateView { + or_replace: head.or_replace, + materialized, + if_not_exists, + name, + columns, + to, + query, + }, + )))) +} + +/// True at `CREATE ... {TABLE | VIEW | MATERIALIZED}`. +fn at_create_table_or_view<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + if p.peek_nth(n).is_word("LOCAL") || p.peek_nth(n).is_word("GLOBAL") { + n += 1; + } + if p.peek_nth(n).is_word("TEMPORARY") || p.peek_nth(n).is_word("TEMP") { + n += 1; + } + let object = p.peek_nth(n); + object.is_word("TABLE") || object.is_word("VIEW") || object.is_word("MATERIALIZED") +} + +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !at_create_table_or_view(p) { + return grammar::parse_create(p); + } + let head = parse_create_head(p)?; + if p.at_keyword("TABLE") { + parse_create_table(p, head) + } else { + parse_create_view(p, head) + } +} + +fn parse_partition<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let part = p.eat_keyword("PART"); + if !part { + p.expect_keyword("PARTITION")?; + } + Ok(ClickHousePartition { + part, + expr: p.parse_expr()?, + }) +} + +fn parse_projection_partition<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.eat_keyword("IN") { + return Ok(None); + } + p.expect_keyword("PARTITION")?; + p.parse_ident().map(Some) +} + +fn parse_add_projection<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = p.parse_ident()?; + p.expect_op("(")?; + p.expect_keyword("SELECT")?; + let projection = D::parse_projection(p)?; + let group_by = if p.at_keyword("GROUP") { + p.advance(); + p.expect_keyword("BY")?; + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + let order_by = if p.at_keyword("ORDER") { + p.advance(); + p.expect_keyword("BY")?; + p.parse_comma_separated(D::parse_order_by_item)? + } else { + Vec::new() + }; + p.expect_op(")")?; + Ok(ClickHouseProjection { + if_not_exists, + name, + projection, + group_by, + order_by, + }) +} + +fn parse_with_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.eat_keyword("WITH") { + return Ok(None); + } + p.expect_keyword("NAME")?; + let token = p.peek(); + if !matches!( + token.kind, + TokenKind::Word | TokenKind::QuotedIdent | TokenKind::String + ) { + return Err(p.expected("a name")); + } + parse_name_or_string(p).map(Some) +} + +/// Parses an operation of `ALTER TABLE`, trying ClickHouse's before the core's. +pub fn parse_alter_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if p.at_keyword("ADD") && next.is_word("PROJECTION") { + p.advance(); + p.advance(); + return parse_add_projection(p).map(|add| ClickHouseAlterOp::AddProjection(Box::new(add))); + } + if p.at_keyword("DROP") && next.is_word("PROJECTION") { + p.advance(); + p.advance(); + let if_exists = grammar::parse_if_exists(p); + let name = p.parse_ident()?; + return Ok(ClickHouseAlterOp::DropProjection { if_exists, name }); + } + if p.at_keyword("CLEAR") && next.is_word("PROJECTION") { + p.advance(); + p.advance(); + let if_exists = grammar::parse_if_exists(p); + let name = p.parse_ident()?; + let partition = parse_projection_partition(p)?; + return Ok(ClickHouseAlterOp::ClearProjection { + if_exists, + name, + partition, + }); + } + if p.at_keyword("MATERIALIZE") && next.is_word("PROJECTION") { + p.advance(); + p.advance(); + let if_exists = grammar::parse_if_exists(p); + let name = p.parse_ident()?; + let partition = parse_projection_partition(p)?; + return Ok(ClickHouseAlterOp::MaterializeProjection { + if_exists, + name, + partition, + }); + } + if p.eat_keyword("ATTACH") { + return parse_partition(p).map(ClickHouseAlterOp::Attach); + } + if p.eat_keyword("DETACH") { + return parse_partition(p).map(ClickHouseAlterOp::Detach); + } + if p.eat_keyword("FREEZE") { + let partition = parse_partition(p)?; + let with_name = parse_with_name(p)?; + return Ok(ClickHouseAlterOp::Freeze { + partition, + with_name, + }); + } + if p.eat_keyword("UNFREEZE") { + let partition = parse_partition(p)?; + let with_name = parse_with_name(p)?; + return Ok(ClickHouseAlterOp::Unfreeze { + partition, + with_name, + }); + } + if p.at_keyword("MODIFY") && next.is_word("ORDER") { + p.advance(); + p.advance(); + p.expect_keyword("BY")?; + return parse_sorting_key(p).map(ClickHouseAlterOp::ModifyOrderBy); + } + if p.eat_keyword("MODIFY") { + p.eat_keyword("COLUMN"); + let column = D::parse_column_def(p)?; + let position = mysql::parse_column_position(p)?; + return Ok(ClickHouseAlterOp::Core(AlterTableOp::ModifyColumn { + column, + position, + })); + } + let mut operation = D::parse_alter_table_op(p)?; + if let AlterTableOp::AddColumn { position, .. } = &mut operation { + *position = mysql::parse_column_position(p)?; + } + Ok(ClickHouseAlterOp::Core(operation)) +} + +fn parse_alter_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ALTER")?; + p.expect_keyword("TABLE")?; + let if_exists = grammar::parse_if_exists(p); + let name = grammar::parse_object_name(p)?; + let on_cluster = parse_on_cluster(p)?; + let operations = p.parse_comma_separated(parse_alter_op)?; + let all_core = operations + .iter() + .all(|operation| matches!(operation, ClickHouseAlterOp::Core(_))); + if on_cluster.is_none() && all_core { + let operations = operations + .into_iter() + .filter_map(|operation| match operation { + ClickHouseAlterOp::Core(operation) => Some(operation), + _ => None, + }) + .collect(); + return Ok(StatementKind::AlterTable(Box::new(AlterTable { + if_exists, + only: false, + name, + operations, + })) + .into()); + } + Ok(statement(ClickHouseStatement::AlterTable(Box::new( + ClickHouseAlterTable { + if_exists, + name, + on_cluster, + operations, + }, + )))) +} + +fn parse_kill<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("KILL")?; + let kind = ["CONNECTION", "QUERY", "MUTATION"] + .into_iter() + .find(|kind| p.eat_keyword(kind)); + let id = grammar::parse_number(p)?; + Ok(ClickHouseStatement::Kill { + kind: kind.map(Cow::Borrowed), + id: id.into(), + }) +} + +fn parse_optimize<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("OPTIMIZE")?; + p.expect_keyword("TABLE")?; + let name = grammar::parse_object_name(p)?; + let on_cluster = parse_on_cluster(p)?; + let partition = if p.eat_keyword("PARTITION") { + if p.eat_keyword("ID") { + let token = p.peek(); + if !at_dictionary_key_token(token) { + return Err(p.expected("a partition id")); + } + Some(ClickHouseOptimizePartition::Id(parse_name_or_string(p)?)) + } else { + Some(ClickHouseOptimizePartition::Expr(p.parse_expr()?)) + } + } else { + None + }; + let include_final = p.eat_keyword("FINAL"); + let deduplicate = if p.eat_keyword("DEDUPLICATE") { + if p.eat_keyword("BY") { + Some(Deduplicate::By(p.parse_expr()?)) + } else { + Some(Deduplicate::All) + } + } else { + None + }; + Ok(ClickHouseStatement::Optimize(Box::new( + ClickHouseOptimize { + name, + on_cluster, + partition, + include_final, + deduplicate, + }, + ))) +} + +fn parse_delete<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DELETE")?; + p.expect_keyword("FROM")?; + let table = p.parse_table_ref()?; + let on_cluster = parse_on_cluster(p)?; + let selection = if p.eat_keyword("WHERE") { + Some(p.parse_expr()?) + } else { + None + }; + let settings = parse_optional_settings(p)?; + if on_cluster.is_none() && settings.is_empty() { + return Ok(StatementKind::Delete(Box::new(Delete { + output: None, + multi: None, + using: Vec::new(), + table, + selection, + order_by: Vec::new(), + limit: None, + returning: Vec::new(), + })) + .into()); + } + Ok(statement(ClickHouseStatement::Delete(Box::new( + ClickHouseDelete { + table, + on_cluster, + selection, + settings, + }, + )))) +} + +fn parse_update<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("UPDATE")?; + let table = p.parse_table_ref()?; + let on_cluster = parse_on_cluster(p)?; + p.expect_keyword("SET")?; + let assignments = p.parse_comma_separated(D::parse_assignment)?; + let selection = if p.eat_keyword("WHERE") { + Some(p.parse_expr()?) + } else { + None + }; + let settings = parse_optional_settings(p)?; + if on_cluster.is_none() && settings.is_empty() { + return Ok(StatementKind::Update(Box::new(Update { + output: None, + from: Vec::new(), + from_before_set: false, + table, + joins: Vec::new(), + assignments, + selection, + order_by: Vec::new(), + limit: None, + returning: Vec::new(), + })) + .into()); + } + Ok(statement(ClickHouseStatement::Update(Box::new( + ClickHouseUpdate { + table, + on_cluster, + assignments, + selection, + settings, + }, + )))) +} + +fn parse_input_format<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let token = p.peek(); + let has_values = !(token.kind == TokenKind::Eof || token.is_op(";")); + let values = if has_values { + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + Ok(ClickHouseInputFormat { name, values }) +} + +/// Parses `INSERT`, which can target a function and end in `SETTINGS` and +/// `FORMAT`. +pub fn parse_insert_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INSERT")?; + p.expect_keyword("INTO")?; + let table_keyword = p.eat_keyword("TABLE"); + let target = if p.eat_keyword("FUNCTION") { + let name = grammar::parse_object_name(p)?; + ClickHouseInsertTarget::Function(Box::new(p.parse_function_call(name)?)) + } else { + ClickHouseInsertTarget::Table(grammar::parse_object_name(p)?) + }; + let columns = if grammar::at_column_list(p) { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let source = if p.at_keyword("SETTINGS") || p.at_keyword("FORMAT") { + None + } else { + Some(grammar::parse_insert_source(p)?) + }; + let settings = parse_optional_settings(p)?; + let format = if p.eat_keyword("FORMAT") { + Some(parse_input_format(p)?) + } else { + None + }; + if let (false, ClickHouseInsertTarget::Table(table), Some(source), true, None) = ( + table_keyword, + &target, + &source, + settings.is_empty(), + &format, + ) { + return Ok(StatementKind::Insert(Box::new(Insert { + into: true, + output: None, + modifiers: Default::default(), + table: table.clone(), + columns, + source: source.clone(), + returning: Vec::new(), + })) + .into()); + } + Ok(statement(ClickHouseStatement::Insert(Box::new( + ClickHouseInsert { + table_keyword, + target, + columns, + source, + settings, + format, + }, + )))) +} + +/// Parses a table constraint. `CONSTRAINT` always starts one, unlike in the +/// core, where it is otherwise a column's name. +pub fn parse_table_constraint<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let third = p.peek_nth(2); + let known = ["PRIMARY", "UNIQUE", "CHECK", "FOREIGN"] + .iter() + .any(|word| third.is_word(word)); + if p.at_keyword("CONSTRAINT") && !known { + return Err(p.expected("a table constraint after CONSTRAINT")); + } + grammar::parse_table_constraint(p) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("KILL") { + return parse_kill(p).map(statement); + } + if p.at_keyword("OPTIMIZE") { + return parse_optimize(p).map(statement); + } + if p.at_keyword("ALTER") && p.peek_nth(1).is_word("TABLE") { + return parse_alter_table(p); + } + if p.at_keyword("DELETE") { + return parse_delete(p); + } + if p.at_keyword("UPDATE") { + return parse_update(p); + } + if p.at_keyword("TRUNCATE") { + let truncate = grammar::parse_truncate(p)?; + let Some(on_cluster) = parse_on_cluster(p)? else { + return Ok(StatementKind::Truncate(Box::new(truncate)).into()); + }; + return Ok(statement(ClickHouseStatement::TruncateOnCluster(Box::new( + ClickHouseTruncate { + truncate, + on_cluster, + }, + )))); + } + grammar::parse_statement(p) +} + +/// Parses what `EXPLAIN` or `DESCRIBE` applies to, which can start with `TABLE`. +pub fn parse_explain_target<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("TABLE") { + return Ok(ExplainTarget::Table { + table_keyword: true, + name: grammar::parse_object_name(p)?, + }); + } + grammar::parse_explain_target(p) +} + +impl Dialect for ClickHouse { + type Ext = Builtin; + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, true) + } + + fn parse_qualify<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + snowflake::parse_qualify(p) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + !word.eq_ignore_ascii_case("ALL") && grammar::is_reserved(word) + } + + #[inline] + fn lex_after(prev: Option>, rest: &str) -> Option { + lex_after(prev, rest) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + lex_comment(rest) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + is_reserved_for_alias(word) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + StringLiteral { + backslash_escapes: true, + ..grammar::string_literal(token) + } + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_table_constraint<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_table_constraint(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn at_from_first<'a>(p: &Parser<'a, Self>, n: usize) -> bool { + p.peek_nth(n).is_word("FROM") + } + + fn parse_select<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if p.at_keyword("FROM") { + grammar::parse_from_first_select(p) + } else { + grammar::parse_select(p) + } + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_prewhere<'a>(p: &mut Parser<'a, Self>) -> PResult>>> { + if p.eat_keyword("PREWHERE") { + p.parse_expr().map(|expr| Some(Box::new(expr))) + } else { + Ok(None) + } + } + + fn parse_query_tail<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_query_tail(p) + } + + fn parse_limit<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_limit(p) + } + + fn parse_order_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_order_by_item(p) + } + + fn eat_group_by_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_group_by_item(p) + } + + fn parse_group_by_modifier<'a>(p: &mut Parser<'a, Self>) -> Option { + parse_group_by_modifier(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_join(p) + } + + fn parse_function_call<'a>( + p: &mut Parser<'a, Self>, + name: ObjectName<'a>, + ) -> PResult> { + parse_function_call(p, name) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_explain_target<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_explain_target(p) + } +} + +impl fmt::Display for ClickHouseSetting<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} = {}", self.name, self.value) + } +} + +impl fmt::Display for ClickHouseFormat<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Name(name) => name.fmt(f), + Self::Null => f.write_str("NULL"), + } + } +} + +impl fmt::Display for ClickHouseQueryClauses<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if !self.settings.is_empty() { + write!(f, " SETTINGS {}", comma(&self.settings))?; + } + if let Some(format) = &self.format { + write!(f, " FORMAT {format}")?; + } + Ok(()) + } +} + +impl fmt::Display for ClickHouseWithFill<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(" WITH FILL")?; + if let Some(from) = &self.from { + write!(f, " FROM {from}")?; + } + if let Some(to) = &self.to { + write!(f, " TO {to}")?; + } + if let Some(step) = &self.step { + write!(f, " STEP {step}")?; + } + Ok(()) + } +} + +impl fmt::Display for ClickHouseInterpolate<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(" INTERPOLATE")?; + let Some(exprs) = &self.exprs else { + return Ok(()); + }; + f.write_str(" (")?; + for (i, (column, expr)) in exprs.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + column.fmt(f)?; + if let Some(expr) = expr { + write!(f, " AS {expr}")?; + } + } + f.write_str(")") + } +} + +impl fmt::Display for ClickHouseOrderByItem<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(with_fill) = &self.with_fill { + with_fill.fmt(f)?; + } + if let Some(interpolate) = &self.interpolate { + interpolate.fmt(f)?; + } + Ok(()) + } +} + +impl fmt::Display for ClickHouseSortingKey<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::One(expr) => expr.fmt(f), + Self::Many(exprs) => write!(f, "({})", comma(exprs)), + } + } +} + +impl fmt::Display for ClickHousePartition<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let keyword = if self.part { "PART" } else { "PARTITION" }; + write!(f, "{keyword} {}", self.expr) + } +} + +fn write_projection_partition( + f: &mut fmt::Formatter<'_>, + partition: &Option>, +) -> fmt::Result { + match partition { + Some(partition) => write!(f, " IN PARTITION {partition}"), + None => Ok(()), + } +} + +fn write_with_name(f: &mut fmt::Formatter<'_>, with_name: &Option>) -> fmt::Result { + match with_name { + Some(name) => write!(f, " WITH NAME {name}"), + None => Ok(()), + } +} + +impl fmt::Display for ClickHouseProjection<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ADD PROJECTION ")?; + write_if_not_exists(f, self.if_not_exists)?; + write!(f, "{} (SELECT {}", self.name, comma(&self.projection))?; + if !self.group_by.is_empty() { + write!(f, " GROUP BY {}", comma(&self.group_by))?; + } + if !self.order_by.is_empty() { + write!(f, " ORDER BY {}", comma(&self.order_by))?; + } + f.write_str(")") + } +} + +impl fmt::Display for ClickHouseAlterOp<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Core(operation) => operation.fmt(f), + Self::AddProjection(projection) => projection.fmt(f), + Self::DropProjection { if_exists, name } => { + f.write_str("DROP PROJECTION ")?; + write_if_exists(f, *if_exists)?; + name.fmt(f) + } + Self::ClearProjection { + if_exists, + name, + partition, + } => { + f.write_str("CLEAR PROJECTION ")?; + write_if_exists(f, *if_exists)?; + name.fmt(f)?; + write_projection_partition(f, partition) + } + Self::MaterializeProjection { + if_exists, + name, + partition, + } => { + f.write_str("MATERIALIZE PROJECTION ")?; + write_if_exists(f, *if_exists)?; + name.fmt(f)?; + write_projection_partition(f, partition) + } + Self::Attach(partition) => write!(f, "ATTACH {partition}"), + Self::Detach(partition) => write!(f, "DETACH {partition}"), + Self::Freeze { + partition, + with_name, + } => { + write!(f, "FREEZE {partition}")?; + write_with_name(f, with_name) + } + Self::Unfreeze { + partition, + with_name, + } => { + write!(f, "UNFREEZE {partition}")?; + write_with_name(f, with_name) + } + Self::ModifyOrderBy(key) => write!(f, "MODIFY ORDER BY {key}"), + } + } +} + +fn write_on_cluster(f: &mut fmt::Formatter<'_>, on_cluster: &Option>) -> fmt::Result { + match on_cluster { + Some(cluster) => write!(f, " ON CLUSTER {cluster}"), + None => Ok(()), + } +} + +impl fmt::Display for ClickHouseAlterTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ALTER TABLE ")?; + write_if_exists(f, self.if_exists)?; + self.name.fmt(f)?; + write_on_cluster(f, &self.on_cluster)?; + write!(f, " {}", comma(&self.operations)) + } +} + +impl fmt::Display for ClickHouseEngine<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ENGINE = {}", self.name)?; + if !self.args.is_empty() { + write!(f, "({})", comma(&self.args))?; + } + Ok(()) + } +} + +impl fmt::Display for ClickHouseCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + f.write_str("CREATE ")?; + if table.or_replace { + f.write_str("OR REPLACE ")?; + } + if let Some(ref scope) = self.scope { + write!(f, "{scope} ")?; + } + if table.temporary { + f.write_str("TEMPORARY ")?; + } + f.write_str("TABLE ")?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + write_on_cluster(f, &self.on_cluster)?; + if !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + if let Some(engine) = &self.engine { + write!(f, " {engine}")?; + } + if let Some(primary_key) = &self.primary_key { + write!(f, " PRIMARY KEY {primary_key}")?; + } + if let Some(order_by) = &self.order_by { + write!(f, " ORDER BY {order_by}")?; + } + if let Some(partition_by) = &self.partition_by { + write!(f, " PARTITION BY {partition_by}")?; + } + if let Some(ref on_commit) = self.on_commit { + write!(f, " ON COMMIT {on_commit}")?; + } + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} + +impl fmt::Display for ClickHouseCreateView<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_create_flags(f, self.or_replace, false)?; + f.write_str(if self.materialized { + "MATERIALIZED VIEW " + } else { + "VIEW " + })?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + if let Some(to) = &self.to { + write!(f, " TO {to}")?; + } + crate::display::write_view_query(f, &self.query) + } +} + +impl fmt::Display for ClickHouseInsertTarget<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Table(name) => name.fmt(f), + Self::Function(call) => write!(f, "FUNCTION {call}"), + } + } +} + +impl fmt::Display for ClickHouseInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("INSERT INTO ")?; + if self.table_keyword { + f.write_str("TABLE ")?; + } + self.target.fmt(f)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + if let Some(source) = &self.source { + crate::display::write_insert_source(f, source, !self.columns.is_empty())?; + } + let settings_on_new_line = !self.columns.is_empty(); + if !self.settings.is_empty() { + if settings_on_new_line { + SpaceOrNewline.fmt(f)?; + } else { + f.write_str(" ")?; + } + write!(f, "SETTINGS {}", comma(&self.settings))?; + } + if let Some(format) = &self.format { + if settings_on_new_line || !self.settings.is_empty() { + SpaceOrNewline.fmt(f)?; + } else { + f.write_str(" ")?; + } + write!(f, "FORMAT {}", format.name)?; + if !format.values.is_empty() { + write!(f, " {}", comma(&format.values))?; + } + } + Ok(()) + } +} + +impl fmt::Display for ClickHouseUpdate<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "UPDATE {}", self.table)?; + write_on_cluster(f, &self.on_cluster)?; + write_list_clause(f, "SET", &self.assignments)?; + write_where_clause(f, &self.selection)?; + write_list_clause(f, "SETTINGS", &self.settings) + } +} + +impl fmt::Display for ClickHouseDelete<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("DELETE FROM")?; + SpaceOrNewline.fmt(f)?; + Indent(&self.table).fmt(f)?; + write_on_cluster(f, &self.on_cluster)?; + write_where_clause(f, &self.selection)?; + write_list_clause(f, "SETTINGS", &self.settings) + } +} + +impl fmt::Display for ClickHouseOptimize<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "OPTIMIZE TABLE {}", self.name)?; + write_on_cluster(f, &self.on_cluster)?; + match &self.partition { + Some(ClickHouseOptimizePartition::Expr(expr)) => write!(f, " PARTITION {expr}")?, + Some(ClickHouseOptimizePartition::Id(id)) => write!(f, " PARTITION ID {id}")?, + None => {} + } + if self.include_final { + f.write_str(" FINAL")?; + } + match &self.deduplicate { + Some(Deduplicate::All) => f.write_str(" DEDUPLICATE"), + Some(Deduplicate::By(expr)) => write!(f, " DEDUPLICATE BY {expr}"), + None => Ok(()), + } + } +} + +impl fmt::Display for ClickHouseStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TruncateOnCluster(truncate) => { + write!( + f, + "{} ON CLUSTER {}", + truncate.truncate, truncate.on_cluster + ) + } + Self::Kill { kind, id } => match kind { + Some(kind) => write!(f, "KILL {kind} {id}"), + None => write!(f, "KILL {id}"), + }, + Self::Optimize(optimize) => optimize.fmt(f), + Self::AlterTable(alter) => alter.fmt(f), + Self::CreateTable(create) => create.fmt(f), + Self::CreateView(create) => create.fmt(f), + Self::Insert(insert) => insert.fmt(f), + Self::Update(update) => update.fmt(f), + Self::Delete(delete) => delete.fmt(f), + } + } +} + +impl fmt::Display for ClickHouseGlobalIn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let not = if self.negated { "NOT " } else { "" }; + write!(f, "{} GLOBAL {not}IN ", self.expr)?; + match &self.target { + ClickHouseInTarget::List(items) => write!(f, "({})", comma(items)), + ClickHouseInTarget::Subquery(query) => write!(f, "({query})"), + } + } +} + +impl fmt::Display for ClickHouseTypedLambda<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.parenthesized { + f.write_str("(")?; + } + for (i, (name, data_type)) in self.params.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + name.fmt(f)?; + if let Some(data_type) = data_type { + write!(f, " {data_type}")?; + } + } + if self.parenthesized { + f.write_str(")")?; + } + write!(f, " -> {}", self.body) + } +} + +impl fmt::Display for ClickHouseSettingsCall<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}(", self.name)?; + if !self.args.is_empty() { + write!(f, "{}, ", comma(&self.args))?; + } + write!(f, "SETTINGS {})", comma(&self.settings)) + } +} + +impl fmt::Display for ClickHouseExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TupleElement { expr, index } => { + expr.fmt(f)?; + f.write_str(" . ")?; + f.write_str(index) + } + Self::Array(items) => write!(f, "[{}]", comma(items)), + Self::Dictionary(fields) => { + f.write_str("{")?; + for (i, (key, value)) in fields.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{key}: {value}")?; + } + f.write_str("}") + } + Self::GlobalIn(global_in) => global_in.fmt(f), + Self::TypedLambda(lambda) => lambda.fmt(f), + Self::SettingsCall(call) => call.fmt(f), + Self::All => f.write_str("ALL"), + } + } +} diff --git a/sqlparser_v2/src/dialect/databricks.rs b/sqlparser_v2/src/dialect/databricks.rs new file mode 100644 index 0000000000..f87d93b74e --- /dev/null +++ b/sqlparser_v2/src/dialect/databricks.rs @@ -0,0 +1,455 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Databricks SQL, built on the Spark SQL rules. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + AlterTableOp, ColumnOption, Cte, DataType, Expr, GroupByModifier, Join, LateralView, + ObjectName, PipeOperator, Quantifier, QueryDistribution, SampleClause, Select, SelectItem, + SelectItemKind, Statement, StatementKind, StringLiteral, TableFactor, TableRef, TimeTravel, + WildcardOptions, +}; +use crate::dialect::builtin::BuiltinStatement; +use crate::dialect::snowflake; +use crate::dialect::{Builtin, Dialect}; +use crate::dialect::{bigquery, oracle, spark}; +use crate::display::comma; +use crate::grammar::{self, prec}; +use crate::lexer::{LexResult, Lexeme, Token, TokenKind}; +use crate::parser::{InfixRule, Parser, SetOperatorRule}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Databricks; + +/// Statements only Databricks has. +#[derive(Debug, Clone, PartialEq)] +pub enum DatabricksStatement<'a> { + /// `USE CATALOG name`, or the same with `DATABASE` or `SCHEMA`. + Use { + kind: Cow<'a, str>, + name: ObjectName<'a>, + }, + /// `OPTIMIZE table [WHERE predicate] [ZORDER BY (a, b)]` + Optimize { + table: ObjectName<'a>, + predicate: Option>, + zorder_by: Vec>, + }, +} + +impl fmt::Display for DatabricksStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Use { kind, name } => write!(f, "USE {kind} {name}"), + Self::Optimize { + table, + predicate, + zorder_by, + } => { + write!(f, "OPTIMIZE {table}")?; + if let Some(predicate) = predicate { + write!(f, " WHERE {predicate}")?; + } + if !zorder_by.is_empty() { + write!(f, " ZORDER BY ({})", comma(zorder_by))?; + } + Ok(()) + } + } + } +} + +/// True if `run`, the letters, digits and underscores from a digit up to the +/// first other byte, is the start of a number rather than a name. `after` is +/// the byte that follows it. +#[inline] +fn is_number_run(run: &[u8], after: Option) -> bool { + let digits = run.iter().take_while(|b| b.is_ascii_digit()).count(); + match run[digits..] { + [] => true, + // `1e5`, or the start of `1e+5`. + [b'e' | b'E', ref exponent @ ..] if exponent.iter().all(u8::is_ascii_digit) => { + !exponent.is_empty() || matches!(after, Some(b'+' | b'-')) + } + _ => false, + } +} + +/// The length of the run of name bytes at the start of `bytes`. +#[inline] +fn name_run(bytes: &[u8]) -> usize { + bytes + .iter() + .take_while(|b| b.is_ascii_alphanumeric() || **b == b'_') + .count() +} + +/// Lexes a name that starts with a digit, such as `1st_table` or the `1c` of +/// `a.1c`, and otherwise leaves numbers to the core. +#[inline] +pub fn lex_digit_name(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let lexeme = |kind, len| Some(Ok(Lexeme { kind, len })); + match bytes { + [b'0', b'x' | b'X', ..] => None, + [b'0'..=b'9', ..] => { + let len = name_run(bytes); + if is_number_run(&bytes[..len], bytes.get(len).copied()) { + return None; + } + lexeme(TokenKind::Word, len) + } + [b'.', b'0'..=b'9', ..] => { + let len = name_run(&bytes[1..]); + if is_number_run(&bytes[1..=len], bytes.get(len + 1).copied()) { + return None; + } + lexeme(TokenKind::Op, 1) + } + _ => None, + } +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + lex_digit_name(rest).or_else(|| spark::lex_spark_token(rest)) +} + +fn parse_optimize<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("OPTIMIZE")?; + let table = grammar::parse_object_name(p)?; + let predicate = if p.eat_keyword("WHERE") { + Some(p.parse_expr()?) + } else { + None + }; + let zorder_by = if p.eat_keyword("ZORDER") { + p.expect_keyword("BY")?; + p.expect_op("(")?; + let columns = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + columns + } else { + Vec::new() + }; + Ok(DatabricksStatement::Optimize { + table, + predicate, + zorder_by, + }) +} + +/// Parses `USE` before a kind of object, if that is what is here. +fn parse_use_of_kind<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let Some(kind) = ["CATALOG", "DATABASE", "SCHEMA"] + .into_iter() + .find(|kind| p.peek_nth(1).is_word(kind)) + else { + return Ok(None); + }; + p.advance(); + p.advance(); + let name = grammar::parse_use_name(p)?; + Ok(Some(DatabricksStatement::Use { + kind: kind.into(), + name, + })) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("EXECUTE") && p.peek_nth(1).is_word("IMMEDIATE") { + let execute = oracle::parse_execute_immediate(p)?; + return Ok(StatementKind::Ext(BuiltinStatement::Oracle(execute)).into()); + } + if grammar::at_alter_view(p) { + return grammar::parse_alter_view(p, false) + .map(|a| StatementKind::AlterView(Box::new(a)).into()); + } + let statement = if p.at_keyword("OPTIMIZE") { + Some(parse_optimize(p)?) + } else if p.at_keyword("USE") { + parse_use_of_kind(p)? + } else { + None + }; + match statement { + Some(statement) => Ok(StatementKind::Ext(BuiltinStatement::Databricks(statement)).into()), + None => spark::parse_statement(p), + } +} + +/// Parses a table, which can be read as of a version or a time. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let factor = spark::parse_table_factor(p)?; + let TableFactor::Named(name) = factor else { + return Ok(factor); + }; + let at_as_of = p.peek_nth(1).is_word("AS") && p.peek_nth(2).is_word("OF"); + let kind = ["TIMESTAMP", "VERSION"] + .into_iter() + .find(|kind| at_as_of && p.at_keyword(kind)); + let Some(kind) = kind else { + return Ok(TableFactor::Named(name)); + }; + p.advance(); + p.advance(); + p.advance(); + let at = if kind == "VERSION" { + if !matches!(p.peek().kind, TokenKind::Number | TokenKind::String) { + return Err(p.expected("a version number")); + } + p.parse_prefix()? + } else { + p.parse_expr()? + }; + Ok(TableFactor::TimeTravel(Box::new(TimeTravel { + name, + kind: kind.into(), + at, + }))) +} + +/// Parses a select item, where a wildcard can end in `REPLACE (...)`. +pub fn parse_select_item<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let item = spark::parse_select_item(p)?; + if !p.at_keyword("REPLACE") || !p.peek_nth(1).is_op("(") { + return Ok(item); + } + let (qualifier, options) = match item.kind { + SelectItemKind::Wildcard => (None, None), + SelectItemKind::QualifiedWildcard(name) => (Some(name), None), + SelectItemKind::WildcardWithOptions { qualifier, options } => (qualifier, Some(options)), + _ => return Ok(item), + }; + let mut options = options.unwrap_or_else(|| { + Box::new(WildcardOptions { + ilike: None, + exclude: Vec::new(), + exclude_parens: false, + except_keyword: false, + replace: Vec::new(), + rename: Vec::new(), + rename_parens: false, + }) + }); + options.replace = grammar::parse_wildcard_replace(p)?; + Ok(SelectItemKind::WildcardWithOptions { qualifier, options }.into()) +} + +/// Parses a prefix expression, where `exists` over anything but a query is an +/// ordinary function. +pub fn parse_prefix<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_keyword("EXISTS") && p.peek_nth(1).is_op("(") && !grammar::query_starts_at(p, 2) { + return grammar::parse_name_expr(p); + } + spark::parse_prefix(p) +} + +/// Parses a `SELECT`, which can start with its `FROM` clause. +pub fn parse_select<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_keyword("FROM") { + grammar::parse_from_first_select(p) + } else { + grammar::parse_select(p) + } +} + +impl Dialect for Databricks { + type Ext = Builtin; + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_alter_table_op(p) + } + + fn parse_qualify<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + snowflake::parse_qualify(p) + } + + fn parse_like_quantifier<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Ok(grammar::parse_like_any(p)) + } + + fn eat_limit_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + grammar::set_operator_rule_with_minus(p) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + word.eq_ignore_ascii_case("MINUS") + || word.eq_ignore_ascii_case("QUALIFY") + || grammar::is_reserved_for_alias(word) + } + + fn parse_group_by_suffix<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_group_by_grouping_sets(p) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, true, false) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + !word.eq_ignore_ascii_case("ALL") && grammar::is_reserved(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn at_from_first<'a>(p: &Parser<'a, Self>, n: usize) -> bool { + p.peek_nth(n).is_word("FROM") + } + + fn parse_select<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_table_ref(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + spark::parse_join(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + spark::parse_select_item_alias(p, expr) + } + + fn parse_lateral_views<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + spark::parse_lateral_views(p) + } + + fn parse_query_distribution<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + spark::parse_query_distribution(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_insert(p) + } + + fn parse_sample_clause<'a>( + p: &mut Parser<'a, Self>, + long_form: bool, + ) -> PResult> { + spark::parse_sample_clause(p, long_form) + } + + fn parse_between_low<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let low = grammar::parse_between_low(p)?; + spark::parse_between_bound(p, low) + } + + fn parse_between_high<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let high = grammar::parse_between_high(p)?; + spark::parse_between_bound(p, high) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + spark::string_literal(token) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if p.at_keyword("STRUCT") && p.peek_nth(1).is_op("(") { + return bigquery::parse_struct(p); + } + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + if snowflake::at_path(p) { + return Some(InfixRule::custom(prec::POSTFIX, snowflake::parse_path)); + } + spark::infix_rule(p) + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_cte<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_cte(p) + } + + fn parse_pipe_operators<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_pipe_operators(p) + } + + fn eat_group_by_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_group_by_modifier<'a>(p: &mut Parser<'a, Self>) -> Option { + grammar::parse_group_by_with(p, true) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_data_type(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + spark::parse_column_option(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_create(p) + } +} diff --git a/sqlparser_v2/src/dialect/duckdb.rs b/sqlparser_v2/src/dialect/duckdb.rs new file mode 100644 index 0000000000..78d030afe3 --- /dev/null +++ b/sqlparser_v2/src/dialect/duckdb.rs @@ -0,0 +1,1591 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! DuckDB, built on the core grammar and PostgreSQL's operators and types. + +use crate::ast::Span; +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + AngleArguments, ArrayType, BinaryOp, ColumnOption, CreateFlags, CreateSchema, Cte, DataType, + DataTypeSuffix, ExplainOption, Expr, ExprKind, FunctionArg, Generated, GeneratedKind, + GeneratedStorage, GeneratedWhen, Ident, InsertSource, IsTest, Join, Literal, ObjectName, + ObjectType, OrderByItem, Query, Select, SelectItem, SelectItemKind, SetQuantifier, SpecialExpr, + Statement, StatementKind, StructField, TableAlias, TableRef, TableWithJoins, WildcardOptions, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinStatement}; +use crate::dialect::{Builtin, Dialect, postgres, snowflake, spark}; +use crate::display::{comma, write_if_not_exists}; +use crate::grammar::{self, prec}; +use crate::lexer::{LexResult, Lexeme, Token, TokenKind}; +use crate::parser::{InfixRule, Parser}; + +#[derive(Debug, Clone, PartialEq)] +pub struct DuckDb; + +/// Expressions only DuckDB has. +#[derive(Debug, Clone, PartialEq)] +pub enum DuckDbExpr<'a> { + /// `{'a': 1, b: 2}` + Struct(Vec<(Ident<'a>, Expr<'a, Builtin>)>), + /// `MAP {key: value}` + Map(Vec<(Expr<'a, Builtin>, Expr<'a, Builtin>)>), + /// `[a, b]` + List(Vec>), + /// `lambda x, y : body` + Lambda(Box>), + /// `receiver.name(args)` + MethodCall(Box>), + /// `ALL` in `ORDER BY ALL`. + AllColumns, + /// `:name`, which is written as two tokens because `:` also separates keys + /// from values. + ColonPlaceholder(Cow<'a, str>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DuckDbLambda<'a> { + pub params: Vec>, + pub body: Expr<'a, Builtin>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DuckDbMethodCall<'a> { + pub receiver: Expr<'a, Builtin>, + /// Always an [`ExprKind::Function`] with a one-part name. + pub call: Expr<'a, Builtin>, +} + +/// Statements only DuckDB has. +#[derive(Debug, Clone, PartialEq)] +pub enum DuckDbStatement<'a> { + CreateMacro(Box>), + CreateSecret(Box>), + /// `DROP [TEMPORARY | PERSISTENT] SECRET [IF EXISTS] name [FROM storage]` + DropSecret { + /// `Some(true)` for `TEMPORARY`, `Some(false)` for `PERSISTENT`. + temporary: Option, + if_exists: bool, + name: Ident<'a>, + storage: Option>, + }, + Attach(Box>), + /// `DETACH [DATABASE] [IF EXISTS] name` + Detach { + database: bool, + if_exists: bool, + name: Ident<'a>, + }, + /// `INSTALL name` + Install(Ident<'a>), + /// `LOAD name` + Load(Ident<'a>), +} + +/// `CREATE [OR REPLACE] [TEMPORARY] MACRO name(args) AS definition`. +/// `CREATE FUNCTION` means the same and renders as `CREATE MACRO`. +#[derive(Debug, Clone, PartialEq)] +pub struct DuckDbCreateMacro<'a> { + pub or_replace: bool, + pub temporary: bool, + pub name: ObjectName<'a>, + /// `None` for an empty argument list. + pub args: Option>>, + pub definition: MacroDefinition<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MacroArg<'a> { + pub name: Ident<'a>, + pub default: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MacroDefinition<'a> { + Expr(Expr<'a, Builtin>), + Table(Box>), +} + +/// `CREATE [OR REPLACE] [TEMPORARY | PERSISTENT] SECRET [IF NOT EXISTS] [name] +/// [IN storage] ( TYPE type [, key value ...] )` +#[derive(Debug, Clone, PartialEq)] +pub struct DuckDbCreateSecret<'a> { + pub or_replace: bool, + /// `Some(true)` for `TEMPORARY`, `Some(false)` for `PERSISTENT`. + pub temporary: Option, + pub if_not_exists: bool, + pub name: Option>, + pub storage: Option>, + pub secret_type: Ident<'a>, + pub options: Vec<(Ident<'a>, Ident<'a>)>, +} + +/// `ATTACH [DATABASE] [IF NOT EXISTS] path [AS alias] [(options)]` +#[derive(Debug, Clone, PartialEq)] +pub struct DuckDbAttach<'a> { + pub database: bool, + pub if_not_exists: bool, + pub path: Ident<'a>, + pub alias: Option>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum AttachOption<'a> { + /// `READ_ONLY [true | false]` + ReadOnly(Option), + /// `TYPE name` + Type(Ident<'a>), +} + +fn duckdb_expr<'a>(expr: DuckDbExpr<'a>) -> Expr<'a, Builtin> { + ExprKind::Ext(BuiltinExpr::DuckDb(expr)).into() +} + +fn duckdb_statement<'a>(statement: DuckDbStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::DuckDb(statement)).into() +} + +#[inline] +fn is_name(token: Token<'_>) -> bool { + matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +#[inline] +fn is_word_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' || !byte.is_ascii() +} + +/// Lexes a word holding `$`. Other words are left to the core. +#[inline] +fn lex_dollar_word(bytes: &[u8]) -> Option { + if !(bytes[0].is_ascii_alphabetic() || bytes[0] == b'_' || !bytes[0].is_ascii()) { + return None; + } + let len = bytes + .iter() + .take_while(|b| is_word_byte(**b) || **b == b'$') + .count(); + bytes[..len].contains(&b'$').then_some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })) +} + +/// Scans digits from `start`, each `_` between two of them. Returns the end +/// and whether an underscore was seen. +fn digit_run(bytes: &[u8], start: usize) -> Result<(usize, bool), &'static str> { + let mut i = start; + let mut underscore = false; + while let Some(&byte) = bytes.get(i) { + if byte == b'_' { + if i == start || !bytes.get(i + 1).is_some_and(u8::is_ascii_digit) { + return Err("invalid number"); + } + underscore = true; + } else if !byte.is_ascii_digit() { + break; + } + i += 1; + } + Ok((i, underscore)) +} + +/// Lexes a number with `_` between its digits. Numbers without one are left to +/// the core. +fn lex_number_with_underscores(bytes: &[u8]) -> Option { + let starts_number = bytes[0].is_ascii_digit() + || (bytes[0] == b'.' && bytes.get(1).is_some_and(u8::is_ascii_digit)); + if !starts_number { + return None; + } + let scan = || -> Result, &'static str> { + let (mut len, mut seen) = digit_run(bytes, 0)?; + if crate::lexer::point_continues_number(bytes, len) { + let (end, underscore) = digit_run(bytes, len + 1)?; + len = end; + seen |= underscore; + } + if matches!(bytes.get(len), Some(b'e' | b'E')) { + let sign = usize::from(matches!(bytes.get(len + 1), Some(b'+' | b'-'))); + if bytes.get(len + 1 + sign).is_some_and(u8::is_ascii_digit) { + let (end, underscore) = digit_run(bytes, len + 1 + sign)?; + len = end; + seen |= underscore; + } + } + Ok(seen.then_some(len)) + }; + match scan() { + Err(message) => Some(Err(message)), + Ok(None) => None, + Ok(Some(len)) if bytes.get(len).is_some_and(|b| is_word_byte(*b)) => { + Some(Err("invalid number")) + } + Ok(Some(len)) => Some(Ok(Lexeme { + kind: TokenKind::Number, + len, + })), + } +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) + }; + let bytes = rest.as_bytes(); + match bytes { + [b'{' | b'}', ..] => op(1), + [b':', b':' | b'=', ..] | [b'/', b'/', ..] | [b'=', b'=', ..] => op(2), + // Never a placeholder token: `:` also separates keys from values. + [b':', ..] => op(1), + // A placeholder, unlike PostgreSQL's operator. + [b'?', ..] => None, + _ => postgres::lex_prefixed_string(rest, false) + .or_else(|| lex_number_with_underscores(bytes)) + .or_else(|| lex_dollar_word(bytes)) + .or_else(|| postgres::lex_token(rest)), + } +} + +/// Parses a name that can be any word or a string, as many of DuckDB's own +/// statements allow. +fn parse_name_or_string<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind != TokenKind::String { + return p.parse_name_part(); + } + p.advance(); + Ok(Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: token.text.chars().next(), + span: token.span, + }) +} + +/// Parses items up to `close`, which is consumed. The list can be empty and +/// can end in a comma. +fn parse_list_until<'a, D: Dialect, T>( + p: &mut Parser<'a, D>, + close: &str, + mut item: impl FnMut(&mut Parser<'a, D>) -> PResult, +) -> PResult> { + let mut items = Vec::new(); + while !p.at_op(close) { + items.push(item(p)?); + if !p.eat_op(",") { + break; + } + } + p.expect_op(close)?; + Ok(items) +} + +fn parse_struct_literal<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("{")?; + let fields = parse_list_until(p, "}", |p| { + let key = parse_name_or_string(p)?; + p.expect_op(":")?; + Ok((key, p.parse_expr()?)) + })?; + Ok(duckdb_expr(DuckDbExpr::Struct(fields))) +} + +fn parse_map_literal<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("MAP")?; + p.expect_op("{")?; + let entries = parse_list_until(p, "}", |p| { + let key = p.with_context(grammar::CONTEXT_COLON_SEPARATES, Parser::parse_expr)?; + p.expect_op(":")?; + Ok((key, p.parse_expr()?)) + })?; + Ok(duckdb_expr(DuckDbExpr::Map(entries))) +} + +fn parse_list_literal<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("[")?; + let items = parse_list_until(p, "]", Parser::parse_expr)?; + Ok(duckdb_expr(DuckDbExpr::List(items))) +} + +/// True at `lambda x :`, `lambda x, y :` or `lambda (x, y) :`. Otherwise +/// `lambda` is an ordinary name. +fn at_keyword_lambda<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if !p.at_keyword("LAMBDA") { + return false; + } + let parenthesized = p.peek_nth(1).is_op("("); + let mut n = if parenthesized { 2 } else { 1 }; + loop { + if !is_name(p.peek_nth(n)) { + return false; + } + let separator = p.peek_nth(n + 1); + if parenthesized && separator.is_op(")") { + return p.peek_nth(n + 2).is_op(":"); + } + if !parenthesized && separator.is_op(":") { + return true; + } + if !separator.is_op(",") { + return false; + } + n += 2; + } +} + +fn parse_keyword_lambda<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("LAMBDA")?; + let parenthesized = p.eat_op("("); + let params = p.parse_comma_separated(Parser::parse_name_part)?; + if parenthesized { + p.expect_op(")")?; + } + p.expect_op(":")?; + let body = p.parse_expr()?; + Ok(duckdb_expr(DuckDbExpr::Lambda(Box::new(DuckDbLambda { + params, + body, + })))) +} + +/// True at a `:` joined to the word after it, which makes a placeholder. +fn at_colon_placeholder<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let (colon, next) = (p.peek(), p.peek_nth(1)); + colon.is_op(":") + && colon.span.end == next.span.start + && matches!(next.kind, TokenKind::Word | TokenKind::Number) +} + +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_op("{") { + return parse_struct_literal(p); + } + if p.at_op("[") { + return parse_list_literal(p); + } + if p.at_keyword("MAP") && p.peek_nth(1).is_op("{") { + return parse_map_literal(p); + } + if at_keyword_lambda(p) { + return parse_keyword_lambda(p); + } + if at_colon_placeholder(p) { + p.advance(); + let name = p.advance(); + return Ok(duckdb_expr(DuckDbExpr::ColonPlaceholder(name.text.into()))); + } + if p.at_op("(") && p.has_context(COLUMN_OPTION) { + return p.without_context(COLUMN_OPTION, grammar::parse_prefix); + } + grammar::parse_prefix(p) +} + +/// Levels of tree height added for a node that wraps the expression before it +/// and passes through the dialect's wrapper types. +const POSTFIX_LEVELS: usize = 2; + +/// Parses `.field` or `.method(args)` after anything but a number, where a +/// point followed by a letter is not a field. +fn parse_member<'a, D: Dialect>( + p: &mut Parser<'a, D>, + receiver: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + if matches!(receiver.kind, ExprKind::Literal(Literal::Number(_))) { + return Err(p.expected("end of the number")); + } + p.advance(); + let field = p.parse_name_part()?; + p.deepen_by(POSTFIX_LEVELS)?; + if !p.at_op("(") { + return Ok(ExprKind::Special(Box::new(SpecialExpr::FieldAccess { + expr: receiver, + field, + })) + .into()); + } + let name = ObjectName { parts: vec![field] }; + let call = p.parse_function_call(name)?; + Ok(duckdb_expr(DuckDbExpr::MethodCall(Box::new( + DuckDbMethodCall { receiver, call }, + )))) +} + +/// Set while parsing a column option, where `NOT NULL` is the next constraint +/// and not a test on the expression before it. Parentheses end this. +const COLUMN_OPTION: u32 = 1; + +/// Parses `NOT NULL` after an expression, which renders as `IS NOT NULL`. +fn parse_postfix_not_null<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + Ok(ExprKind::Is { + expr: Box::new(left), + test: IsTest::Null, + negated: true, + } + .into()) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + if p.at_op("//") { + return Some(InfixRule::binary(prec::MUL, BinaryOp::Named("//".into()))); + } + if p.at_op("==") { + return Some(InfixRule::binary(prec::COMPARE, BinaryOp::Eq)); + } + if p.at_op("[") { + return Some(InfixRule::custom( + prec::POSTFIX, + grammar::parse_subscript_or_slice_with_step, + )); + } + if p.at_op(".") && is_name(p.peek_nth(1)) { + return Some(InfixRule::custom(prec::POSTFIX, parse_member)); + } + if p.at_keyword("NOT") && p.peek_nth(1).is_word("NULL") && !p.has_context(COLUMN_OPTION) { + return Some(InfixRule::custom(prec::IS, parse_postfix_not_null)); + } + postgres::infix_rule(p) +} + +/// Parses `name type, ...)` of a `STRUCT` or `UNION` type, after its `(`. +fn parse_type_fields<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let fields = p.parse_comma_separated(|p| { + let name = parse_name_or_string(p)?; + let data_type = p.nested(D::parse_data_type)?; + Ok(StructField { + not_null: false, + options: Vec::new(), + name: Some(name), + colon: false, + data_type, + comment: None, + }) + })?; + p.expect_op(")")?; + Ok(fields) +} + +/// Parses a type, which can be `STRUCT(a INT)`, `UNION(a INT)` or `MAP(a, b)`. +/// Interval fields are rejected rather than leaving `DAY` in `x::INTERVAL DAY` +/// to be read as an alias. +pub fn parse_data_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let is_map = p.at_keyword("MAP") && p.peek_nth(1).is_op("("); + if !(is_map || p.at_keyword("STRUCT") || p.at_keyword("UNION")) { + if spark::at_interval_with_fields(p) { + return Err(p.expected("an INTERVAL type without fields")); + } + let mut ty = grammar::parse_data_type(p)?; + if ty.array == ArrayType::None && p.at_op("[") { + ty.array = grammar::parse_array_brackets(p)?; + } + return Ok(ty); + } + let token = p.advance(); + p.expect_op("(")?; + let arguments = if is_map { + let types = p.parse_comma_separated(|p| p.nested(D::parse_data_type))?; + p.expect_op(")")?; + AngleArguments::ParenTypes(types) + } else { + AngleArguments::ParenFields(parse_type_fields(p)?) + }; + let array = if p.at_op("[") { + grammar::parse_array_brackets(p)? + } else { + ArrayType::None + }; + Ok(DataType { + qualifier: Vec::new(), + name: Ident { + text: token.text.into(), + quote: None, + span: token.span, + }, + angle: Some(Box::new(arguments)), + args: Vec::new(), + suffix: DataTypeSuffix::None, + array, + }) +} + +/// Parses a select item, where a wildcard can end in `EXCLUDE` and `REPLACE`. +pub fn parse_select_item<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let item = grammar::parse_select_item(p)?; + let (SelectItemKind::Wildcard | SelectItemKind::QualifiedWildcard(_)) = item.kind else { + return Ok(item); + }; + let exclude_parens = p.at_keyword("EXCLUDE") && p.peek_nth(1).is_op("("); + let exclude = if !p.eat_keyword("EXCLUDE") { + Vec::new() + } else if exclude_parens { + grammar::parse_ident_list(p)? + } else { + vec![p.parse_ident()?] + }; + let replace = if p.at_keyword("REPLACE") { + grammar::parse_wildcard_replace(p)? + } else { + Vec::new() + }; + if exclude.is_empty() && replace.is_empty() { + return Ok(item); + } + let qualifier = match item.kind { + SelectItemKind::QualifiedWildcard(name) => Some(name), + _ => None, + }; + Ok(SelectItemKind::WildcardWithOptions { + qualifier, + options: Box::new(WildcardOptions { + ilike: None, + exclude, + exclude_parens, + except_keyword: false, + replace, + rename: Vec::new(), + rename_parens: false, + }), + } + .into()) +} + +/// True at `AS 'string'`, which an alias can be in place of a name. +fn at_as_string<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("AS") && p.peek_nth(1).kind == TokenKind::String +} + +/// Finishes a select item, whose alias can be a string after `AS`. +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, D::Ext>, +) -> PResult> { + if at_as_string(p) { + p.advance(); + let alias = Some(parse_name_or_string(p)?); + return Ok(SelectItemKind::Expr { expr, alias }.into()); + } + grammar::parse_select_item_alias(p, expr) +} + +fn parse_table_alias<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let at_join = (p.at_keyword("SEMI") || p.at_keyword("ANTI")) && p.peek_nth(1).is_word("JOIN"); + if at_join { + return Ok(None); + } + if !at_as_string(p) { + return grammar::parse_optional_table_alias(p); + } + p.advance(); + let name = parse_name_or_string(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + Ok(Some(TableAlias { + name, + explicit: true, + columns, + column_types: Vec::new(), + })) +} + +/// Parses a table and its alias, which can be a string after `AS`. +pub fn parse_table_ref<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let factor = D::parse_table_factor(p)?; + let alias = parse_table_alias(p)?; + Ok(TableRef { + factor, + alias, + span: Span::default(), + }) +} + +/// Parses a common table expression, which can say whether to materialize. +pub fn parse_cte<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + let columns = D::parse_cte_columns(p)?; + p.expect_keyword("AS")?; + let materialized = if p.eat_keyword("MATERIALIZED") { + Some(true) + } else if p.at_keyword("NOT") && p.peek_nth(1).is_word("MATERIALIZED") { + p.advance(); + p.advance(); + Some(false) + } else { + None + }; + p.expect_op("(")?; + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + Ok(Cte { + name, + columns, + materialized, + query, + }) +} + +/// Parses a set operator's quantifier and any `BY NAME`. +pub fn parse_set_quantifier<'a, D: Dialect>(p: &mut Parser<'a, D>) -> (SetQuantifier, bool) { + let quantifier = grammar::parse_quantifier(p); + let by_name = p.at_keyword("BY") && p.peek_nth(1).is_word("NAME"); + if by_name { + p.advance(); + p.advance(); + } + (quantifier, by_name) +} + +/// Parses what follows `ORDER BY`, which can be `ALL` with its modifiers. +pub fn parse_query_order_by<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let all = p.peek().span; + if !p.eat_keyword("ALL") { + return p.parse_comma_separated(D::parse_order_by_item); + } + let (asc, nulls_first) = grammar::parse_order_by_modifiers(p)?; + Ok(vec![OrderByItem { + using: None, + ext: Default::default(), + expr: Expr::new(duckdb_expr(DuckDbExpr::AllColumns).kind, all), + asc, + nulls_first, + }]) +} + +/// Parses a call's arguments, which can be empty before `ORDER BY`. +pub fn parse_function_args<'a, D: Dialect>( + p: &mut Parser<'a, D>, + quantifier: SetQuantifier, +) -> PResult>> { + if quantifier != SetQuantifier::Distinct && p.at_keyword("ORDER") && p.peek_nth(1).is_word("BY") + { + return Ok(Vec::new()); + } + if quantifier == SetQuantifier::None && p.at_op(")") { + return Ok(Vec::new()); + } + grammar::parse_list_with_trailing_comma(p, D::parse_function_arg) +} + +/// Parses an argument, which can be named with `:=` or `=>`. An `=` compares, +/// as in `coalesce(x = 1, false)`. +pub fn parse_function_arg<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if is_name(p.peek()) { + let next = p.peek_nth(1); + if let Some(operator) = [":="].into_iter().find(|op| next.is_op(op)) { + let name = p.parse_name_part()?; + p.advance(); + let value = p.parse_expr()?; + return Ok(FunctionArg::NamedWith { + name, + operator: operator.into(), + value, + }); + } + } + // `x -> body` is a lambda only as an argument; elsewhere `->` extracts + // from JSON, as DuckDB's binder decides. + if spark::at_lambda(p) { + return p.spanned_expr(spark::parse_lambda).map(FunctionArg::Expr); + } + grammar::parse_function_arg(p) +} + +/// Parses a column option, which can be `AS (expr)` without `GENERATED`. +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !(p.at_keyword("AS") && p.peek_nth(1).is_op("(")) { + return p.with_context(COLUMN_OPTION, grammar::parse_column_option); + } + p.advance(); + p.advance(); + let expr = p.parse_expr()?; + p.expect_op(")")?; + let storage = if p.eat_keyword("STORED") { + Some(GeneratedStorage::Stored) + } else if p.eat_keyword("VIRTUAL") { + Some(GeneratedStorage::Virtual) + } else { + None + }; + Ok(Some(ColumnOption::Generated(Box::new(Generated { + when: Some(GeneratedWhen::Omitted), + kind: GeneratedKind::Expr { expr, storage }, + })))) +} + +/// The spellings of the date and time parts DuckDB knows, in lower case. +const DATE_PARTS: [&str; 79] = [ + "c", + "cent", + "centuries", + "century", + "d", + "day", + "dayofmonth", + "dayofweek", + "dayofyear", + "days", + "dec", + "decade", + "decades", + "decs", + "dow", + "doy", + "epoch", + "era", + "h", + "hour", + "hours", + "hr", + "hrs", + "isodow", + "isoyear", + "julian", + "m", + "microsecond", + "microseconds", + "mil", + "millenia", + "millennia", + "millenium", + "millennium", + "millisecond", + "milliseconds", + "mils", + "min", + "mins", + "minute", + "minutes", + "mon", + "mons", + "month", + "months", + "ms", + "msec", + "msecond", + "mseconds", + "msecs", + "nanosecond", + "nanoseconds", + "ns", + "quarter", + "quarters", + "s", + "sec", + "second", + "seconds", + "secs", + "timezone", + "timezone_hour", + "timezone_minute", + "us", + "usec", + "usecond", + "useconds", + "usecs", + "w", + "week", + "weekday", + "weekofyear", + "weeks", + "y", + "year", + "years", + "yearweek", + "yr", + "yrs", +]; + +/// Parses the part `EXTRACT` takes: a core date or time field, one of DuckDB's +/// other spellings of one, such as `us`, or a string. +pub fn parse_extract_field<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.peek(); + let known = token.kind == TokenKind::Word + && DATE_PARTS + .iter() + .any(|part| token.text.eq_ignore_ascii_case(part)); + if token.kind == TokenKind::String || known { + p.advance(); + return Ok(token.text); + } + grammar::parse_date_time_field(p) +} + +/// Parses `[TEMPORARY] [PERSISTENT]`. `temp` allows the short `TEMP` too. +fn parse_persistence<'a, D: Dialect>(p: &mut Parser<'a, D>, temp: bool) -> PResult> { + let temporary = p.eat_keyword("TEMPORARY") || (temp && p.eat_keyword("TEMP")); + let persistent = p.eat_keyword("PERSISTENT"); + match (temporary, persistent) { + (true, true) => Err(p.expected("only one of TEMPORARY and PERSISTENT")), + (true, false) => Ok(Some(true)), + (false, true) => Ok(Some(false)), + (false, false) => Ok(None), + } +} + +/// True if a word in `objects` comes after the modifiers of a `CREATE` or `DROP`. +fn at_object_after_modifiers<'a, D: Dialect>(p: &Parser<'a, D>, objects: &[&str]) -> bool { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + while ["TEMPORARY", "TEMP", "PERSISTENT"] + .iter() + .any(|word| p.peek_nth(n).is_word(word)) + { + n += 1; + } + objects.iter().any(|word| p.peek_nth(n).is_word(word)) +} + +fn parse_macro_arg<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = parse_name_or_string(p)?; + let default = if p.eat_op(":=") || p.eat_op("=>") { + Some(p.parse_expr()?) + } else { + None + }; + Ok(MacroArg { name, default }) +} + +fn parse_create_macro<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + if !p.eat_keyword("MACRO") { + p.expect_keyword("FUNCTION")?; + } + let name = grammar::parse_object_name(p)?; + p.expect_op("(")?; + let args = if p.eat_op(")") { + None + } else { + let args = p.parse_comma_separated(parse_macro_arg)?; + p.expect_op(")")?; + Some(args) + }; + p.expect_keyword("AS")?; + let definition = if p.eat_keyword("TABLE") { + MacroDefinition::Table(Box::new(D::parse_query(p)?)) + } else { + MacroDefinition::Expr(p.parse_expr()?) + }; + Ok(DuckDbCreateMacro { + or_replace, + temporary, + name, + args, + definition, + }) +} + +fn parse_create_secret<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let temporary = parse_persistence(p, true)?; + p.expect_keyword("SECRET")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let mut name = None; + let mut storage = None; + if !p.at_op("(") { + if p.eat_keyword("IN") { + storage = Some(parse_name_or_string(p)?); + } else { + name = Some(parse_name_or_string(p)?); + if p.eat_keyword("IN") { + storage = Some(parse_name_or_string(p)?); + } + } + } + p.expect_op("(")?; + p.expect_keyword("TYPE")?; + let secret_type = parse_name_or_string(p)?; + let options = if p.eat_op(",") { + p.parse_comma_separated(|p| { + let key = parse_name_or_string(p)?; + Ok((key, parse_name_or_string(p)?)) + })? + } else { + Vec::new() + }; + p.expect_op(")")?; + Ok(DuckDbCreateSecret { + or_replace, + temporary, + if_not_exists, + name, + storage, + secret_type, + options, + }) +} + +/// Parses `CREATE`, handling DuckDB's macros and secrets. +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if at_object_after_modifiers(p, &["MACRO", "FUNCTION"]) { + let create = parse_create_macro(p)?; + return Ok(duckdb_statement(DuckDbStatement::CreateMacro(Box::new( + create, + )))); + } + if at_object_after_modifiers(p, &["SECRET"]) { + let create = parse_create_secret(p)?; + return Ok(duckdb_statement(DuckDbStatement::CreateSecret(Box::new( + create, + )))); + } + grammar::parse_create(p) +} + +/// Parses `CREATE TYPE name AS ENUM (...)`, which is the form DuckDB shares +/// with PostgreSQL. +pub fn parse_create_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult>> { + if flags != CreateFlags::default() || !p.eat_keyword("TYPE") { + return Ok(None); + } + let parsed = postgres::parse_create_type(p)?; + let is_enum = matches!( + &parsed, + postgres::PostgresStatement::CreateType(create) + if matches!(**create, postgres::CreateType::Enum { .. }) + ); + if !is_enum { + return Err(p.expected("AS ENUM")); + } + Ok(Some( + StatementKind::Ext(BuiltinStatement::Postgres(parsed)).into(), + )) +} + +fn parse_drop_secret<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DROP")?; + let temporary = parse_persistence(p, false)?; + p.expect_keyword("SECRET")?; + let if_exists = p.at_keyword("IF"); + if if_exists { + p.advance(); + p.expect_keyword("EXISTS")?; + } + let name = parse_name_or_string(p)?; + let storage = if p.eat_keyword("FROM") { + Some(parse_name_or_string(p)?) + } else { + None + }; + Ok(DuckDbStatement::DropSecret { + temporary, + if_exists, + name, + storage, + }) +} + +fn parse_attach_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.eat_op("(") { + return Ok(Vec::new()); + } + let options = p.parse_comma_separated(|p| { + if p.eat_keyword("READ_ONLY") { + let value = if p.eat_keyword("TRUE") { + Some(true) + } else if p.eat_keyword("FALSE") { + Some(false) + } else { + None + }; + return Ok(AttachOption::ReadOnly(value)); + } + p.expect_keyword("TYPE")?; + parse_name_or_string(p).map(AttachOption::Type) + })?; + p.expect_op(")")?; + Ok(options) +} + +fn parse_attach<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("ATTACH")?; + let database = p.eat_keyword("DATABASE"); + let if_not_exists = grammar::parse_if_not_exists(p)?; + let path = parse_name_or_string(p)?; + let alias = if p.eat_keyword("AS") { + Some(parse_name_or_string(p)?) + } else { + None + }; + let options = parse_attach_options(p)?; + Ok(DuckDbAttach { + database, + if_not_exists, + path, + alias, + options, + }) +} + +fn parse_detach<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DETACH")?; + let database = p.eat_keyword("DATABASE"); + let if_exists = p.at_keyword("IF"); + if if_exists { + p.advance(); + p.expect_keyword("EXISTS")?; + } + let name = parse_name_or_string(p)?; + Ok(DuckDbStatement::Detach { + database, + if_exists, + name, + }) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("ABORT") { + return grammar::parse_abort(p); + } + if p.at_keyword("ANALYZE") { + return grammar::parse_analyze(p); + } + if p.at_keyword("RESET") { + return postgres::utility::parse_reset(p) + .map(|s| StatementKind::Ext(BuiltinStatement::Postgres(s)).into()); + } + if let Some(prepared) = postgres::utility::parse_prepared_statement(p)? { + return Ok(StatementKind::Ext(BuiltinStatement::Postgres(prepared)).into()); + } + if p.at_keyword("ATTACH") { + let attach = parse_attach(p)?; + return Ok(duckdb_statement(DuckDbStatement::Attach(Box::new(attach)))); + } + if p.at_keyword("DETACH") { + return parse_detach(p).map(duckdb_statement); + } + if p.eat_keyword("INSTALL") { + return parse_name_or_string(p) + .map(DuckDbStatement::Install) + .map(duckdb_statement); + } + if p.eat_keyword("LOAD") { + return parse_name_or_string(p) + .map(DuckDbStatement::Load) + .map(duckdb_statement); + } + if p.at_keyword("DROP") && at_object_after_modifiers(p, &["SECRET"]) { + return parse_drop_secret(p).map(duckdb_statement); + } + grammar::parse_statement(p) +} + +/// Parses a `SELECT`, which can start with its `FROM` clause. +pub fn parse_select<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_keyword("FROM") { + grammar::parse_from_first_select(p) + } else { + grammar::parse_select(p) + } +} + +#[inline] +pub fn is_reserved(word: &str) -> bool { + ["RETURNING", "NOTNULL", "ISNULL"] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved(word) +} + +#[inline] +pub fn is_reserved_for_alias(word: &str) -> bool { + ["QUALIFY", "ASOF"] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved_for_alias(word) +} + +impl Dialect for DuckDb { + type Ext = Builtin; + + fn parse_create_table_query<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_table_or_query(p) + } + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + parse_create_type(p, flags) + } + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_delete_using<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_delete_using(p) + } + + fn eat_limit_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, true, true) + } + + fn parse_insert_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_insert_source_with_default(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + grammar::eat_drop_object_type(p, &["TYPE"]) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + if flags.temporary { + return Err(p.expected("TABLE or VIEW")); + } + grammar::parse_create_schema_body(p, flags) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + is_reserved(word) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + is_reserved_for_alias(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn parse_select<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select(p) + } + + fn at_from_first<'a>(p: &Parser<'a, Self>, n: usize) -> bool { + p.peek_nth(n).is_word("FROM") + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_projection<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_list_with_trailing_comma(p, Parser::parse_select_item) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + spark::parse_join(p) + } + + fn parse_cte<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_cte(p) + } + + fn string_literal(token: Token<'_>) -> crate::ast::StringLiteral<'_> { + postgres::string_literal(token, false) + } + + fn parse_set_quantifier<'a>(p: &mut Parser<'a, Self>) -> (SetQuantifier, bool) { + parse_set_quantifier(p) + } + + fn parse_select_modifiers<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult> { + postgres::parse_distinct_on(p) + } + + fn parse_query_order_by<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_query_order_by(p) + } + + fn parse_function_args<'a>( + p: &mut Parser<'a, Self>, + quantifier: SetQuantifier, + ) -> PResult>> { + parse_function_args(p, quantifier) + } + + fn parse_function_arg<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_function_arg(p) + } + + fn parse_extract_field<'a>(p: &mut Parser<'a, Self>) -> PResult<&'a str> { + parse_extract_field(p) + } + + fn parse_between_low<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let low = grammar::parse_between_low(p)?; + spark::parse_between_bound(p, low) + } + + fn parse_qualify<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + snowflake::parse_qualify(p) + } + + fn eat_group_by_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_returning<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + postgres::parse_returning(p) + } + + fn parse_interval<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_interval(p, false) + } + + fn parse_explain_options<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_explain_option_list(p) + } + + /// A built-in type name can introduce a string: `UUID '...'`. + fn is_typed_string_type(name: &str) -> bool { + grammar::is_typed_string_type(name) + || TYPED_STRING_TYPES + .iter() + .any(|type_name| name.eq_ignore_ascii_case(type_name)) + } + + fn parse_add_column_if_not_exists<'a>(p: &mut Parser<'a, Self>) -> PResult { + grammar::parse_if_not_exists(p) + } + + fn eat_drop_temporary<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("TEMPORARY") + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } +} + +/// Renders the expressions that cannot form long left-deep chains. +fn write_non_chain_expr(f: &mut fmt::Formatter<'_>, expr: &DuckDbExpr<'_>) -> fmt::Result { + match expr { + DuckDbExpr::Struct(fields) => { + f.write_str("{")?; + for (i, (key, value)) in fields.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{key}: {value}")?; + } + f.write_str("}") + } + DuckDbExpr::Map(entries) => { + f.write_str("MAP {")?; + for (i, (key, value)) in entries.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{key}: {value}")?; + } + f.write_str("}") + } + DuckDbExpr::List(items) => write!(f, "[{}]", comma(items)), + DuckDbExpr::Lambda(lambda) => { + write!(f, "lambda {} : {}", comma(&lambda.params), lambda.body) + } + DuckDbExpr::AllColumns => f.write_str("ALL"), + DuckDbExpr::ColonPlaceholder(name) => write!(f, ":{name}"), + DuckDbExpr::MethodCall(_) => { + unreachable!("rendered by DuckDbExpr::fmt") + } + } +} + +impl fmt::Display for DuckDbExpr<'_> { + /// Method calls can form long left-deep chains, so this avoids + /// `write!` as [`Expr`]'s rendering does. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MethodCall(call) => { + call.receiver.fmt(f)?; + f.write_str(".")?; + call.call.fmt(f) + } + other => write_non_chain_expr(f, other), + } + } +} + +impl fmt::Display for MacroArg<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + match &self.default { + Some(default) => write!(f, " := {default}"), + None => Ok(()), + } + } +} + +fn persistence(temporary: Option) -> &'static str { + match temporary { + Some(true) => "TEMPORARY ", + Some(false) => "PERSISTENT ", + None => "", + } +} + +impl fmt::Display for DuckDbCreateMacro<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let or_replace = if self.or_replace { "OR REPLACE " } else { "" }; + let temporary = if self.temporary { "TEMPORARY " } else { "" }; + write!(f, "CREATE {or_replace}{temporary}MACRO {}(", self.name)?; + if let Some(args) = &self.args { + comma(args).fmt(f)?; + } + f.write_str(")")?; + match &self.definition { + MacroDefinition::Expr(expr) => write!(f, " AS {expr}"), + MacroDefinition::Table(query) => write!(f, " AS TABLE {query}"), + } + } +} + +impl fmt::Display for DuckDbCreateSecret<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let or_replace = if self.or_replace { "OR REPLACE " } else { "" }; + write!( + f, + "CREATE {or_replace}{}SECRET ", + persistence(self.temporary) + )?; + write_if_not_exists(f, self.if_not_exists)?; + if let Some(name) = &self.name { + write!(f, "{name} ")?; + } + if let Some(storage) = &self.storage { + write!(f, "IN {storage} ")?; + } + write!(f, "( TYPE {}", self.secret_type)?; + for (key, value) in &self.options { + write!(f, ", {key} {value}")?; + } + f.write_str(" )") + } +} + +impl fmt::Display for AttachOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ReadOnly(None) => f.write_str("READ_ONLY"), + Self::ReadOnly(Some(value)) => write!(f, "READ_ONLY {value}"), + Self::Type(kind) => write!(f, "TYPE {kind}"), + } + } +} + +impl fmt::Display for DuckDbAttach<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ATTACH ")?; + if self.database { + f.write_str("DATABASE ")?; + } + write_if_not_exists(f, self.if_not_exists)?; + self.path.fmt(f)?; + if let Some(alias) = &self.alias { + write!(f, " AS {alias}")?; + } + if !self.options.is_empty() { + write!(f, " ({})", comma(&self.options))?; + } + Ok(()) + } +} + +impl fmt::Display for DuckDbStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CreateMacro(create) => create.fmt(f), + Self::CreateSecret(create) => create.fmt(f), + Self::DropSecret { + temporary, + if_exists, + name, + storage, + } => { + let if_exists = if *if_exists { "IF EXISTS " } else { "" }; + write!( + f, + "DROP {}SECRET {if_exists}{name}", + persistence(*temporary) + )?; + match storage { + Some(storage) => write!(f, " FROM {storage}"), + None => Ok(()), + } + } + Self::Attach(attach) => attach.fmt(f), + Self::Detach { + database, + if_exists, + name, + } => { + let database = if *database { "DATABASE " } else { "" }; + let if_exists = if *if_exists { "IF EXISTS " } else { "" }; + write!(f, "DETACH {database}{if_exists}{name}") + } + Self::Install(name) => write!(f, "INSTALL {name}"), + Self::Load(name) => write!(f, "LOAD {name}"), + } + } +} + +/// DuckDB's built-in types that can introduce a string literal, besides the +/// standard date and time types. +const TYPED_STRING_TYPES: &[&str] = &[ + "BIGINT", + "INT8", + "LONG", + "BIT", + "BITSTRING", + "BLOB", + "BYTEA", + "BINARY", + "VARBINARY", + "BOOLEAN", + "BOOL", + "LOGICAL", + "DECIMAL", + "NUMERIC", + "DOUBLE", + "FLOAT8", + "FLOAT", + "FLOAT4", + "REAL", + "HUGEINT", + "INTEGER", + "INT4", + "INT", + "SIGNED", + "SMALLINT", + "INT2", + "SHORT", + "TINYINT", + "INT1", + "UBIGINT", + "UHUGEINT", + "UINTEGER", + "USMALLINT", + "UTINYINT", + "UUID", + "VARCHAR", + "CHAR", + "BPCHAR", + "TEXT", + "STRING", +]; diff --git a/sqlparser_v2/src/dialect/hive.rs b/sqlparser_v2/src/dialect/hive.rs new file mode 100644 index 0000000000..c60c6ee97c --- /dev/null +++ b/sqlparser_v2/src/dialect/hive.rs @@ -0,0 +1,1226 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Apache Hive, built on the Spark SQL rules. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::BinaryOp; +use crate::ast::{ + AlterTableOp, ColumnOption, CreateFlags, CreateTable, Cte, DataType, Expr, GroupByModifier, + Ident, Join, LateralView, ObjectName, OrderByItem, Quantifier, QueryDistribution, SampleClause, + SelectItem, Span, Statement, StatementKind, StringLiteral, TableFactor, TableRef, +}; +use crate::dialect::builtin::BuiltinStatement; +use crate::dialect::databricks; +use crate::dialect::mysql::MySqlExpr; +use crate::dialect::spark::{self, PartitionColumn, SparkOption}; +use crate::dialect::{Builtin, Dialect, ExprExtOf}; +use crate::display::{comma, write_columns, write_create_flags, write_if_not_exists}; +use crate::grammar::{self, prec}; +use crate::lexer::{self, LexResult, Lexeme, Token, TokenKind, quoted}; +use crate::parser::{InfixRule, Parser, SetOperatorRule}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Hive; + +#[derive(Debug, Clone, PartialEq)] +pub struct HiveCreateConnector<'a> { + pub if_not_exists: bool, + pub name: Ident<'a>, + pub connector_type: Option>, + pub url: Option>, + pub comment: Option>, + pub properties: Vec<(StringLiteral<'a>, StringLiteral<'a>)>, +} + +/// What `ALTER CONNECTOR ... SET` changes. +#[derive(Debug, Clone, PartialEq)] +pub enum HiveAlterConnectorAction<'a> { + Properties(Vec<(StringLiteral<'a>, StringLiteral<'a>)>), + Url(StringLiteral<'a>), + Owner(Cow<'a, str>, StringLiteral<'a>), +} + +/// Parses `CREATE`, `ALTER` or `DROP CONNECTOR`, or returns `None` at anything else. +fn parse_connector<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let verb = ["CREATE", "ALTER", "DROP"] + .into_iter() + .find(|verb| p.at_keyword(verb)); + if verb.is_none() || !p.peek_nth(1).is_word("CONNECTOR") { + return Ok(None); + } + p.advance(); + p.advance(); + let parsed = match verb { + Some("CREATE") => { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = p.parse_ident()?; + let connector_type = parse_connector_string(p, "TYPE")?; + let url = parse_connector_string(p, "URL")?; + let comment = parse_connector_string(p, "COMMENT")?; + let properties = if p.at_keyword("WITH") && p.peek_nth(1).is_word("DCPROPERTIES") { + p.advance(); + p.advance(); + parse_connector_properties(p)? + } else { + Vec::new() + }; + HiveStatement::CreateConnector(Box::new(HiveCreateConnector { + if_not_exists, + name, + connector_type, + url, + comment, + properties, + })) + } + Some("DROP") => { + let if_exists = p.at_keyword("IF") && p.peek_nth(1).is_word("EXISTS"); + if if_exists { + p.advance(); + p.advance(); + } + HiveStatement::DropConnector { + if_exists, + name: p.parse_ident()?, + } + } + _ => { + let name = p.parse_ident()?; + p.expect_keyword("SET")?; + let action = if p.eat_keyword("DCPROPERTIES") { + HiveAlterConnectorAction::Properties(parse_connector_properties(p)?) + } else if p.eat_keyword("URL") { + HiveAlterConnectorAction::Url(spark::parse_string(p)?) + } else { + p.expect_keyword("OWNER")?; + let kind = if p.eat_keyword("USER") { + "USER" + } else { + p.expect_keyword("ROLE")?; + "ROLE" + }; + HiveAlterConnectorAction::Owner(kind.into(), spark::parse_string(p)?) + }; + HiveStatement::AlterConnector { name, action } + } + }; + Ok(Some(hive(parsed))) +} + +fn parse_connector_string<'a, D: Dialect>( + p: &mut Parser<'a, D>, + keyword: &str, +) -> PResult>> { + if p.at_keyword(keyword) && p.peek_nth(1).kind == TokenKind::String { + p.advance(); + return spark::parse_string(p).map(Some); + } + Ok(None) +} + +fn parse_connector_properties<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult, StringLiteral<'a>)>> { + p.expect_op("(")?; + let properties = p.parse_comma_separated(|p| { + let key = spark::parse_string(p)?; + p.expect_op("=")?; + Ok((key, spark::parse_string(p)?)) + })?; + p.expect_op(")")?; + Ok(properties) +} + +/// Statements only Hive has. +#[derive(Debug, Clone, PartialEq)] +pub enum HiveStatement<'a> { + CreateConnector(Box>), + DropConnector { + if_exists: bool, + name: Ident<'a>, + }, + AlterConnector { + name: Ident<'a>, + action: HiveAlterConnectorAction<'a>, + }, + CreateTable(Box>), + CreateFunction(Box>), + /// `WITH ... [FROM name] INSERT ...` + WithInsert { + with: Vec>, + from: Option>, + insert: Box>, + }, + Analyze(Box>), + /// `MSCK [REPAIR] TABLE name [ADD | DROP | SYNC PARTITIONS]` + Msck { + repair: bool, + table: ObjectName<'a>, + action: Option>, + }, + /// `SET HIVEVAR:name = value, ...` + SetHiveVar { + name: ObjectName<'a>, + values: Vec>, + }, + LoadData(Box>), +} + +/// `CREATE [TEMPORARY] [EXTERNAL] TABLE` with clauses only Hive has. +#[derive(Debug, Clone, PartialEq)] +pub struct HiveCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + pub external: bool, + pub like: Option>, + /// In the order written. + pub clauses: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HiveTableClause<'a> { + Comment(StringLiteral<'a>), + PartitionedBy(Vec>), + ClusteredBy(Box>), + RowFormat(HiveRowFormat<'a>), + Stored(HiveStorage<'a>), + Location(StringLiteral<'a>), + TblProperties(Vec>), +} + +/// `CLUSTERED BY (a) [SORTED BY (a ASC)] INTO n BUCKETS` +#[derive(Debug, Clone, PartialEq)] +pub struct HiveClusteredBy<'a> { + pub columns: Vec>, + pub sorted_by: Vec>, + pub buckets: Cow<'a, str>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HiveRowFormat<'a> { + /// `SERDE 'class' [WITH SERDEPROPERTIES (...)]` + Serde { + class: StringLiteral<'a>, + properties: Vec>, + }, + /// `DELIMITED` and its delimiters, each with the words before it. + Delimited(Vec<(Cow<'a, str>, StringLiteral<'a>)>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum HiveStorage<'a> { + /// `STORED AS format` + Format(Ident<'a>), + /// `STORED AS INPUTFORMAT 'class' OUTPUTFORMAT 'class'` + InputOutput { + input: StringLiteral<'a>, + output: StringLiteral<'a>, + }, +} + +/// `CREATE [OR REPLACE] [TEMPORARY] FUNCTION name AS 'class' [USING kind 'uri']` +#[derive(Debug, Clone, PartialEq)] +pub struct HiveCreateFunction<'a> { + pub or_replace: bool, + pub temporary: bool, + pub name: ObjectName<'a>, + pub class: StringLiteral<'a>, + pub using: Option<(Cow<'a, str>, StringLiteral<'a>)>, +} + +/// `ANALYZE TABLE name ...` +#[derive(Debug, Clone, PartialEq)] +pub struct HiveAnalyze<'a> { + pub table: ObjectName<'a>, + pub partition: Vec>, + pub compute_statistics: bool, + pub noscan: bool, + pub cache_metadata: bool, + pub for_columns: bool, + pub columns: Vec>, +} + +/// `LOAD DATA [LOCAL] INPATH 'path' [OVERWRITE] INTO TABLE name ...` +#[derive(Debug, Clone, PartialEq)] +pub struct HiveLoadData<'a> { + pub local: bool, + pub path: StringLiteral<'a>, + pub overwrite: bool, + pub table: ObjectName<'a>, + pub partition: Vec>, + /// `INPUTFORMAT expr SERDE expr` + pub format: Option<(Expr<'a, Builtin>, Expr<'a, Builtin>)>, +} + +#[inline] +fn is_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$' | b'{' | b'}') +} + +/// Lexes a name holding `$`, `{` or `}`, and a number ending in `L`. +#[inline] +fn lex_name(rest: &str) -> Option { + let bytes = rest.as_bytes(); + if !bytes[0].is_ascii_alphanumeric() && bytes[0] != b'$' { + return None; + } + if bytes[0] == b'$' && bytes.get(1).is_some_and(u8::is_ascii_digit) { + return None; + } + let len = bytes.iter().take_while(|b| is_name_byte(**b)).count(); + let run = &bytes[..len]; + if run.iter().any(|b| matches!(b, b'$' | b'{' | b'}')) { + return Some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })); + } + let digits = run.iter().take_while(|b| b.is_ascii_digit()).count(); + if digits > 0 && digits + 1 == len && run[digits] == b'L' { + return Some(Ok(Lexeme { + kind: TokenKind::Number, + len, + })); + } + None +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + match rest.as_bytes() { + [b'"', ..] => Some(quoted(rest, TokenKind::QuotedIdent)), + [b'<', b'=', b'>', ..] => Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 3, + })), + _ => lex_name(rest) + .or_else(|| databricks::lex_digit_name(rest)) + .or_else(|| spark::lex_token(rest)), + } +} + +/// Parses `PARTITION`'s parenthesized list, with the keyword still to read. +fn parse_partition<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + p.expect_keyword("PARTITION")?; + p.expect_op("(")?; + let partition = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(partition) +} + +fn parse_optional_partition<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.at_keyword("PARTITION") { + parse_partition(p) + } else { + Ok(Vec::new()) + } +} + +fn parse_clustered_by<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("BY")?; + let columns = grammar::parse_ident_list(p)?; + let sorted_by = if p.eat_keyword("SORTED") { + p.expect_keyword("BY")?; + p.expect_op("(")?; + let sorted_by = p.parse_comma_separated(D::parse_order_by_item)?; + p.expect_op(")")?; + sorted_by + } else { + Vec::new() + }; + p.expect_keyword("INTO")?; + let buckets = grammar::parse_number(p)?; + p.expect_keyword("BUCKETS")?; + Ok(HiveClusteredBy { + columns, + sorted_by, + buckets: buckets.into(), + }) +} + +/// Parses one optional delimiter of `ROW FORMAT DELIMITED`. +fn parse_delimiters<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult)>> { + const DELIMITERS: [(&[&str], &str); 5] = [ + (&["FIELDS", "TERMINATED", "BY"], "FIELDS TERMINATED BY"), + ( + &["COLLECTION", "ITEMS", "TERMINATED", "BY"], + "COLLECTION ITEMS TERMINATED BY", + ), + ( + &["MAP", "KEYS", "TERMINATED", "BY"], + "MAP KEYS TERMINATED BY", + ), + (&["LINES", "TERMINATED", "BY"], "LINES TERMINATED BY"), + (&["NULL", "DEFINED", "AS"], "NULL DEFINED AS"), + ]; + let mut delimiters = Vec::new(); + loop { + let found = DELIMITERS + .iter() + .find(|(words, _)| p.at_keyword(words[0]) && p.peek_nth(1).is_word(words[1])); + let Some((words, label)) = found else { + return Ok(delimiters); + }; + for word in *words { + p.expect_keyword(word)?; + } + delimiters.push((*label, spark::parse_string(p)?)); + if *label == "FIELDS TERMINATED BY" && p.at_keyword("ESCAPED") { + p.advance(); + p.expect_keyword("BY")?; + delimiters.push(("ESCAPED BY", spark::parse_string(p)?)); + } + } +} + +fn parse_row_format<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("FORMAT")?; + if p.eat_keyword("DELIMITED") { + return parse_delimiters(p).map(|delimiters| { + HiveRowFormat::Delimited(delimiters.into_iter().map(|(k, v)| (k.into(), v)).collect()) + }); + } + p.expect_keyword("SERDE")?; + let class = spark::parse_string(p)?; + let properties = if p.at_keyword("WITH") && p.peek_nth(1).is_word("SERDEPROPERTIES") { + p.advance(); + p.advance(); + spark::parse_option_list(p)? + } else { + Vec::new() + }; + Ok(HiveRowFormat::Serde { class, properties }) +} + +fn parse_stored<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("AS")?; + if p.eat_keyword("INPUTFORMAT") { + let input = spark::parse_string(p)?; + p.expect_keyword("OUTPUTFORMAT")?; + let output = spark::parse_string(p)?; + return Ok(HiveStorage::InputOutput { input, output }); + } + p.parse_ident().map(HiveStorage::Format) +} + +/// Parses a table clause, with the place it holds in Hive's fixed order. +fn parse_table_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult)>> { + use HiveTableClause as Clause; + if let Some(comment) = spark::parse_optional_comment(p)? { + return Ok(Some((0, Clause::Comment(comment)))); + } + if p.eat_keyword("PARTITIONED") { + p.expect_keyword("BY")?; + p.expect_op("(")?; + let columns = p.parse_comma_separated(spark::parse_partition_column)?; + p.expect_op(")")?; + return Ok(Some((1, Clause::PartitionedBy(columns)))); + } + if p.eat_keyword("CLUSTERED") { + let clustered = parse_clustered_by(p)?; + return Ok(Some((2, Clause::ClusteredBy(Box::new(clustered))))); + } + if p.at_keyword("ROW") && p.peek_nth(1).is_word("FORMAT") { + p.advance(); + return Ok(Some((3, Clause::RowFormat(parse_row_format(p)?)))); + } + if p.eat_keyword("STORED") { + return Ok(Some((3, Clause::Stored(parse_stored(p)?)))); + } + if p.eat_keyword("LOCATION") { + return Ok(Some((3, Clause::Location(spark::parse_string(p)?)))); + } + if p.eat_keyword("TBLPROPERTIES") { + return Ok(Some(( + 4, + Clause::TblProperties(spark::parse_option_list(p)?), + ))); + } + Ok(None) +} + +fn parse_table_clauses<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut clauses: Vec> = Vec::new(); + let mut last_rank = 0; + while let Some((rank, clause)) = parse_table_clause(p)? { + let repeated = clauses + .iter() + .any(|seen| std::mem::discriminant(seen) == std::mem::discriminant(&clause)); + if rank < last_rank || repeated { + return Err(p.expected("table clauses in order, each only once")); + } + last_rank = rank; + clauses.push(clause); + } + Ok(clauses) +} + +fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + let external = p.eat_keyword("EXTERNAL"); + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let like = if p.eat_keyword("LIKE") { + Some(grammar::parse_object_name(p)?) + } else { + None + }; + let (columns, constraints) = if like.is_none() && p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let clauses = parse_table_clauses(p)?; + let query = if like.is_none() && p.eat_keyword("AS") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() && clauses.is_empty() && like.is_none() { + return Err(p.expected("column definitions, table clauses, LIKE or AS")); + } + let table = CreateTable { + or_replace, + temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + if !external && clauses.is_empty() && like.is_none() { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + Ok(hive(HiveStatement::CreateTable(Box::new( + HiveCreateTable { + table, + external, + like, + clauses, + }, + )))) +} + +/// True at `CREATE [OR REPLACE] [TEMPORARY] FUNCTION`. +fn at_create_function<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + if p.peek_nth(n).is_word("TEMPORARY") { + n += 1; + } + p.at_keyword("CREATE") && p.peek_nth(n).is_word("FUNCTION") +} + +fn parse_create_function<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let temporary = p.eat_keyword("TEMPORARY"); + p.expect_keyword("FUNCTION")?; + let name = grammar::parse_object_name(p)?; + p.expect_keyword("AS")?; + let class = spark::parse_string(p)?; + let using = if p.eat_keyword("USING") { + let Some(kind) = ["JAR", "FILE", "ARCHIVE"] + .into_iter() + .find(|kind| p.eat_keyword(kind)) + else { + return Err(p.expected("JAR, FILE or ARCHIVE")); + }; + Some((kind, spark::parse_string(p)?)) + } else { + None + }; + Ok(HiveCreateFunction { + or_replace, + temporary, + name, + class, + using: using.map(|(kind, text)| (kind.into(), text)), + }) +} + +/// Parses `CREATE`, handling Hive's tables and functions. +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if at_create_function(p) { + let function = parse_create_function(p)?; + return Ok(hive(HiveStatement::CreateFunction(Box::new(function)))); + } + if spark::at_create_table(p) { + return parse_create_table(p); + } + grammar::parse_create(p) +} + +fn parse_analyze<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("ANALYZE")?; + p.expect_keyword("TABLE")?; + let mut analyze = HiveAnalyze { + table: grammar::parse_object_name(p)?, + partition: Vec::new(), + compute_statistics: false, + noscan: false, + cache_metadata: false, + for_columns: false, + columns: Vec::new(), + }; + loop { + if p.at_keyword("PARTITION") { + analyze.partition = parse_partition(p)?; + } else if p.eat_keyword("NOSCAN") { + analyze.noscan = true; + } else if p.eat_keyword("COMPUTE") { + p.expect_keyword("STATISTICS")?; + analyze.compute_statistics = true; + } else if p.eat_keyword("CACHE") { + p.expect_keyword("METADATA")?; + analyze.cache_metadata = true; + } else if p.eat_keyword("FOR") { + p.expect_keyword("COLUMNS")?; + analyze.for_columns = true; + if matches!(p.peek().kind, TokenKind::Word | TokenKind::QuotedIdent) + && !at_analyze_clause(p) + { + analyze.columns = p.parse_comma_separated(Parser::parse_ident)?; + } + } else { + return Ok(analyze); + } + } +} + +fn at_analyze_clause<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + ["PARTITION", "NOSCAN", "COMPUTE", "CACHE", "FOR"] + .into_iter() + .any(|word| p.at_keyword(word)) +} + +fn parse_msck<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("MSCK")?; + let repair = p.eat_keyword("REPAIR"); + p.expect_keyword("TABLE")?; + let table = grammar::parse_object_name(p)?; + let action = ["ADD", "DROP", "SYNC"] + .into_iter() + .find(|action| p.eat_keyword(action)); + if action.is_some() { + p.expect_keyword("PARTITIONS")?; + } + Ok(HiveStatement::Msck { + repair, + table, + action: action.map(Cow::Borrowed), + }) +} + +/// True at `SET HIVEVAR:name`, which lexes as a word and then a parameter. +fn at_set_hivevar<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let name = p.peek_nth(2); + p.at_keyword("SET") + && p.peek_nth(1).is_word("HIVEVAR") + && name.kind == TokenKind::Placeholder + && name.text.starts_with(':') +} + +fn parse_set_hivevar<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + let token = p.peek(); + p.advance(); + let mut parts = vec![Ident { + text: Cow::Borrowed(&token.text[1..]), + quote: None, + span: Span { + start: token.span.start + 1, + end: token.span.end, + }, + }]; + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + if !p.eat_op("=") && !p.eat_keyword("TO") { + return Err(p.expected("= or TO")); + } + let values = p.parse_comma_separated(Parser::parse_expr)?; + Ok(HiveStatement::SetHiveVar { + name: ObjectName { parts }, + values, + }) +} + +fn parse_load_data<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("LOAD")?; + p.expect_keyword("DATA")?; + let local = p.eat_keyword("LOCAL"); + p.expect_keyword("INPATH")?; + let path = spark::parse_string(p)?; + let overwrite = p.eat_keyword("OVERWRITE"); + p.expect_keyword("INTO")?; + p.expect_keyword("TABLE")?; + let table = grammar::parse_object_name(p)?; + let partition = parse_optional_partition(p)?; + let format = if p.eat_keyword("INPUTFORMAT") { + let input = p.parse_expr()?; + p.expect_keyword("SERDE")?; + Some((input, p.parse_expr()?)) + } else { + None + }; + Ok(HiveLoadData { + local, + path, + overwrite, + table, + partition, + format, + }) +} + +/// Parses a statement that starts with `WITH`, which can be an `INSERT`. +fn parse_with<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("WITH")?; + let with = p.parse_comma_separated(D::parse_cte)?; + let from = if p.eat_keyword("FROM") { + Some(grammar::parse_object_name(p)?) + } else { + None + }; + if from.is_none() && !p.at_keyword("INSERT") { + let with = Some(Box::new(crate::ast::With { + recursive: false, + ctes: with, + })); + let query = grammar::parse_query_after_with(p, with)?; + return Ok(StatementKind::Query(Box::new(query)).into()); + } + let insert = Box::new(D::parse_insert_statement(p)?); + Ok(hive(HiveStatement::WithInsert { with, from, insert })) +} + +fn hive<'a>(statement: HiveStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::Hive(statement)).into() +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if let Some(statement) = parse_connector(p)? { + return Ok(statement); + } + if grammar::at_alter_view(p) { + return grammar::parse_alter_view(p, false) + .map(|a| StatementKind::AlterView(Box::new(a)).into()); + } + if p.at_keyword("WITH") { + return parse_with(p); + } + if p.at_keyword("ANALYZE") { + return Ok(hive(HiveStatement::Analyze(Box::new(parse_analyze(p)?)))); + } + if p.at_keyword("MSCK") { + return parse_msck(p).map(hive); + } + if at_set_hivevar(p) { + return parse_set_hivevar(p).map(hive); + } + if p.at_keyword("LOAD") { + return Ok(hive(HiveStatement::LoadData(Box::new(parse_load_data(p)?)))); + } + spark::parse_statement(p) +} + +/// Parses an `ALTER TABLE` operation, adding those on partitions. +pub fn parse_alter_table_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("ADD") { + let if_not_exists = p.peek_nth(1).is_word("IF") && p.peek_nth(2).is_word("NOT"); + let words = if if_not_exists { 4 } else { 1 }; + if p.peek_nth(words).is_word("PARTITION") { + for _ in 0..words { + p.advance(); + } + let mut partitions = Vec::new(); + while p.at_keyword("PARTITION") { + partitions.push(parse_partition(p)?); + } + return Ok(AlterTableOp::AddPartitions { + if_not_exists, + partitions, + }); + } + } + if p.at_keyword("DROP") { + let if_exists = p.peek_nth(1).is_word("IF") && p.peek_nth(2).is_word("EXISTS"); + let words = if if_exists { 3 } else { 1 }; + if p.peek_nth(words).is_word("PARTITION") { + for _ in 0..words { + p.advance(); + } + let partition = parse_partition(p)?; + return Ok(AlterTableOp::DropPartition { + if_exists, + partition, + }); + } + } + if p.at_keyword("PARTITION") { + let old = parse_partition(p)?; + p.expect_keyword("RENAME")?; + p.expect_keyword("TO")?; + let new = parse_partition(p)?; + let set = p.at_keyword("SET") && p.peek_nth(1).is_word("LOCATION"); + if set { + p.advance(); + } + let location = if p.eat_keyword("LOCATION") { + Some((set, spark::parse_string(p)?)) + } else { + None + }; + return Ok(AlterTableOp::RenamePartition { old, new, location }); + } + spark::parse_alter_table_op(p) +} + +/// Parses a table, whose name can be the word `LIMIT`. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("LIMIT") { + let token = p.peek(); + p.advance(); + return Ok(TableFactor::Named(ObjectName { + parts: vec![Ident { + text: token.text.into(), + quote: None, + span: token.span, + }], + })); + } + grammar::parse_table_factor(p) +} + +pub fn infix_rule<'a, D>(p: &Parser<'a, D>) -> Option> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + if p.at_op("<=>") { + return Some(InfixRule::binary( + prec::COMPARE, + BinaryOp::Named("<=>".into()), + )); + } + spark::infix_rule(p) +} + +impl Dialect for Hive { + type Ext = Builtin; + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, false) + } + + fn parse_like_quantifier<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Ok(grammar::parse_like_any(p)) + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + grammar::set_operator_rule_with_minus(p) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + word.eq_ignore_ascii_case("MINUS") || grammar::is_reserved_for_alias(word) + } + + fn parse_group_by_suffix<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_group_by_grouping_sets(p) + } + + fn parse_cte_columns<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(Vec::new()) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_table_ref(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + spark::parse_join(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + spark::parse_select_item_alias(p, expr) + } + + fn parse_lateral_views<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + spark::parse_lateral_views(p) + } + + fn parse_query_distribution<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + spark::parse_query_distribution(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_insert(p) + } + + fn parse_sample_clause<'a>( + p: &mut Parser<'a, Self>, + long_form: bool, + ) -> PResult> { + spark::parse_sample_clause(p, long_form) + } + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_alter_table_op(p) + } + + fn eat_drop_purge<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("PURGE") + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + if rest.starts_with('#') { + return Some(Ok(lexer::line_comment(rest))); + } + lexer::lex_core_comment(rest) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + StringLiteral { + backslash_escapes: true, + ..grammar::string_literal(token) + } + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item(p) + } + + fn parse_group_by_modifier<'a>(p: &mut Parser<'a, Self>) -> Option { + grammar::parse_group_by_with(p, true) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + spark::parse_data_type(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + spark::parse_column_option(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } +} + +impl fmt::Display for HiveRowFormat<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Serde { class, properties } => { + write!(f, "ROW FORMAT SERDE {}", class)?; + if !properties.is_empty() { + write!(f, " WITH SERDEPROPERTIES ({})", comma(properties))?; + } + Ok(()) + } + Self::Delimited(delimiters) => { + f.write_str("ROW FORMAT DELIMITED")?; + for (label, value) in delimiters { + write!(f, " {label} {}", value)?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for HiveStorage<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Format(format) => write!(f, "STORED AS {format}"), + Self::InputOutput { input, output } => { + write!(f, "STORED AS INPUTFORMAT {} OUTPUTFORMAT {}", input, output) + } + } + } +} + +impl fmt::Display for HiveClusteredBy<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "CLUSTERED BY ({})", comma(&self.columns))?; + if !self.sorted_by.is_empty() { + write!(f, " SORTED BY ({})", comma(&self.sorted_by))?; + } + write!(f, " INTO {} BUCKETS", self.buckets) + } +} + +impl fmt::Display for HiveTableClause<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Comment(comment) => write!(f, "COMMENT {}", comment), + Self::PartitionedBy(columns) => write!(f, "PARTITIONED BY ({})", comma(columns)), + Self::ClusteredBy(clustered) => clustered.fmt(f), + Self::RowFormat(format) => format.fmt(f), + Self::Stored(storage) => storage.fmt(f), + Self::Location(location) => write!(f, "LOCATION {}", location), + Self::TblProperties(options) => write!(f, "TBLPROPERTIES ({})", comma(options)), + } + } +} + +impl fmt::Display for HiveCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + write_create_flags(f, table.or_replace, table.temporary)?; + f.write_str(if self.external { + "EXTERNAL TABLE " + } else { + "TABLE " + })?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + if let Some(like) = &self.like { + write!(f, " LIKE {like}")?; + } + if !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + for clause in &self.clauses { + write!(f, " {clause}")?; + } + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} + +impl fmt::Display for HiveCreateFunction<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_create_flags(f, self.or_replace, self.temporary)?; + write!(f, "FUNCTION {} AS {}", self.name, self.class)?; + if let Some((kind, uri)) = &self.using { + write!(f, " USING {kind} {}", uri)?; + } + Ok(()) + } +} + +impl fmt::Display for HiveAnalyze<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ANALYZE TABLE {}", self.table)?; + if !self.partition.is_empty() { + write!(f, " PARTITION ({})", comma(&self.partition))?; + } + if self.compute_statistics { + f.write_str(" COMPUTE STATISTICS")?; + } + if self.noscan { + f.write_str(" NOSCAN")?; + } + if self.cache_metadata { + f.write_str(" CACHE METADATA")?; + } + if self.for_columns { + f.write_str(" FOR COLUMNS")?; + if !self.columns.is_empty() { + write!(f, " {}", comma(&self.columns))?; + } + } + Ok(()) + } +} + +impl fmt::Display for HiveLoadData<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let local = if self.local { "LOCAL " } else { "" }; + let overwrite = if self.overwrite { "OVERWRITE " } else { "" }; + write!( + f, + "LOAD DATA {local}INPATH {} {overwrite}INTO TABLE {}", + self.path, self.table + )?; + if !self.partition.is_empty() { + write!(f, " PARTITION ({})", comma(&self.partition))?; + } + if let Some((input, serde)) = &self.format { + write!(f, " INPUTFORMAT {input} SERDE {serde}")?; + } + Ok(()) + } +} + +impl fmt::Display for HiveStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CreateConnector(connector) => { + f.write_str("CREATE CONNECTOR ")?; + write_if_not_exists(f, connector.if_not_exists)?; + connector.name.fmt(f)?; + if let Some(ref connector_type) = connector.connector_type { + write!(f, " TYPE {}", connector_type)?; + } + if let Some(ref url) = connector.url { + write!(f, " URL {}", url)?; + } + if let Some(ref comment) = connector.comment { + write!(f, " COMMENT {}", comment)?; + } + if !connector.properties.is_empty() { + f.write_str(" WITH DCPROPERTIES ")?; + write_connector_properties(f, &connector.properties)?; + } + Ok(()) + } + Self::DropConnector { if_exists, name } => { + f.write_str("DROP CONNECTOR ")?; + if *if_exists { + f.write_str("IF EXISTS ")?; + } + name.fmt(f) + } + Self::AlterConnector { name, action } => { + write!(f, "ALTER CONNECTOR {name} SET ")?; + match action { + HiveAlterConnectorAction::Properties(properties) => { + f.write_str("DCPROPERTIES")?; + write_connector_properties(f, properties) + } + HiveAlterConnectorAction::Url(url) => { + write!(f, "URL {}", url) + } + HiveAlterConnectorAction::Owner(kind, name) => { + write!(f, "OWNER {kind} {}", name) + } + } + } + Self::CreateTable(create) => create.fmt(f), + Self::CreateFunction(function) => function.fmt(f), + Self::WithInsert { with, from, insert } => { + write!(f, "WITH {}", comma(with))?; + if let Some(from) = from { + write!(f, " FROM {from}")?; + } + write!(f, " {insert}") + } + Self::Analyze(analyze) => analyze.fmt(f), + Self::Msck { + repair, + table, + action, + } => { + let repair = if *repair { "REPAIR " } else { "" }; + write!(f, "MSCK {repair}TABLE {table}")?; + if let Some(action) = action { + write!(f, " {action} PARTITIONS")?; + } + Ok(()) + } + Self::SetHiveVar { name, values } => { + write!(f, "SET HIVEVAR:{name} = {}", comma(values)) + } + Self::LoadData(load) => load.fmt(f), + } + } +} + +fn write_connector_properties( + f: &mut fmt::Formatter<'_>, + properties: &[(StringLiteral<'_>, StringLiteral<'_>)], +) -> fmt::Result { + f.write_str("(")?; + for (i, (key, value)) in properties.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{} = {}", key, value)?; + } + f.write_str(")") +} diff --git a/sqlparser_v2/src/dialect/mod.rs b/sqlparser_v2/src/dialect/mod.rs new file mode 100644 index 0000000000..8173723d3d --- /dev/null +++ b/sqlparser_v2/src/dialect/mod.rs @@ -0,0 +1,876 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Dialects customize the grammar by overriding [`Dialect`] methods. + +pub mod bigquery; +pub mod builtin; +pub mod clickhouse; +pub mod databricks; +pub mod duckdb; +pub mod hive; +pub mod mssql; +pub mod mysql; +pub mod oracle; +pub mod postgres; +pub mod redshift; +pub mod snowflake; +pub mod spark; +pub mod sqlite; +pub mod teradata; + +use std::fmt::{self, Debug, Display}; + +pub use bigquery::BigQuery; +pub use builtin::{Builtin, DialectKind}; +pub use clickhouse::ClickHouse; +pub use databricks::Databricks; +pub use duckdb::DuckDb; +pub use hive::Hive; +pub use mssql::MsSql; +pub use mysql::MySql; +pub use oracle::Oracle; +pub use postgres::Postgres; +pub use redshift::Redshift; +pub use snowflake::Snowflake; +pub use spark::Spark; +pub use sqlite::Sqlite; +pub use teradata::Teradata; + +use crate::PResult; +use crate::ast::*; +use crate::grammar; +use crate::lexer::{LexResult, Token}; +use crate::parser::{InfixRule, Parser, SetOperatorRule}; + +/// The types stored in the AST's extension slots. +/// +/// This is separate from [`Dialect`] so that several dialects can share one +/// AST type. All built-in dialects use [`Builtin`]; a third-party dialect can +/// use it too, or define its own to add new nodes. +pub trait AstExt: 'static + Sized + Debug + Clone + PartialEq { + /// Additional expression nodes. + type Expr<'a>: Debug + Display + Clone + PartialEq; + /// Data parsed directly after `SELECT`. It must render as nothing, or as + /// text ending in a space. + type Select<'a>: Debug + Display + Clone + PartialEq + Default; + /// Additional statements. + type Statement<'a>: Debug + Display + Clone + PartialEq; + /// Data parsed directly after `INSERT`. It must render as nothing, or as + /// text ending in a space. + type Insert<'a>: Debug + Display + Clone + PartialEq + Default; + /// Additional table factors, usable wherever a table can appear. + type TableFactor<'a>: Debug + Display + Clone + PartialEq; + /// Additional join conditions, rendered after the joined table with a + /// space before them. + type JoinConstraint<'a>: Debug + Display + Clone + PartialEq; + /// Data parsed after an `ORDER BY` item. It must render as nothing, or as + /// text starting with a space. + type OrderByItem<'a>: Debug + Display + Clone + PartialEq + Default; + /// Clauses parsed at the end of a query, before any pipe steps. It must + /// render as nothing, or as text starting with a space. + type QueryTail<'a>: Debug + Display + Clone + PartialEq + Default; + + /// True if `modifiers` render after `DISTINCT` rather than before it. + fn modifiers_follow_quantifier(_modifiers: &Self::Select<'_>) -> bool { + false + } +} + +/// The insert extension type of dialect `D`. +pub type InsertExtOf<'a, D> = <::Ext as AstExt>::Insert<'a>; + +/// An empty extension, for slots a dialect does not use. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct NoExt; + +impl Display for NoExt { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { + Ok(()) + } +} + +/// The expression extension type of dialect `D`. +pub type ExprExtOf<'a, D> = <::Ext as AstExt>::Expr<'a>; + +/// The select extension type of dialect `D`. +pub type SelectExtOf<'a, D> = <::Ext as AstExt>::Select<'a>; + +/// The query tail extension type of dialect `D`. +pub type QueryTailOf<'a, D> = <::Ext as AstExt>::QueryTail<'a>; + +/// A SQL dialect: the core grammar plus this dialect's overrides. +/// +/// Every grammar rule is a method defaulting to [`crate::grammar`], so a +/// dialect overrides only the rules it changes and calls back into the core +/// for everything else. +/// +/// To build on another dialect, delegate the hooks to that dialect's exported +/// generic rules, as [`Redshift`] does with [`postgres`]. +pub trait Dialect: 'static + Sized { + /// The AST extensions this dialect produces. + type Ext: AstExt; + + /// Lexes a dialect-specific token at the start of the non-empty `rest`, + /// or returns `None` to use the core lexer. + #[inline] + fn lex_token(_rest: &str) -> Option { + None + } + + /// Lexes a token whose meaning depends on the token directly before it, + /// which is `None` if anything separates them. Runs before [`lex_token`]. + /// + /// [`lex_token`]: Dialect::lex_token + #[inline] + fn lex_after(_prev: Option>, _rest: &str) -> Option { + None + } + + /// Called at the start of each line after the first. A dialect with raw + /// data on the lines after a statement returns where in `tokens` to place + /// a [`TokenKind::DialectLiteral`] covering that data, and the data's + /// length in `sql` from `pos`. + /// + /// [`TokenKind::DialectLiteral`]: crate::lexer::TokenKind::DialectLiteral + #[inline] + fn lex_payload_line(_sql: &str, _tokens: &[Token<'_>], _pos: usize) -> Option<(usize, usize)> { + None + } + + /// Returns the length of a comment at the start of the non-empty `rest`, + /// or `None` if there is no comment there. + #[inline] + fn lex_comment(rest: &str) -> Option> { + crate::lexer::lex_core_comment(rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + grammar::is_reserved(word) + } + + /// True for words that cannot be an alias without `AS`. + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + grammar::is_reserved_for_alias(word) + } + + /// Builds a string literal from its token. + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + grammar::string_literal(token) + } + + /// Parses an optional filter after a function call. + fn parse_function_filter<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_function_filter(p) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_statement(p) + } + + /// Parses `INSERT` where a dialect's forms are not all [`Insert`] nodes. + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Self::parse_insert(p).map(|insert| StatementKind::Insert(Box::new(insert)).into()) + } + + fn parse_insert<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_insert(p) + } + + fn parse_insert_modifiers<'a>(_p: &mut Parser<'a, Self>) -> PResult> { + Ok(Default::default()) + } + + /// Parses the optional column list of an `INSERT`. + fn parse_insert_columns<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_insert_columns(p) + } + + /// Parses the keyword between `INSERT` and the table, returning whether + /// it was present. The core requires `INTO`. + fn parse_insert_into<'a>(p: &mut Parser<'a, Self>) -> PResult { + p.expect_keyword("INTO")?; + Ok(true) + } + + /// Parses what follows the table of an `INSERT`. + fn parse_insert_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_insert_source(p) + } + + fn parse_update<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_update(p) + } + + /// Parses an optional `FROM` after an `UPDATE`'s assignments. The core has none. + fn parse_update_from_after_set<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(Vec::new()) + } + + /// Parses an optional `FROM` before an `UPDATE`'s `SET`. The core has none. + fn parse_update_from_before_set<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(Vec::new()) + } + + fn parse_assignment<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_assignment(p) + } + + fn parse_delete<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_delete(p) + } + + /// Parses an optional `USING` after a `DELETE`'s table. The core has none. + fn parse_delete_using<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(Vec::new()) + } + + /// Parses an optional `RETURNING`-style clause. The core has none. + fn parse_returning<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(Vec::new()) + } + + /// Parses an optional `OUTPUT`-style clause. The core has none. + fn parse_output_clause<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>>> { + Ok(None) + } + + /// Dispatches a `CREATE` statement on its object type. + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_create(p) + } + + /// Parses what follows `CREATE ... TABLE`. + fn parse_create_table<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + grammar::parse_create_table(p, flags) + } + + fn parse_create_view<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + grammar::parse_create_view(p, flags) + } + + fn parse_create_index<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_create_index(p) + } + + fn parse_drop<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_drop(p) + } + + fn parse_truncate<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_truncate(p) + } + + fn parse_alter_table<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_alter_table(p) + } + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_alter_table_op(p) + } + + /// Consumes any `IF NOT EXISTS` in `ADD COLUMN`. The core has none. + fn parse_add_column_if_not_exists<'a>(_p: &mut Parser<'a, Self>) -> PResult { + Ok(false) + } + + /// Consumes any `ONLY` after `ALTER TABLE`. The core has none. + fn parse_alter_table_only<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + /// Parses what follows `CREATE SCHEMA`. + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + grammar::parse_create_schema(p, flags) + } + + /// Parses an object type that only this dialect can `CREATE`, with the + /// cursor on the type's first word. The core has none. + fn parse_create_extension<'a>( + _p: &mut Parser<'a, Self>, + _flags: CreateFlags, + ) -> PResult>> { + Ok(None) + } + + /// Parses the source of `CREATE TABLE ... AS`. + fn parse_create_table_query<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Self::parse_query(p) + } + + /// Parses a table constraint, or returns `None` if there is none here. + fn parse_table_constraint<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_table_constraint(p) + } + + fn parse_column_def<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_column_def(p) + } + + /// Parses a column option, or returns `None` if there is none here. + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_column_option(p) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_data_type(p) + } + + fn parse_query<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_query(p) + } + + /// Parses the lower bound of `BETWEEN`. + fn parse_between_low<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_between_low(p) + } + + /// Parses the upper bound of `BETWEEN`, after `AND`. + fn parse_between_high<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_between_high(p) + } + + /// Parses what follows `SAMPLE` or `TABLESAMPLE`. + fn parse_sample_clause<'a>( + p: &mut Parser<'a, Self>, + long_form: bool, + ) -> PResult> { + grammar::parse_sample_clause(p, long_form) + } + + /// Parses the values that a `PIVOT` clause lists after `IN (`. + fn parse_pivot_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_pivot_source(p) + } + + /// Parses any `LATERAL VIEW` clauses after `FROM`. The common grammar has none. + fn parse_lateral_views<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(Vec::new()) + } + + /// Parses `CLUSTER BY`, `DISTRIBUTE BY` and `SORT BY` at the end of a + /// `SELECT`. The common grammar has none of them. + fn parse_query_distribution<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>>> { + Ok(None) + } + + /// Finishes a select item once its expression has been parsed. + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Self::Ext>, + ) -> PResult> { + grammar::parse_select_item_alias(p, expr) + } + + /// Parses a `LIMIT` that follows the locking clauses, in dialects where + /// `FOR UPDATE` can precede it. Runs only when no `LIMIT` came earlier. + fn parse_limit_after_locks<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>>> { + Ok(None) + } + + /// Parses what ends a query after its locking clauses. The core has none. + fn parse_query_tail<'a>(_p: &mut Parser<'a, Self>) -> PResult> { + Ok(Default::default()) + } + + /// Parses any `|> ...` steps after a query. The common grammar has none; + /// a dialect with pipe syntax can use [`grammar::parse_pipe_operators`]. + fn parse_pipe_operators<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(Vec::new()) + } + + /// Parses what follows a set operator's keyword: its quantifier, and + /// whether columns are matched by name. The core has no matching by name. + fn parse_set_quantifier<'a>(p: &mut Parser<'a, Self>) -> (SetQuantifier, bool) { + (grammar::parse_quantifier(p), false) + } + + /// The set operator at the current token, or `None` if there is none. + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + grammar::set_operator_rule(p) + } + + fn parse_select<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_select(p) + } + + fn parse_select_head<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult<(SelectExtOf<'a, Self>, SetQuantifier)> { + grammar::parse_select_head(p) + } + + /// Consumes `RECURSIVE` after `WITH`, in dialects that write it. + fn eat_with_recursive<'a>(p: &mut Parser<'a, Self>) -> bool { + grammar::eat_with_recursive(p) + } + + /// Parses a statement that a `WITH` clause leads into, with the cursor after + /// that clause. The core has only queries there. + fn parse_statement_after_with<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(None) + } + + /// True if the token `n` ahead starts a `VALUES` query. + fn at_query_values<'a>(p: &Parser<'a, Self>, n: usize) -> bool { + grammar::at_query_values(p, n) + } + + /// Parses the rows of a `VALUES` query, after the keyword. + fn parse_query_values<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_query_values(p) + } + + /// True if the token `n` ahead starts a query that puts `FROM` first. Such + /// a dialect also overrides `parse_select` to read it. + fn at_from_first<'a>(_p: &Parser<'a, Self>, _n: usize) -> bool { + false + } + + /// Parses the select list. + fn parse_projection<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + p.parse_comma_separated(Parser::parse_select_item) + } + + /// Parses an optional `INTO` after the select list. The core has none. + fn parse_select_into<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>>> { + Ok(None) + } + + /// Parses what follows `FROM`. + fn parse_from_list<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + p.parse_comma_separated(Self::parse_table_with_joins) + } + + /// Parses an optional `PREWHERE` clause, before `WHERE`. + fn parse_prewhere<'a>(_p: &mut Parser<'a, Self>) -> PResult>>> { + Ok(None) + } + + /// Parses an optional `QUALIFY` clause. + fn parse_qualify<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + /// Decides whether parentheses that hold no join are allowed. + fn check_nested_join<'a>( + p: &Parser<'a, Self>, + table: &TableWithJoins<'a, Self::Ext>, + ) -> PResult<()> { + grammar::check_nested_join(p, table) + } + + /// Parses `SEPARATOR 'text'` inside a call's parentheses, after its + /// arguments and `ORDER BY`. The core has none. + fn parse_function_separator<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(None) + } + + /// Parses `ON OVERFLOW ...` inside a call's parentheses, after its + /// arguments. The core has none. + fn parse_function_on_overflow<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>>> { + Ok(None) + } + + /// True at the closing of a call that has no arguments before it. + fn at_empty_function_args<'a>(p: &Parser<'a, Self>) -> bool { + p.at_op(")") + } + + /// Parses an optional `OVER` clause after a function call. + fn parse_function_over<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + if p.eat_keyword("OVER") { + grammar::parse_window_over(p).map(Some) + } else { + Ok(None) + } + } + + /// True if the name just read is followed by a call's arguments. + fn at_function_call<'a>(p: &Parser<'a, Self>) -> bool { + p.at_op("(") + } + + fn parse_show<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_show(p) + } + + fn parse_transaction<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_transaction(p) + } + + fn parse_use<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_use(p) + } + + /// Parses `EXPLAIN` or `DESCRIBE`. + fn parse_explain<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_explain(p) + } + + fn parse_call<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_call(p) + } + + /// Parses one grantee of `GRANT` or `REVOKE`. + fn parse_grantee<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grantee(p) + } + + /// Parses the list of grantees of `GRANT` and `REVOKE`. + fn parse_grantees<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_grantees(p) + } + + /// Parses one name a grant applies to. + fn parse_grant_name<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grant_name(p) + } + + fn parse_grant<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grant(p) + } + + fn parse_revoke<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_revoke(p) + } + + fn parse_merge<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_merge(p) + } + + /// Consumes `TEMPORARY` after `DROP`, in dialects that have it. + fn eat_drop_temporary<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + /// Consumes `PURGE` at the end of `DROP`, in dialects that have it. + fn eat_drop_purge<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + /// Parses `DROP FUNCTION` and the like. + fn parse_drop_routine<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_drop_routine(p) + } + + /// Consumes modifiers written before an index's name. + fn parse_index_flags<'a>(_p: &mut Parser<'a, Self>) -> IndexFlags { + IndexFlags::default() + } + + /// Parses the settings written after an index's definition. + fn parse_index_settings<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult> { + Ok(Vec::new()) + } + + /// Consumes `ALL` after `LIMIT`, in dialects that have `LIMIT ALL`. + fn eat_limit_all<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + /// Parses `GROUPING SETS (...)` written after a `GROUP BY` list. + fn parse_group_by_suffix<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>>> { + Ok(None) + } + + /// Parses the column list after a CTE's name. The core allows one. + fn parse_cte_columns<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + if grammar::at_column_list(p) { + grammar::parse_ident_list(p) + } else { + Ok(Vec::new()) + } + } + + /// Parses a quantifier written before a list of patterns on the right of + /// `LIKE`. The core has none. + fn parse_like_quantifier<'a>(_p: &mut Parser<'a, Self>) -> PResult> { + Ok(None) + } + + /// Parses a form of `IS` beyond the common ones, after `IS` and any `NOT`. + fn parse_is_test<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + /// Consumes `ALL` after `GROUP BY`, in dialects that have `GROUP BY ALL`. + fn eat_group_by_all<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + /// Parses the window another window is defined as: `WINDOW w AS other`. The + /// common grammar requires a parenthesized definition. + fn parse_named_window_reference<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + /// Consumes `ROW` as what a `MERGE` clause inserts, in dialects that have it. + fn eat_merge_insert_row<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + /// Parses `WITH ROLLUP` and the like after `GROUP BY`. + fn parse_group_by_modifier<'a>(_p: &mut Parser<'a, Self>) -> Option { + None + } + + /// Parses one column of `CREATE INDEX`. + fn parse_index_column<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_index_column(p) + } + + /// Parses `WITH (...)` storage parameters on an index. + fn parse_index_storage<'a>(_p: &mut Parser<'a, Self>) -> PResult> { + Ok(Vec::new()) + } + + /// Parses `USING expr` after a column's new type. + fn parse_alter_type_using<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult>> { + Ok(None) + } + + /// Parses a `SET` statement. + fn parse_set<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_set(p) + } + + /// Parses options written directly after `EXPLAIN`. + fn parse_explain_options<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(Vec::new()) + } + + /// Parses what `EXPLAIN` or `DESCRIBE` applies to. + fn parse_explain_target<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_explain_target(p) + } + + /// Consumes a kind of object that only this dialect can `DROP`. + fn parse_drop_object_type<'a>(_p: &mut Parser<'a, Self>) -> Option> { + None + } + + /// Parses a part of a name after a dot, where reserved words are allowed. + fn parse_name_part<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_name_part(p) + } + + /// Parses one part of an object's name, given the parts before it. + fn parse_object_name_part<'a>( + p: &mut Parser<'a, Self>, + before: &[Ident<'a>], + ) -> PResult> { + grammar::parse_object_name_part(p, before) + } + + /// Parses the table on the right of a join. `has_constraint` is false for a + /// natural or cross join, which takes no `ON` or `USING`. + fn parse_join_table<'a>( + p: &mut Parser<'a, Self>, + _has_constraint: bool, + ) -> PResult> { + Self::parse_table_ref(p) + } + + /// Parses `CONNECT BY` and `START WITH` clauses, in dialects with them. + fn parse_connect_by<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + let _ = p; + Ok(Vec::new()) + } + + /// Parses one item of a `GROUP BY` list. + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + p.parse_expr() + } + + fn parse_select_modifiers<'a>(_p: &mut Parser<'a, Self>) -> PResult> { + Ok(Default::default()) + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_select_item(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_table_ref(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_table_factor(p) + } + + fn parse_cte<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_cte(p) + } + + fn parse_table_with_joins<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult> { + grammar::parse_table_with_joins(p) + } + + /// Parses the next join of a `FROM` item, or returns `None` if there is + /// no join at the current token. + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_join(p) + } + + /// Parses `IGNORE NULLS` or `RESPECT NULLS` inside a call's parentheses, + /// after its arguments. The core only has them after the parentheses. + fn parse_function_arg_null_treatment<'a>( + _p: &mut Parser<'a, Self>, + ) -> PResult> { + Ok(None) + } + + /// Parses a call's arguments, after any quantifier. + fn parse_function_args<'a>( + p: &mut Parser<'a, Self>, + quantifier: SetQuantifier, + ) -> PResult>> { + grammar::parse_function_args(p, quantifier) + } + + /// Parses one argument of a call. + fn parse_function_arg<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_function_arg(p) + } + + /// Parses a call's parenthesized arguments, with the current token on `(`. + fn parse_function_call<'a>( + p: &mut Parser<'a, Self>, + name: ObjectName<'a>, + ) -> PResult> { + grammar::parse_function_call(p, name) + } + + fn parse_order_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_order_by_item(p) + } + + /// Parses what follows `ORDER BY` at the end of a query. + fn parse_query_order_by<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + p.parse_comma_separated(Self::parse_order_by_item) + } + + /// Parses what follows the `LIMIT` keyword. + fn parse_limit<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_limit(p) + } + + /// Parses the part that `EXTRACT` takes. The text is kept as written, + /// with any quotes. + /// True if the unquoted word `name` before a string makes it a literal of + /// that type, as `DATE` does in `DATE '2020-01-01'`. + #[inline] + fn is_typed_string_type(name: &str) -> bool { + grammar::is_typed_string_type(name) + } + + /// True if the unquoted word `word`, without parentheses after it, calls a + /// function rather than naming a column, as `CURRENT_DATE` does. + #[inline] + fn is_niladic_function(word: &str) -> bool { + grammar::is_niladic_function(word) + } + + /// Parses the offset of a window frame bound, before `PRECEDING` or + /// `FOLLOWING`. + fn parse_frame_offset<'a>(p: &mut Parser<'a, Self>) -> PResult> { + p.parse_expr() + } + + fn parse_extract_field<'a>(p: &mut Parser<'a, Self>) -> PResult<&'a str> { + grammar::parse_date_time_field(p) + } + + /// Parses what follows the `INTERVAL` keyword. + fn parse_interval<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_interval(p, true) + } + + /// The prefix half of the Pratt parser. + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_prefix(p) + } + + /// The infix half of the Pratt parser: how to parse the operator at the + /// current token, or `None` if it is not an infix operator. + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + grammar::infix_rule(p) + } +} + +/// The core grammar with no overrides. +#[derive(Debug, Clone, PartialEq)] +pub struct Core; + +impl Dialect for Core { + type Ext = Builtin; +} diff --git a/sqlparser_v2/src/dialect/mssql.rs b/sqlparser_v2/src/dialect/mssql.rs new file mode 100644 index 0000000000..3bcf89de0b --- /dev/null +++ b/sqlparser_v2/src/dialect/mssql.rs @@ -0,0 +1,2830 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Microsoft SQL Server (T-SQL). + +use std::borrow::Cow; +use std::fmt::{self, Display as _}; + +use crate::PResult; +use crate::ast::{ + BinaryOp, ColumnDef, ColumnOption, CreateFlags, CreateSchema, CreateTable, CreateView, + DataType, DataTypeSuffix, DropBehavior, Expr, ExprKind, GrantObjects, Grantee, Ident, + IdentityParams, InsertSource, IsTest, Join, JoinConstraint, JoinKind, ObjectName, ObjectType, + OutputClause, Privileges, Query, RoutineArg, Select, SelectInto, SelectItem, SelectItemKind, + SetQuantifier, Span, Statement, StatementKind, StringLiteral, TableFactor, TableRef, + TableWithJoins, TimeTravel, +}; +use crate::dialect::builtin::{ + BuiltinExpr, BuiltinQueryClauses, BuiltinQueryTail, BuiltinSelect, BuiltinStatement, + BuiltinTableFactor, +}; +use crate::dialect::{Builtin, Dialect}; +use crate::display::{Indent, SpaceOrNewline, comma}; +use crate::grammar::{self, parse_object_name, prec}; +use crate::lexer::{self, LexResult, Lexeme, Token, TokenKind, quoted}; +use crate::parser::{InfixRule, Parser}; + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSql; + +/// Statements only Microsoft SQL Server has. +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlStatement<'a> { + /// `BEGIN ... END` used as a statement. + Block(Vec>), + /// `BEGIN TRY`, `END TRY`, `BEGIN CATCH` or `END CATCH`. + TryCatch(Cow<'a, str>), + If(Box>), + While(Box>), + /// `DECLARE item, ...` + Declare(Vec>), + Print(Box>), + RaisError(Box>), + /// `THROW [number, message, state]` + Throw(Option; 3]>>), + /// `WAITFOR {DELAY | TIME} expr` + WaitFor { + delay: bool, + expr: Box>, + }, + Return(Option>>), + Open(Ident<'a>), + /// `CLOSE name`, or `CLOSE ALL` when there is no name. + Close(Option>), + Fetch(Box>), + Deallocate { + prepare: bool, + name: Ident<'a>, + }, + Execute(Box>), + CreateProcedure(Box>), + CreateFunction(Box>), + CreateTrigger(Box>), + CreateRole(Box>), + AlterRole(Box>), + Deny(Box>), + /// `SET` without an assignment operator, such as `SET NOCOUNT ON`. + SessionParam(Box>), + /// `CREATE TABLE ... WITH (...)` + CreateTable(Box>), + CreateOrAlterView(Box>), +} + +/// The statements in a `BEGIN ... END` block or a bare sequence. +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlBody<'a> { + Statements(Vec>), + Block(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlIf<'a> { + pub condition: Expr<'a, Builtin>, + pub then_branch: MsSqlBody<'a>, + pub else_branch: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlWhile<'a> { + pub condition: Expr<'a, Builtin>, + pub body: MsSqlBody<'a>, +} + +/// One item of `DECLARE`. +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlDeclare<'a> { + pub name: Ident<'a>, + pub cursor: bool, + pub for_query: Option>>, + pub data_type: Option>, + pub assignment: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlRaisError<'a> { + pub message: Expr<'a, Builtin>, + pub severity: Expr<'a, Builtin>, + pub state: Expr<'a, Builtin>, + pub arguments: Vec>, + pub options: Vec>, +} + +/// `FETCH [direction] {FROM | IN} name [INTO target]` +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlFetch<'a> { + /// `NEXT`, `FORWARD ALL` and so on; empty for a bare count. + pub direction: Cow<'a, str>, + pub count: Option>, + pub from: bool, + pub name: Ident<'a>, + pub into: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlExecute<'a> { + pub name: Option>, + pub parameters: Vec>, + pub has_parentheses: bool, + pub into: Vec>, + pub using: Vec<(Expr<'a, Builtin>, Option>)>, + pub output: bool, + pub default: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlCreateProcedure<'a> { + pub or_alter: bool, + pub name: ObjectName<'a>, + /// `None` when the name has no parentheses. + pub params: Option>>, + pub language: Option>, + pub body: MsSqlBody<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlCreateFunction<'a> { + pub or_alter: bool, + pub name: ObjectName<'a>, + pub params: Vec>, + pub returns: MsSqlReturns<'a>, + pub body: MsSqlFunctionBody<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlReturns<'a> { + Type(DataType<'a>), + /// `TABLE (...)`, or `@name TABLE (...)`. + Table { + name: Option>, + columns: Vec>, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlFunctionBody<'a> { + Block(Vec>), + /// `AS RETURN expr` + ReturnExpr(Expr<'a, Builtin>), + /// `AS RETURN SELECT ...` + ReturnSelect(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlCreateTrigger<'a> { + pub or_alter: bool, + pub name: ObjectName<'a>, + pub table: ObjectName<'a>, + /// `FOR`, `AFTER`, `BEFORE` or `INSTEAD OF`. + pub period: Cow<'a, str>, + pub events: Vec>, + pub body: MsSqlBody<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlTriggerEvent<'a> { + Insert, + Update(Vec>), + Delete, + Truncate, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlCreateRole<'a> { + pub if_not_exists: bool, + pub names: Vec>, + pub authorization: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlAlterRole<'a> { + pub name: Ident<'a>, + pub operation: MsSqlAlterRoleOp<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlAlterRoleOp<'a> { + AddMember(Ident<'a>), + DropMember(Ident<'a>), + Rename(Ident<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlDeny<'a> { + pub privileges: Privileges<'a>, + pub objects: GrantObjects<'a>, + pub grantees: Vec>, + pub behavior: Option, + pub as_grantor: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlSessionParam<'a> { + /// `SET name, ... value` + Generic { + names: Vec>, + value: Expr<'a, Builtin>, + }, + /// `SET STATISTICS topic {ON | OFF}` + Statistics { topic: Cow<'a, str>, on: bool }, + /// `SET IDENTITY_INSERT table {ON | OFF}` + IdentityInsert { table: ObjectName<'a>, on: bool }, + /// `SET OFFSETS keyword, ... {ON | OFF}` + Offsets { + keywords: Vec>, + on: bool, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlTableOption<'a> { + KeyValue { + key: ObjectName<'a>, + value: Expr<'a, Builtin>, + }, + Heap, + ClusteredColumnstore, + ClusteredColumnstoreOrder(Vec>), + /// `CLUSTERED INDEX (column [ASC | DESC], ...)` + ClusteredIndex(Vec<(Ident<'a>, Option)>), + /// `PARTITION (column RANGE [LEFT | RIGHT] FOR VALUES (...))` + Partition { + column: Ident<'a>, + direction: Option>, + values: Vec>, + }, +} + +/// Expressions only Microsoft SQL Server has. +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlExpr<'a> { + /// `[TRY_]CONVERT(type, expr [, style...])` + Convert(Box>), + /// `JSON_OBJECT(...)` or `JSON_ARRAY(...)` + JsonCall(Box>), + /// `expr.name(args)` + Method(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlMethod<'a> { + pub expr: Expr<'a, Builtin>, + pub name: Ident<'a>, + pub args: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlConvert<'a> { + pub is_try: bool, + pub data_type: DataType<'a>, + pub expr: Expr<'a, Builtin>, + pub styles: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlJsonCall<'a> { + pub name: Ident<'a>, + pub args: Vec>, + /// `ABSENT ON NULL` or `NULL ON NULL`. + pub null_clause: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlJsonArg<'a> { + Value(Expr<'a, Builtin>), + /// `key : value` + KeyValue(Expr<'a, Builtin>, Expr<'a, Builtin>), +} + +/// `TOP n` or `TOP (expr)`. +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlTop<'a> { + pub quantity: Expr<'a, Builtin>, + pub parenthesized: bool, + pub percent: bool, + pub with_ties: bool, +} + +/// A table factor only Microsoft SQL Server has. +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlTableFactor<'a> { + /// A table followed by `WITH (hint, ...)`, including any alias. + Hinted(Box>), + OpenJson(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlHintedTable<'a> { + pub table: TableRef<'a, Builtin>, + pub hints: Vec>, +} + +/// `OPENJSON(expr [, path]) [WITH (column, ...)]` +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlOpenJson<'a> { + pub expr: Expr<'a, Builtin>, + pub path: Option>, + pub columns: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlOpenJsonColumn<'a> { + pub name: Ident<'a>, + pub data_type: DataType<'a>, + pub path: Option>, + pub as_json: bool, +} + +/// `FOR XML`, `FOR JSON` or `FOR BROWSE` at the end of a query. +#[derive(Debug, Clone, PartialEq)] +pub enum MsSqlForClause<'a> { + Browse, + Xml(MsSqlForXml<'a>), + Json(MsSqlForJson<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlForXml<'a> { + /// `RAW`, `AUTO`, `EXPLICIT` or `PATH`. + pub mode: Cow<'a, str>, + pub mode_name: Option>, + pub elements: bool, + pub binary_base64: bool, + pub root: Option>, + pub type_directive: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MsSqlForJson<'a> { + /// `AUTO` or `PATH`. + pub mode: Cow<'a, str>, + pub root: Option>, + pub include_null_values: bool, + pub without_array_wrapper: bool, +} + +/// Words that can never be an alias, even after `AS`. +const NON_ALIAS_KEYWORDS: [&str; 18] = [ + "IF", + "ELSE", + "DECLARE", + "EXEC", + "EXECUTE", + "INSERT", + "UPDATE", + "DELETE", + "DROP", + "CREATE", + "ALTER", + "TRUNCATE", + "PRINT", + "WHILE", + "RETURN", + "THROW", + "RAISERROR", + "MERGE", +]; + +#[inline] +fn is_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'@' | b'$' | b'#') || !byte.is_ascii() +} + +/// Lexes a word that can hold `@`, `#` or `$`. +fn lex_word(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let first = bytes[0]; + if !first.is_ascii_alphabetic() && !matches!(first, b'_' | b'@' | b'#') && first.is_ascii() { + return None; + } + if matches!(first, b'x' | b'X') && bytes.get(1) == Some(&b'\'') { + return None; + } + let len = bytes.iter().take_while(|&&b| is_name_byte(b)).count(); + // A name needs more than `@` signs, or `a <@@> b` would read as columns. + if first == b'@' && bytes[..len].iter().all(|&b| b == b'@') { + return Some(Err("expected a name after @")); + } + Some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })) +} + +/// Lexes `[name]`, in which `]]` escapes a closing bracket. +fn bracketed(rest: &str) -> LexResult { + let bytes = rest.as_bytes(); + let mut i = 1; + while i < bytes.len() { + if bytes[i] == b']' { + if bytes.get(i + 1) == Some(&b']') { + i += 2; + continue; + } + return Ok(Lexeme { + kind: TokenKind::QuotedIdent, + len: i + 1, + }); + } + i += 1; + } + Err("unterminated [ identifier") +} + +/// Lexes a money literal: `$` followed by digits and a fraction. +fn lex_money(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let digits = bytes[1..].iter().take_while(|b| b.is_ascii_digit()).count(); + if digits == 0 || bytes.get(1 + digits) != Some(&b'.') { + return None; + } + let fraction = bytes[digits + 2..] + .iter() + .take_while(|b| b.is_ascii_digit()) + .count(); + Some(Ok(Lexeme { + kind: TokenKind::Placeholder, + len: 1 + digits + 1 + fraction, + })) +} + +/// Treats non-ASCII whitespace, which the core lexer does not skip, as a comment. +#[inline] +fn lex_comment(rest: &str) -> Option> { + if !rest.as_bytes()[0].is_ascii() { + let ch = rest.chars().next()?; + if ch.is_whitespace() { + return Some(Ok(ch.len_utf8())); + } + } + lexer::lex_core_comment(rest) +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + match rest.as_bytes() { + [b'[', ..] => Some(bracketed(rest)), + [b'N' | b'n', b'\'', ..] => { + Some(quoted(&rest[1..], TokenKind::String).map(|lexeme| Lexeme { + kind: TokenKind::String, + len: lexeme.len + 1, + })) + } + [b'{' | b'}', ..] => Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })), + [b'$', ..] => lex_money(rest), + // A `:` is punctuation here, since JSON functions separate keys and + // values with it and a key can be written without a space before it. + [b':', ..] => Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })), + // `=>` has no meaning in T-SQL, so it stays two tokens. + [b'=', b'>', ..] => Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })), + _ => lex_word(rest), + } +} + +/// Builds a string literal, removing a leading `N`. +pub fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + grammar::national_string_literal(token) +} + +fn is_any(token: Token<'_>, words: &[&str]) -> bool { + token.kind == TokenKind::Word && words.iter().any(|word| token.is_word(word)) +} + +fn at_any<'a, D: Dialect>(p: &Parser<'a, D>, words: &[&str]) -> bool { + is_any(p.peek(), words) +} + +fn mssql_statement<'a>(statement: MsSqlStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::MsSql(statement)).into() +} + +/// Parses statements until `END` or the end of input, with an optional `;` +/// after each one. +fn parse_loose_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut statements = Vec::new(); + while !p.at_eof() && !p.at_keyword("END") { + statements.push(p.nested(Parser::parse_statement)?); + while p.eat_op(";") {} + } + Ok(statements) +} + +/// Parses statements until `END` or the end of input, each followed by `;`. +fn parse_strict_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut statements = Vec::new(); + while !p.at_eof() && !p.at_keyword("END") { + statements.push(p.nested(Parser::parse_statement)?); + p.expect_op(";")?; + } + Ok(statements) +} + +/// Parses a `BEGIN ... END` block, or else a sequence of statements. +fn parse_body<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("BEGIN") { + let statements = parse_strict_list(p)?; + p.expect_keyword("END")?; + Ok(MsSqlBody::Block(statements)) + } else { + parse_strict_list(p).map(MsSqlBody::Statements) + } +} + +/// Parses one branch of `IF`: a loose `BEGIN ... END` block or one statement. +fn parse_if_branch<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("BEGIN") { + let statements = parse_loose_list(p)?; + p.expect_keyword("END")?; + Ok(MsSqlBody::Block(statements)) + } else { + let statement = p.nested(Parser::parse_statement)?; + Ok(MsSqlBody::Statements(vec![statement])) + } +} + +fn parse_if<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("IF")?; + let condition = p.parse_expr()?; + let then_branch = parse_if_branch(p)?; + let mut semicolons = 0; + while p.peek_nth(semicolons).is_op(";") { + semicolons += 1; + } + let else_branch = if p.peek_nth(semicolons).is_word("ELSE") { + for _ in 0..=semicolons { + p.advance(); + } + Some(parse_if_branch(p)?) + } else { + None + }; + Ok(mssql_statement(MsSqlStatement::If(Box::new(MsSqlIf { + condition, + then_branch, + else_branch, + })))) +} + +fn parse_while<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("WHILE")?; + let condition = p.parse_expr()?; + let body = parse_body(p)?; + Ok(mssql_statement(MsSqlStatement::While(Box::new( + MsSqlWhile { condition, body }, + )))) +} + +/// True at a `BEGIN` that starts a transaction or a `TRY`/`CATCH` marker +/// rather than a block. +fn at_transaction_begin<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + next.is_op(";") + || next.kind == TokenKind::Eof + || is_any( + next, + &[ + "TRANSACTION", + "WORK", + "TRAN", + "TRY", + "CATCH", + "DEFERRED", + "IMMEDIATE", + "EXCLUSIVE", + ], + ) +} + +fn parse_declare_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + if !name.text.starts_with('@') && !p.at_keyword("CURSOR") { + return Err(p.expected("a variable name starting with @, or CURSOR")); + } + let cursor = p.eat_keyword("CURSOR"); + let data_type = if cursor { + None + } else { + p.eat_keyword("AS"); + Some(D::parse_data_type(p)?) + }; + let for_query = if p.eat_keyword("FOR") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + let assignment = if for_query.is_none() && p.eat_op("=") { + Some(p.parse_expr()?) + } else { + None + }; + Ok(MsSqlDeclare { + name, + cursor, + for_query, + data_type, + assignment, + }) +} + +fn parse_raiserror<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.expect_op("(")?; + let message = p.parse_expr()?; + p.expect_op(",")?; + let severity = p.parse_expr()?; + p.expect_op(",")?; + let state = p.parse_expr()?; + let mut arguments = Vec::new(); + while p.eat_op(",") { + arguments.push(p.parse_expr()?); + } + p.expect_op(")")?; + let options = if p.eat_keyword("WITH") { + p.parse_comma_separated(|p| { + for option in ["LOG", "NOWAIT", "SETERROR"] { + if p.eat_keyword(option) { + return Ok(option); + } + } + Err(p.expected("LOG, NOWAIT or SETERROR")) + })? + } else { + Vec::new() + }; + Ok(MsSqlRaisError { + message, + severity, + state, + arguments, + options: options.into_iter().map(Cow::Borrowed).collect(), + }) +} + +/// True at the end of a statement that takes no operand, where a statement +/// list inside `BEGIN ... END` may continue without a semicolon. +fn at_operand_end<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_eof() || p.at_op(";") || p.at_keyword("END") || p.at_keyword("ELSE") +} + +fn parse_throw<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let args = if at_operand_end(p) { + None + } else { + let number = p.parse_expr()?; + p.expect_op(",")?; + let message = p.parse_expr()?; + p.expect_op(",")?; + let state = p.parse_expr()?; + Some(Box::new([number, message, state])) + }; + Ok(mssql_statement(MsSqlStatement::Throw(args))) +} + +fn parse_waitfor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let delay = if p.eat_keyword("DELAY") { + true + } else { + p.expect_keyword("TIME")?; + false + }; + let expr = Box::new(p.parse_expr()?); + Ok(mssql_statement(MsSqlStatement::WaitFor { delay, expr })) +} + +fn parse_return<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let value = if at_operand_end(p) { + None + } else { + Some(Box::new(p.parse_expr()?)) + }; + Ok(mssql_statement(MsSqlStatement::Return(value))) +} + +fn parse_fetch<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let mut count = None; + let direction = if p.eat_keyword("NEXT") { + "NEXT" + } else if p.eat_keyword("PRIOR") { + "PRIOR" + } else if p.eat_keyword("FIRST") { + "FIRST" + } else if p.eat_keyword("LAST") { + "LAST" + } else if p.eat_keyword("ABSOLUTE") { + count = Some(grammar::parse_number_text(p)?); + "ABSOLUTE" + } else if p.eat_keyword("RELATIVE") { + count = Some(grammar::parse_number_text(p)?); + "RELATIVE" + } else if p.eat_keyword("FORWARD") { + if p.eat_keyword("ALL") { + "FORWARD ALL" + } else { + count = Some(grammar::parse_number_text(p)?); + "FORWARD" + } + } else if p.eat_keyword("BACKWARD") { + if p.eat_keyword("ALL") { + "BACKWARD ALL" + } else { + count = Some(grammar::parse_number_text(p)?); + "BACKWARD" + } + } else if p.eat_keyword("ALL") { + "ALL" + } else { + count = Some(grammar::parse_number_text(p)?); + "" + }; + let from = if p.eat_keyword("FROM") { + true + } else { + p.expect_keyword("IN")?; + false + }; + let name = p.parse_ident()?; + let into = if p.eat_keyword("INTO") { + Some(parse_object_name(p)?) + } else { + None + }; + Ok(mssql_statement(MsSqlStatement::Fetch(Box::new( + MsSqlFetch { + direction: direction.into(), + count: count.map(Cow::Borrowed), + from, + name, + into, + }, + )))) +} + +fn parse_execute<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let name = if p.at_op("(") || p.peek().kind == TokenKind::String { + None + } else { + Some(parse_object_name(p)?) + }; + let has_parentheses = p.eat_op("("); + let parameters = if at_execute_end(p, has_parentheses) { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + if has_parentheses { + p.expect_op(")")?; + } + let into = if p.eat_keyword("INTO") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + let using = if p.eat_keyword("USING") { + p.parse_comma_separated(|p| { + let expr = p.parse_expr()?; + let alias = grammar::parse_optional_alias(p)?; + Ok((expr, alias)) + })? + } else { + Vec::new() + }; + let output = p.eat_keyword("OUTPUT"); + let default = p.eat_keyword("DEFAULT"); + Ok(MsSqlExecute { + name, + parameters, + has_parentheses, + into, + using, + output, + default, + }) +} + +fn at_execute_end<'a, D: Dialect>(p: &Parser<'a, D>, has_parentheses: bool) -> bool { + if has_parentheses { + return p.at_op(")"); + } + at_operand_end(p) || at_any(p, &["USING", "OUTPUT", "DEFAULT"]) +} + +fn parse_deny<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let privileges = grammar::parse_privileges(p)?; + p.expect_keyword("ON")?; + let objects = grammar::parse_grant_objects(p)?; + p.expect_keyword("TO")?; + let grantees = D::parse_grantees(p)?; + let behavior = if p.eat_keyword("CASCADE") { + Some(DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(DropBehavior::Restrict) + } else { + None + }; + let as_grantor = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + Ok(mssql_statement(MsSqlStatement::Deny(Box::new(MsSqlDeny { + privileges, + objects, + grantees, + behavior, + as_grantor, + })))) +} + +fn parse_alter_role<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + let name = p.parse_ident()?; + let operation = if p.eat_keyword("ADD") { + p.expect_keyword("MEMBER")?; + MsSqlAlterRoleOp::AddMember(p.parse_ident()?) + } else if p.eat_keyword("DROP") { + p.expect_keyword("MEMBER")?; + MsSqlAlterRoleOp::DropMember(p.parse_ident()?) + } else if p.eat_keyword("RENAME") { + // The form this crate renders, as the original does. + p.expect_keyword("TO")?; + MsSqlAlterRoleOp::Rename(p.parse_ident()?) + } else { + p.expect_keyword("WITH")?; + p.expect_keyword("NAME")?; + p.expect_op("=")?; + MsSqlAlterRoleOp::Rename(p.parse_ident()?) + }; + Ok(mssql_statement(MsSqlStatement::AlterRole(Box::new( + MsSqlAlterRole { name, operation }, + )))) +} + +/// True at `SET` when what follows is not a variable assignment or one of the +/// core's special forms. +fn at_session_param<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if grammar::at_special_set(p) || is_any(p.peek_nth(1), &["LOCAL", "SESSION", "GLOBAL"]) { + return false; + } + let mut n = 1; + if !matches!(p.peek_nth(n).kind, TokenKind::Word | TokenKind::QuotedIdent) { + return false; + } + while p.peek_nth(n + 1).is_op(".") { + n += 2; + } + let after = p.peek_nth(n + 1); + !(after.is_op("=") || after.is_word("TO")) +} + +/// Reads a word, in any form, as text for `SET name, ... value`. +fn parse_session_word<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.peek(); + if !matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) { + return Err(p.expected("a session parameter name")); + } + p.advance(); + Ok(token.text) +} + +fn parse_on_off<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + if p.eat_keyword("ON") { + Ok(true) + } else { + p.expect_keyword("OFF")?; + Ok(false) + } +} + +/// Parses the value of a `SET` session parameter. A word on its own, such as +/// `ON` or `dmy`, is taken as written. +fn parse_session_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + let next = p.peek_nth(1); + if token.kind == TokenKind::Word && !next.is_op("(") && !next.is_op(".") { + p.advance(); + return Ok(Expr::new( + ExprKind::Ident(Ident { + text: token.text.into(), + quote: None, + span: token.span, + }), + token.span, + )); + } + p.parse_expr() +} + +fn parse_session_param<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SET")?; + let param = if p.eat_keyword("STATISTICS") { + let topic = ["IO", "PROFILE", "TIME", "XML"] + .into_iter() + .find(|topic| p.eat_keyword(topic)) + .ok_or_else(|| p.expected("IO, PROFILE, TIME or XML"))?; + MsSqlSessionParam::Statistics { + topic: topic.into(), + on: parse_on_off(p)?, + } + } else if p.eat_keyword("IDENTITY_INSERT") { + let table = parse_object_name(p)?; + MsSqlSessionParam::IdentityInsert { + table, + on: parse_on_off(p)?, + } + } else if p.eat_keyword("OFFSETS") { + let keywords = p.parse_comma_separated(parse_session_word)?; + MsSqlSessionParam::Offsets { + keywords: keywords.into_iter().map(Cow::Borrowed).collect(), + on: parse_on_off(p)?, + } + } else { + let names = p.parse_comma_separated(parse_session_word)?; + let value = parse_session_value(p)?; + MsSqlSessionParam::Generic { + names: names.into_iter().map(Cow::Borrowed).collect(), + value, + } + }; + Ok(mssql_statement(MsSqlStatement::SessionParam(Box::new( + param, + )))) +} + +fn parse_routine_params<'a, D: Dialect>( + p: &mut Parser<'a, D>, + allow_modes: bool, +) -> PResult>> { + p.expect_op("(")?; + if p.eat_op(")") { + return Ok(Vec::new()); + } + let params = p.parse_comma_separated(|p| { + let mode = if allow_modes { + ["IN", "OUT", "INOUT"] + .into_iter() + .find(|mode| p.eat_keyword(mode)) + } else { + None + }; + let name = Some(p.parse_ident()?); + let data_type = D::parse_data_type(p)?; + let default = if p.eat_op("=") { + Some((true, p.parse_expr()?)) + } else { + None + }; + Ok(RoutineArg { + mode: mode.map(Cow::Borrowed), + name, + data_type, + default, + }) + })?; + p.expect_op(")")?; + Ok(params) +} + +fn parse_create_procedure<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_alter: bool, +) -> PResult> { + let name = parse_object_name(p)?; + let params = if p.at_op("(") { + Some(parse_routine_params(p, true)?) + } else { + None + }; + let language = if p.eat_keyword("LANGUAGE") { + Some(p.parse_ident()?) + } else { + None + }; + p.expect_keyword("AS")?; + let body = parse_body(p)?; + Ok(mssql_statement(MsSqlStatement::CreateProcedure(Box::new( + MsSqlCreateProcedure { + or_alter, + name, + params, + language, + body, + }, + )))) +} + +fn parse_table_columns<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + let columns = p.parse_comma_separated(D::parse_column_def)?; + p.expect_op(")")?; + Ok(columns) +} + +fn parse_returns<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("TABLE") && p.peek_nth(1).is_op("(") { + p.advance(); + return Ok(MsSqlReturns::Table { + name: None, + columns: parse_table_columns(p)?, + }); + } + if p.peek_nth(1).is_word("TABLE") && p.at_ident() { + let name = Some(p.parse_ident()?); + p.advance(); + return Ok(MsSqlReturns::Table { + name, + columns: parse_table_columns(p)?, + }); + } + D::parse_data_type(p).map(MsSqlReturns::Type) +} + +fn parse_create_function<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_alter: bool, +) -> PResult> { + let name = parse_object_name(p)?; + let params = parse_routine_params(p, false)?; + p.expect_keyword("RETURNS")?; + let returns = parse_returns(p)?; + p.eat_keyword("AS"); + let body = if p.eat_keyword("BEGIN") { + let statements = parse_strict_list(p)?; + p.expect_keyword("END")?; + MsSqlFunctionBody::Block(statements) + } else if p.eat_keyword("RETURN") { + if p.at_op("(") { + MsSqlFunctionBody::ReturnExpr(p.parse_expr()?) + } else if p.at_keyword("SELECT") { + MsSqlFunctionBody::ReturnSelect(Box::new(D::parse_select(p)?)) + } else { + return Err(p.expected("a subquery or SELECT after RETURN")); + } + } else { + return Err(p.expected("BEGIN or RETURN")); + }; + Ok(mssql_statement(MsSqlStatement::CreateFunction(Box::new( + MsSqlCreateFunction { + or_alter, + name, + params, + returns, + body, + }, + )))) +} + +fn parse_trigger_event<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("INSERT") { + return Ok(MsSqlTriggerEvent::Insert); + } + if p.eat_keyword("DELETE") { + return Ok(MsSqlTriggerEvent::Delete); + } + if p.eat_keyword("TRUNCATE") { + return Ok(MsSqlTriggerEvent::Truncate); + } + p.expect_keyword("UPDATE")?; + let columns = if p.eat_keyword("OF") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + Ok(MsSqlTriggerEvent::Update(columns)) +} + +fn parse_create_trigger<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_alter: bool, +) -> PResult> { + let name = parse_object_name(p)?; + p.expect_keyword("ON")?; + let table = parse_object_name(p)?; + let period = if p.eat_keyword("FOR") { + "FOR" + } else if p.eat_keyword("AFTER") { + "AFTER" + } else if p.eat_keyword("BEFORE") { + "BEFORE" + } else if p.eat_keyword("INSTEAD") { + p.expect_keyword("OF")?; + "INSTEAD OF" + } else { + return Err(p.expected("FOR, AFTER or INSTEAD OF")); + }; + let events = p.parse_comma_separated(parse_trigger_event)?; + p.expect_keyword("AS")?; + let body = parse_body(p)?; + Ok(mssql_statement(MsSqlStatement::CreateTrigger(Box::new( + MsSqlCreateTrigger { + or_alter, + name, + table, + period: period.into(), + events, + body, + }, + )))) +} + +fn parse_create_role<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let names = p.parse_comma_separated(parse_object_name)?; + p.eat_keyword("WITH"); + let authorization = if p.eat_keyword("AUTHORIZATION") { + Some(parse_object_name(p)?) + } else { + None + }; + Ok(mssql_statement(MsSqlStatement::CreateRole(Box::new( + MsSqlCreateRole { + if_not_exists, + names, + authorization, + }, + )))) +} + +fn parse_clustered_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + if p.eat_keyword("COLUMNSTORE") { + p.expect_keyword("INDEX")?; + if p.eat_keyword("ORDER") { + return grammar::parse_ident_list(p).map(MsSqlTableOption::ClusteredColumnstoreOrder); + } + return Ok(MsSqlTableOption::ClusteredColumnstore); + } + p.expect_keyword("INDEX")?; + p.expect_op("(")?; + let columns = p.parse_comma_separated(|p| { + let name = p.parse_ident()?; + let asc = if p.eat_keyword("ASC") { + Some(true) + } else if p.eat_keyword("DESC") { + Some(false) + } else { + None + }; + Ok((name, asc)) + })?; + p.expect_op(")")?; + Ok(MsSqlTableOption::ClusteredIndex(columns)) +} + +fn parse_partition_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.expect_op("(")?; + let column = p.parse_ident()?; + p.expect_keyword("RANGE")?; + let direction = if p.eat_keyword("LEFT") { + Some("LEFT") + } else if p.eat_keyword("RIGHT") { + Some("RIGHT") + } else { + None + }; + p.expect_keyword("FOR")?; + p.expect_keyword("VALUES")?; + p.expect_op("(")?; + let values = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + p.expect_op(")")?; + Ok(MsSqlTableOption::Partition { + column, + direction: direction.map(Cow::Borrowed), + values, + }) +} + +fn parse_table_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("HEAP") { + p.advance(); + return Ok(MsSqlTableOption::Heap); + } + if p.at_keyword("PARTITION") { + return parse_partition_option(p); + } + if p.at_keyword("CLUSTERED") { + return parse_clustered_option(p); + } + let mut parts = vec![p.parse_ident()?]; + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + p.expect_op("=")?; + let value = p.parse_expr()?; + Ok(MsSqlTableOption::KeyValue { + key: ObjectName { parts }, + value, + }) +} + +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let or_alter = p.peek_nth(1).is_word("OR") && p.peek_nth(2).is_word("ALTER"); + let object = p.peek_nth(if or_alter { 3 } else { 1 }); + let routine = is_any(object, &["PROCEDURE", "PROC", "FUNCTION", "TRIGGER"]); + if or_alter || routine || object.is_word("ROLE") { + p.advance(); + if or_alter { + p.advance(); + p.advance(); + } + if p.eat_keyword("PROCEDURE") || p.eat_keyword("PROC") { + return parse_create_procedure(p, or_alter); + } + if p.eat_keyword("FUNCTION") { + return parse_create_function(p, or_alter); + } + if p.eat_keyword("TRIGGER") { + return parse_create_trigger(p, or_alter); + } + if p.eat_keyword("ROLE") { + return parse_create_role(p); + } + return D::parse_create_view(p, CreateFlags::default()) + .map(|view| mssql_statement(MsSqlStatement::CreateOrAlterView(Box::new(view)))); + } + let statement = grammar::parse_create(p)?; + if p.at_keyword("WITH") + && p.peek_nth(1).is_op("(") + && let StatementKind::CreateTable(table) = statement.kind + { + p.advance(); + p.advance(); + let options = p.parse_comma_separated(parse_table_option)?; + p.expect_op(")")?; + return Ok(mssql_statement(MsSqlStatement::CreateTable(Box::new( + MsSqlCreateTable { + table: *table, + options, + }, + )))); + } + Ok(statement) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.peek().kind != TokenKind::Word { + return grammar::parse_statement(p); + } + if p.at_keyword("BEGIN") { + if !at_transaction_begin(p) { + p.advance(); + let statements = parse_strict_list(p)?; + p.expect_keyword("END")?; + return Ok(mssql_statement(MsSqlStatement::Block(statements))); + } + if let Some(marker) = parse_try_catch(p) { + return Ok(mssql_statement(MsSqlStatement::TryCatch(marker.into()))); + } + return grammar::parse_statement(p); + } + if p.at_keyword("END") { + if let Some(marker) = parse_try_catch(p) { + return Ok(mssql_statement(MsSqlStatement::TryCatch(marker.into()))); + } + return grammar::parse_statement(p); + } + if p.at_keyword("IF") { + return parse_if(p); + } + if p.at_keyword("WHILE") { + return parse_while(p); + } + if p.at_keyword("DECLARE") { + p.advance(); + let items = p.parse_comma_separated(parse_declare_item)?; + return Ok(mssql_statement(MsSqlStatement::Declare(items))); + } + if p.at_keyword("PRINT") { + p.advance(); + let expr = p.parse_expr()?; + return Ok(mssql_statement(MsSqlStatement::Print(Box::new(expr)))); + } + if p.at_keyword("RAISERROR") { + return parse_raiserror(p) + .map(|raise| mssql_statement(MsSqlStatement::RaisError(Box::new(raise)))); + } + if p.at_keyword("THROW") { + return parse_throw(p); + } + if p.at_keyword("WAITFOR") { + return parse_waitfor(p); + } + if p.at_keyword("RETURN") { + return parse_return(p); + } + if p.at_keyword("OPEN") { + p.advance(); + let name = p.parse_ident()?; + return Ok(mssql_statement(MsSqlStatement::Open(name))); + } + if p.at_keyword("CLOSE") { + p.advance(); + let name = if p.eat_keyword("ALL") { + None + } else { + Some(p.parse_ident()?) + }; + return Ok(mssql_statement(MsSqlStatement::Close(name))); + } + if p.at_keyword("FETCH") { + return parse_fetch(p); + } + if p.at_keyword("DEALLOCATE") { + p.advance(); + let prepare = p.eat_keyword("PREPARE"); + let name = p.parse_ident()?; + return Ok(mssql_statement(MsSqlStatement::Deallocate { + prepare, + name, + })); + } + if p.at_keyword("EXEC") || p.at_keyword("EXECUTE") { + return parse_execute(p) + .map(|execute| mssql_statement(MsSqlStatement::Execute(Box::new(execute)))); + } + if p.at_keyword("DENY") { + return parse_deny(p); + } + if p.at_keyword("ALTER") && p.peek_nth(1).is_word("ROLE") { + return parse_alter_role(p); + } + if grammar::at_alter_view(p) { + return grammar::parse_alter_view(p, true) + .map(|a| StatementKind::AlterView(Box::new(a)).into()); + } + if p.at_keyword("SET") && at_session_param(p) { + return parse_session_param(p); + } + grammar::parse_statement(p) +} + +/// Consumes `BEGIN TRY`, `END TRY`, `BEGIN CATCH` or `END CATCH`, returning +/// its normalized form. +fn parse_try_catch<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option<&'static str> { + let marker = match (p.at_keyword("BEGIN"), p.peek_nth(1)) { + (true, next) if next.is_word("TRY") => "BEGIN TRY", + (true, next) if next.is_word("CATCH") => "BEGIN CATCH", + (false, next) if next.is_word("TRY") => "END TRY", + (false, next) if next.is_word("CATCH") => "END CATCH", + _ => return None, + }; + p.advance(); + p.advance(); + Some(marker) +} + +/// Parses `TOP n` or `TOP (expr)`, with the keyword read. +fn parse_top<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let parenthesized = p.eat_op("("); + let quantity = if parenthesized { + let quantity = p.parse_expr()?; + p.expect_op(")")?; + quantity + } else { + let token = p.expect_kind(TokenKind::Number, "a number after TOP")?; + Expr::new( + ExprKind::Literal(crate::ast::Literal::Number(token.text.into())), + token.span, + ) + }; + let percent = p.eat_keyword("PERCENT"); + let with_ties = p.at_keyword("WITH") && p.peek_nth(1).is_word("TIES"); + if with_ties { + p.advance(); + p.advance(); + } + Ok(MsSqlTop { + quantity, + parenthesized, + percent, + with_ties, + }) +} + +pub fn parse_select_head<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + let quantifier = grammar::parse_quantifier(p); + let mssql_top = if p.eat_keyword("TOP") { + Some(Box::new(parse_top(p)?)) + } else { + None + }; + Ok(( + BuiltinSelect { + mssql_top, + ..Default::default() + }, + quantifier, + )) +} + +fn parse_string_alias<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option> { + let token = p.peek(); + if token.kind != TokenKind::String { + return None; + } + p.advance(); + Some(Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some('\''), + span: token.span, + }) +} + +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, Builtin>, +) -> PResult> { + // `alias = expr` names a select item. + let Expr { kind, span } = expr; + let expr = match kind { + ExprKind::Binary { + left, + op: BinaryOp::Eq, + right, + } if matches!(left.as_ref().kind, ExprKind::Ident(_)) => { + let ExprKind::Ident(alias) = left.kind else { + unreachable!() + }; + return Ok(SelectItemKind::Expr { + expr: *right, + alias: Some(alias), + } + .into()); + } + kind => Expr::new(kind, span), + }; + if p.at_keyword("AS") { + let next = p.peek_nth(1); + if is_any(next, &NON_ALIAS_KEYWORDS) { + return Err(p.expected("an alias")); + } + if next.kind == TokenKind::String { + p.advance(); + let alias = parse_string_alias(p); + return Ok(SelectItemKind::Expr { expr, alias }.into()); + } + } + if let Some(alias) = parse_string_alias(p) { + return Ok(SelectItemKind::Expr { + expr, + alias: Some(alias), + } + .into()); + } + grammar::parse_select_item_alias(p, expr) +} + +pub fn parse_data_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + if p.at_op("(") && p.peek_nth(1).is_word("MAX") && p.peek_nth(2).is_op(")") { + p.advance(); + let max = p.advance(); + p.advance(); + return Ok(DataType { + qualifier: Vec::new(), + name, + angle: None, + args: vec![max.text.into()], + suffix: DataTypeSuffix::None, + array: crate::ast::ArrayType::None, + }); + } + grammar::parse_data_type_after_name(p, name) +} + +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.at_keyword("IDENTITY") { + return grammar::parse_column_option(p); + } + p.advance(); + let params = if p.eat_op("(") { + let seed = grammar::parse_number_text(p)?; + p.expect_op(",")?; + let increment = grammar::parse_number_text(p)?; + p.expect_op(")")?; + Some(IdentityParams { + seed: seed.into(), + increment: increment.into(), + start_form: false, + }) + } else { + None + }; + Ok(Some(ColumnOption::Identity { + autoincrement: false, + params, + order: None, + })) +} + +fn parse_convert<'a, D: Dialect>( + p: &mut Parser<'a, D>, + is_try: bool, +) -> PResult> { + p.expect_op("(")?; + let data_type = D::parse_data_type(p)?; + p.expect_op(",")?; + let expr = p.parse_expr()?; + let mut styles = Vec::new(); + while p.eat_op(",") { + styles.push(p.parse_expr()?); + } + p.expect_op(")")?; + Ok( + ExprKind::Ext(BuiltinExpr::MsSql(MsSqlExpr::Convert(Box::new( + MsSqlConvert { + is_try, + data_type, + expr, + styles, + }, + )))) + .into(), + ) +} + +/// The null clause at the cursor, without consuming it. +fn json_null_clause<'a, D: Dialect>(p: &Parser<'a, D>) -> Option<&'static str> { + if !p.peek_nth(1).is_word("ON") || !p.peek_nth(2).is_word("NULL") { + return None; + } + if p.at_keyword("ABSENT") { + Some("ABSENT ON NULL") + } else if p.at_keyword("NULL") { + Some("NULL ON NULL") + } else { + None + } +} + +fn parse_json_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Ident<'a>, +) -> PResult> { + p.expect_op("(")?; + let mut args = Vec::new(); + let mut null_clause = None; + loop { + if let Some(clause) = json_null_clause(p) { + null_clause = Some(clause); + p.advance(); + p.advance(); + p.advance(); + break; + } + if p.at_op(")") { + break; + } + let key = p.parse_expr()?; + if p.eat_op(":") { + args.push(MsSqlJsonArg::KeyValue(key, p.parse_expr()?)); + } else { + args.push(MsSqlJsonArg::Value(key)); + } + if !p.eat_op(",") && json_null_clause(p).is_none() { + break; + } + } + p.expect_op(")")?; + Ok( + ExprKind::Ext(BuiltinExpr::MsSql(MsSqlExpr::JsonCall(Box::new( + MsSqlJsonCall { + name, + args, + null_clause: null_clause.map(Cow::Borrowed), + }, + )))) + .into(), + ) +} + +pub fn parse_function_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + if let [only] = name.parts.as_slice() + && only.quote.is_none() + { + let text = &only.text; + let type_first = matches!(p.peek_nth(1).kind, TokenKind::Word | TokenKind::QuotedIdent); + // A literal first argument is an ordinary call, as in the original. + if type_first && text.eq_ignore_ascii_case("CONVERT") { + return parse_convert(p, false); + } + if type_first && text.eq_ignore_ascii_case("TRY_CONVERT") { + return parse_convert(p, true); + } + if text.eq_ignore_ascii_case("JSON_OBJECT") || text.eq_ignore_ascii_case("JSON_ARRAY") { + return parse_json_call(p, only.clone()); + } + } + grammar::parse_function_call(p, name) +} + +/// Parses `.name(args)` after an expression, a method call on an XML value. +fn parse_method<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.advance(); + let name = p.parse_name_part()?; + p.expect_op("(")?; + let args = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op(")")?; + // A method call passes through more wrapper types than an ordinary level. + p.deepen_by(2)?; + Ok(ExprKind::Ext(BuiltinExpr::MsSql(MsSqlExpr::Method(Box::new( + MsSqlMethod { + expr: left, + name, + args, + }, + )))) + .into()) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + if p.at_op(".") + && matches!(p.peek_nth(1).kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(2).is_op("(") + { + return Some(InfixRule::custom(prec::POSTFIX, parse_method)); + } + grammar::infix_rule(p) +} + +/// Reads a word as a name, in tables where keywords are allowed. +fn parse_keyword_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Ident<'a> { + let token = p.advance(); + Ident { + text: token.text.into(), + quote: None, + span: token.span, + } +} + +/// True at `db..table`, a name whose schema is left out. +fn at_double_dot<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_ident() && p.peek_nth(1).is_op(".") && p.peek_nth(2).is_op(".") +} + +/// Parses `db..table [.name ...]`, with the empty schema as an empty part. +fn parse_double_dot_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut parts = vec![p.parse_ident()?]; + p.expect_op(".")?; + parts.push(Ident { + text: "".into(), + quote: None, + span: Span::default(), + }); + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + Ok(ObjectName { parts }) +} + +fn parse_openjson<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.expect_op("(")?; + let expr = p.parse_expr()?; + let path = if p.eat_op(",") { + Some(p.parse_expr()?) + } else { + None + }; + p.expect_op(")")?; + let columns = if p.at_keyword("WITH") && p.peek_nth(1).is_op("(") { + p.advance(); + p.advance(); + let columns = p.parse_comma_separated(|p| { + let name = p.parse_ident()?; + let data_type = D::parse_data_type(p)?; + let token = p.peek(); + let path = if token.kind == TokenKind::String { + p.advance(); + Some(D::string_literal(token)) + } else { + None + }; + let as_json = p.eat_keyword("AS"); + if as_json { + p.expect_keyword("JSON")?; + } + Ok(MsSqlOpenJsonColumn { + name, + data_type, + path, + as_json, + }) + })?; + p.expect_op(")")?; + columns + } else { + Vec::new() + }; + Ok(TableFactor::Ext(BuiltinTableFactor::MsSql( + MsSqlTableFactor::OpenJson(Box::new(MsSqlOpenJson { + expr, + path, + columns, + })), + ))) +} + +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("OPENJSON") && p.peek_nth(1).is_op("(") { + return parse_openjson(p); + } + if p.at_keyword("LIMIT") { + return Ok(TableFactor::Named(ObjectName { + parts: vec![parse_keyword_name(p)], + })); + } + let factor = if at_double_dot(p) { + let name = parse_double_dot_name(p)?; + if p.at_op("(") { + let call = Box::new(p.parse_function_call(name)?); + TableFactor::Function { + call, + with_ordinality: false, + } + } else { + TableFactor::Named(name) + } + } else { + grammar::parse_table_factor(p)? + }; + let time_travel = p.at_keyword("FOR") + && p.peek_nth(1).is_word("SYSTEM_TIME") + && p.peek_nth(2).is_word("AS") + && p.peek_nth(3).is_word("OF"); + if time_travel && let TableFactor::Named(name) = factor { + for _ in 0..4 { + p.advance(); + } + let at = p.parse_expr()?; + return Ok(TableFactor::TimeTravel(Box::new(TimeTravel { + name, + kind: "FOR SYSTEM_TIME".into(), + at, + }))); + } + Ok(factor) +} + +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let factor = D::parse_table_factor(p)?; + if p.at_keyword("AS") && is_any(p.peek_nth(1), &NON_ALIAS_KEYWORDS) { + return Err(p.expected("an alias")); + } + let alias = grammar::parse_optional_table_alias(p)?; + let table = TableRef { + factor, + alias, + span: Span::default(), + }; + if !(p.at_keyword("WITH") && p.peek_nth(1).is_op("(")) { + return Ok(table); + } + p.advance(); + p.advance(); + let hints = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(TableRef { + factor: TableFactor::Ext(BuiltinTableFactor::MsSql(MsSqlTableFactor::Hinted( + Box::new(MsSqlHintedTable { table, hints }), + ))), + alias: None, + span: Span::default(), + }) +} + +pub fn parse_join<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let apply = (p.at_keyword("CROSS") || p.at_keyword("OUTER")) && p.peek_nth(1).is_word("APPLY"); + if !apply { + return grammar::parse_join(p); + } + let kind = if p.at_keyword("CROSS") { + JoinKind::Custom("CROSS APPLY".into()) + } else { + JoinKind::Custom("OUTER APPLY".into()) + }; + p.advance(); + p.advance(); + let table = p.parse_table_ref()?; + Ok(Some(Join { + kind, + spelled_out: false, + table, + constraint: JoinConstraint::None, + })) +} + +pub fn parse_output_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if !p.eat_keyword("OUTPUT") { + return Ok(None); + } + let items = D::parse_projection(p)?; + let into = if p.eat_keyword("INTO") { + Some(parse_object_name(p)?) + } else { + None + }; + Ok(Some(Box::new(OutputClause { items, into }))) +} + +/// Parses a string inside parentheses, with the opening one still to read. +fn parse_parenthesized_string<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("(")?; + let token = p.expect_kind(TokenKind::String, "a string")?; + p.expect_op(")")?; + Ok(D::string_literal(token)) +} + +fn parse_for_xml<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mode = if p.eat_keyword("RAW") { + "RAW" + } else if p.eat_keyword("AUTO") { + "AUTO" + } else if p.eat_keyword("EXPLICIT") { + "EXPLICIT" + } else { + p.expect_keyword("PATH")?; + "PATH" + }; + let mode_name = if p.at_op("(") { + Some(parse_parenthesized_string(p)?) + } else { + None + }; + let mut clause = MsSqlForXml { + mode: mode.into(), + mode_name, + elements: false, + binary_base64: false, + root: None, + type_directive: false, + }; + while p.eat_op(",") { + if p.eat_keyword("ELEMENTS") { + clause.elements = true; + } else if p.eat_keyword("BINARY") { + p.expect_keyword("BASE64")?; + clause.binary_base64 = true; + } else if p.eat_keyword("ROOT") { + clause.root = Some(parse_parenthesized_string(p)?); + } else if p.eat_keyword("TYPE") { + clause.type_directive = true; + } else { + return Err(p.expected("a FOR XML directive")); + } + } + Ok(clause) +} + +fn parse_for_json<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mode = if p.eat_keyword("AUTO") { + "AUTO" + } else { + p.expect_keyword("PATH")?; + "PATH" + }; + let mut clause = MsSqlForJson { + mode: mode.into(), + root: None, + include_null_values: false, + without_array_wrapper: false, + }; + while p.eat_op(",") { + if p.eat_keyword("ROOT") { + clause.root = Some(parse_parenthesized_string(p)?); + } else if p.eat_keyword("INCLUDE_NULL_VALUES") { + clause.include_null_values = true; + } else if p.eat_keyword("WITHOUT_ARRAY_WRAPPER") { + clause.without_array_wrapper = true; + } else { + return Err(p.expected("a FOR JSON directive")); + } + } + Ok(clause) +} + +pub fn parse_query_tail<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.at_keyword("FOR") { + return Ok(Default::default()); + } + let next = p.peek_nth(1); + let clause = if next.is_word("XML") { + p.advance(); + p.advance(); + MsSqlForClause::Xml(parse_for_xml(p)?) + } else if next.is_word("JSON") { + p.advance(); + p.advance(); + MsSqlForClause::Json(parse_for_json(p)?) + } else if next.is_word("BROWSE") { + p.advance(); + p.advance(); + MsSqlForClause::Browse + } else { + return Ok(Default::default()); + }; + Ok(BuiltinQueryTail(Some(Box::new( + BuiltinQueryClauses::MsSql(clause), + )))) +} + +pub fn parse_grantees<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + p.parse_comma_separated(grammar::parse_grantee) +} + +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if grammar::at_odbc_escape(p) { + return grammar::parse_odbc_escape(p); + } + let token = p.peek(); + // T-SQL has no boolean literals, so these are ordinary names. + if is_any(token, &["TRUE", "FALSE"]) { + return grammar::parse_name_expr(p); + } + // A `:` is punctuation to the lexer, so `:name` is only a parameter when + // the name follows without a space. + if token.is_op(":") { + let next = p.peek_nth(1); + if matches!(next.kind, TokenKind::Word | TokenKind::Number) + && next.span.start == token.span.end + { + p.advance(); + p.advance(); + return Ok(ExprKind::Placeholder(Cow::Borrowed( + &p.source()[token.span.start as usize..next.span.end as usize], + )) + .into()); + } + } + grammar::parse_prefix(p) +} + +pub fn is_reserved(word: &str) -> bool { + !word.eq_ignore_ascii_case("TRUE") + && !word.eq_ignore_ascii_case("FALSE") + && grammar::is_reserved(word) +} + +/// True for words that cannot follow an expression as a bare alias. +pub fn is_reserved_for_alias(word: &str) -> bool { + grammar::is_reserved_for_alias(word) + || NON_ALIAS_KEYWORDS + .iter() + .chain(&["OUTPUT", "VALUES", "END"]) + .any(|keyword| keyword.eq_ignore_ascii_case(word)) +} + +impl Dialect for MsSql { + /// Recursive CTEs need no keyword here, and `RECURSIVE` is rejected. + fn eat_with_recursive<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + type Ext = Builtin; + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_table(p) + } + + fn parse_is_test<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_is_json(p) + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, true, true) + } + + fn parse_insert_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_insert_source_with_default(p) + } + + fn parse_insert_into<'a>(p: &mut Parser<'a, Self>) -> PResult { + Ok(p.eat_keyword("INTO")) + } + + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + if flags != CreateFlags::default() { + return Err(p.expected("TABLE or VIEW")); + } + grammar::parse_create_schema_authorization(p, true) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + fn is_reserved(word: &str) -> bool { + is_reserved(word) + } + + fn is_reserved_for_alias(word: &str) -> bool { + is_reserved_for_alias(word) + } + + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + string_literal(token) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_select_head<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + parse_select_head(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_join(p) + } + + fn parse_function_call<'a>( + p: &mut Parser<'a, Self>, + name: ObjectName<'a>, + ) -> PResult> { + parse_function_call(p, name) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + /// T-SQL has no `FILTER` clause. + fn parse_function_filter<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + lex_comment(rest) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + if let Some(object_type) = grammar::eat_drop_object_type(p, &["TYPE"]) { + return Some(object_type); + } + grammar::eat_drop_object_type(p, &["TRIGGER"]) + } + + fn parse_output_clause<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + parse_output_clause(p) + } + + fn parse_query_tail<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_query_tail(p) + } + + fn parse_grantees<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_grantees(p) + } +} + +fn write_statements( + f: &mut fmt::Formatter<'_>, + statements: &[Statement<'_, Builtin>], +) -> fmt::Result { + for (i, statement) in statements.iter().enumerate() { + if i > 0 { + SpaceOrNewline.fmt(f)?; + } + write!(f, "{statement};")?; + } + Ok(()) +} + +/// Statements, each on its own line in `{:#}`. +struct StatementLines<'s, 'a>(&'s [Statement<'a, Builtin>]); + +impl fmt::Display for StatementLines<'_, '_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_statements(f, self.0) + } +} + +/// Writes a body after a keyword, on indented lines if it is not a block. +fn write_body_after_keyword(f: &mut fmt::Formatter<'_>, body: &MsSqlBody<'_>) -> fmt::Result { + match body { + MsSqlBody::Statements(statements) => { + SpaceOrNewline.fmt(f)?; + Indent(StatementLines(statements)).fmt(f) + } + MsSqlBody::Block(statements) => { + f.write_str(" ")?; + write_block(f, statements) + } + } +} + +/// Writes ` AS` and a body, which starts on a new line in `{:#}`. +fn write_as_body(f: &mut fmt::Formatter<'_>, body: &MsSqlBody<'_>) -> fmt::Result { + f.write_str(" AS")?; + match body { + MsSqlBody::Statements(_) => write_body_after_keyword(f, body), + MsSqlBody::Block(statements) => { + SpaceOrNewline.fmt(f)?; + write_block(f, statements) + } + } +} + +impl fmt::Display for MsSqlBody<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Statements(statements) => write_statements(f, statements), + Self::Block(statements) => write_block(f, statements), + } + } +} + +fn write_block(f: &mut fmt::Formatter<'_>, statements: &[Statement<'_, Builtin>]) -> fmt::Result { + f.write_str("BEGIN")?; + if !statements.is_empty() { + SpaceOrNewline.fmt(f)?; + Indent(StatementLines(statements)).fmt(f)?; + } + SpaceOrNewline.fmt(f)?; + f.write_str("END") +} + +impl fmt::Display for MsSqlIf<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "IF {}", self.condition)?; + write_body_after_keyword(f, &self.then_branch)?; + if let Some(branch) = &self.else_branch { + SpaceOrNewline.fmt(f)?; + f.write_str("ELSE")?; + write_body_after_keyword(f, branch)?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlWhile<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "WHILE {}", self.condition)?; + write_body_after_keyword(f, &self.body) + } +} + +impl fmt::Display for MsSqlDeclare<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + if self.cursor { + f.write_str(" CURSOR")?; + } + if let Some(query) = &self.for_query { + write!(f, " FOR {query}")?; + } + if let Some(data_type) = &self.data_type { + write!(f, " {data_type}")?; + } + if let Some(value) = &self.assignment { + write!(f, " = {value}")?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlRaisError<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "RAISERROR({}, {}, {}", + self.message, self.severity, self.state + )?; + if !self.arguments.is_empty() { + write!(f, ", {}", comma(&self.arguments))?; + } + f.write_str(")")?; + if !self.options.is_empty() { + write!(f, " WITH {}", comma(&self.options))?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlFetch<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("FETCH ")?; + match (self.direction.as_ref(), &self.count) { + ("", Some(count)) => write!(f, "{count} ")?, + (direction, Some(count)) => write!(f, "{direction} {count} ")?, + (direction, None) => write!(f, "{direction} ")?, + } + write!(f, "{} {}", if self.from { "FROM" } else { "IN" }, self.name)?; + if let Some(into) = &self.into { + write!(f, " INTO {into}")?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlExecute<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("EXECUTE")?; + if let Some(name) = &self.name { + write!(f, " {name}")?; + } + if self.has_parentheses { + let open = if self.name.is_some() { "(" } else { " (" }; + write!(f, "{open}{})", comma(&self.parameters))?; + } else if !self.parameters.is_empty() { + write!(f, " {}", comma(&self.parameters))?; + } + if !self.into.is_empty() { + write!(f, " INTO {}", comma(&self.into))?; + } + if !self.using.is_empty() { + f.write_str(" USING ")?; + for (i, (expr, alias)) in self.using.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + expr.fmt(f)?; + if let Some(alias) = alias { + write!(f, " AS {alias}")?; + } + } + } + if self.output { + f.write_str(" OUTPUT")?; + } + if self.default { + f.write_str(" DEFAULT")?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlCreateProcedure<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "CREATE {}PROCEDURE {}", + if self.or_alter { "OR ALTER " } else { "" }, + self.name + )?; + if let Some(params) = &self.params { + write!(f, " ({})", comma(params))?; + } + if let Some(language) = &self.language { + write!(f, " LANGUAGE {language}")?; + } + write_as_body(f, &self.body) + } +} + +impl fmt::Display for MsSqlReturns<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Type(data_type) => data_type.fmt(f), + Self::Table { name, columns } => { + if let Some(name) = name { + write!(f, "{name} ")?; + } + write!(f, "TABLE ({})", comma(columns)) + } + } + } +} + +impl fmt::Display for MsSqlFunctionBody<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Block(statements) => { + f.write_str("AS")?; + SpaceOrNewline.fmt(f)?; + write_block(f, statements) + } + Self::ReturnExpr(expr) => write!(f, "AS RETURN {expr}"), + Self::ReturnSelect(select) => write!(f, "AS RETURN {select}"), + } + } +} + +impl fmt::Display for MsSqlCreateFunction<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "CREATE {}FUNCTION {}({}) RETURNS {} ", + if self.or_alter { "OR ALTER " } else { "" }, + self.name, + comma(&self.params), + self.returns, + )?; + self.body.fmt(f) + } +} + +impl fmt::Display for MsSqlTriggerEvent<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Insert => f.write_str("INSERT"), + Self::Delete => f.write_str("DELETE"), + Self::Truncate => f.write_str("TRUNCATE"), + Self::Update(columns) if columns.is_empty() => f.write_str("UPDATE"), + Self::Update(columns) => write!(f, "UPDATE OF {}", comma(columns)), + } + } +} + +impl fmt::Display for MsSqlCreateTrigger<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "CREATE {}TRIGGER {} ON {} {} {}", + if self.or_alter { "OR ALTER " } else { "" }, + self.name, + self.table, + self.period, + comma(&self.events), + )?; + write_as_body(f, &self.body) + } +} + +impl fmt::Display for MsSqlCreateRole<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ROLE ")?; + if self.if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + comma(&self.names).fmt(f)?; + if let Some(owner) = &self.authorization { + write!(f, " AUTHORIZATION {owner}")?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlAlterRole<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ALTER ROLE {} ", self.name)?; + match &self.operation { + MsSqlAlterRoleOp::AddMember(member) => write!(f, "ADD MEMBER {member}"), + MsSqlAlterRoleOp::DropMember(member) => write!(f, "DROP MEMBER {member}"), + MsSqlAlterRoleOp::Rename(name) => write!(f, "RENAME TO {name}"), + } + } +} + +impl fmt::Display for MsSqlDeny<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "DENY {} ON {} TO {}", + self.privileges, + self.objects, + comma(&self.grantees) + )?; + match self.behavior { + Some(DropBehavior::Cascade) => f.write_str(" CASCADE")?, + Some(DropBehavior::Restrict) => f.write_str(" RESTRICT")?, + None => {} + } + if let Some(grantor) = &self.as_grantor { + write!(f, " AS {grantor}")?; + } + Ok(()) + } +} + +fn write_on_off(f: &mut fmt::Formatter<'_>, on: bool) -> fmt::Result { + f.write_str(if on { "ON" } else { "OFF" }) +} + +impl fmt::Display for MsSqlSessionParam<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SET ")?; + match self { + Self::Generic { names, value } => write!(f, "{} {value}", comma(names)), + Self::Statistics { topic, on } => { + write!(f, "STATISTICS {topic} ")?; + write_on_off(f, *on) + } + Self::IdentityInsert { table, on } => { + write!(f, "IDENTITY_INSERT {table} ")?; + write_on_off(f, *on) + } + Self::Offsets { keywords, on } => { + write!(f, "OFFSETS {} ", comma(keywords))?; + write_on_off(f, *on) + } + } + } +} + +impl fmt::Display for MsSqlTableOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::KeyValue { key, value } => write!(f, "{key} = {value}"), + Self::Heap => f.write_str("HEAP"), + Self::ClusteredColumnstore => f.write_str("CLUSTERED COLUMNSTORE INDEX"), + Self::ClusteredColumnstoreOrder(columns) => { + write!(f, "CLUSTERED COLUMNSTORE INDEX ORDER ({})", comma(columns)) + } + Self::ClusteredIndex(columns) => { + f.write_str("CLUSTERED INDEX (")?; + for (i, (name, asc)) in columns.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + name.fmt(f)?; + match asc { + Some(true) => f.write_str(" ASC")?, + Some(false) => f.write_str(" DESC")?, + None => {} + } + } + f.write_str(")") + } + Self::Partition { + column, + direction, + values, + } => { + write!(f, "PARTITION ({column} RANGE")?; + if let Some(direction) = direction { + write!(f, " {direction}")?; + } + write!(f, " FOR VALUES ({}))", comma(values)) + } + } + } +} + +impl fmt::Display for MsSqlCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} WITH ({})", self.table, comma(&self.options)) + } +} + +impl fmt::Display for MsSqlStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Block(statements) => write_block(f, statements), + Self::TryCatch(marker) => f.write_str(marker), + Self::If(statement) => statement.fmt(f), + Self::While(statement) => statement.fmt(f), + Self::Declare(items) => write!(f, "DECLARE {}", comma(items)), + Self::Print(expr) => write!(f, "PRINT {expr}"), + Self::RaisError(statement) => statement.fmt(f), + Self::Throw(None) => f.write_str("THROW"), + Self::Throw(Some(args)) => { + let [number, message, state] = args.as_ref(); + write!(f, "THROW {number}, {message}, {state}") + } + Self::WaitFor { delay, expr } => { + write!( + f, + "WAITFOR {} {expr}", + if *delay { "DELAY" } else { "TIME" } + ) + } + Self::Return(None) => f.write_str("RETURN"), + Self::Return(Some(expr)) => write!(f, "RETURN {expr}"), + Self::Open(name) => write!(f, "OPEN {name}"), + Self::Close(None) => f.write_str("CLOSE ALL"), + Self::Close(Some(name)) => write!(f, "CLOSE {name}"), + Self::Fetch(statement) => statement.fmt(f), + Self::Deallocate { prepare, name } => { + write!( + f, + "DEALLOCATE {}{name}", + if *prepare { "PREPARE " } else { "" } + ) + } + Self::Execute(statement) => statement.fmt(f), + Self::CreateProcedure(statement) => statement.fmt(f), + Self::CreateFunction(statement) => statement.fmt(f), + Self::CreateTrigger(statement) => statement.fmt(f), + Self::CreateRole(statement) => statement.fmt(f), + Self::AlterRole(statement) => statement.fmt(f), + Self::Deny(statement) => statement.fmt(f), + Self::SessionParam(statement) => statement.fmt(f), + Self::CreateTable(statement) => statement.fmt(f), + Self::CreateOrAlterView(view) => { + let rendered = view.to_string(); + let rest = rendered.strip_prefix("CREATE ").unwrap_or(&rendered); + write!(f, "CREATE OR ALTER {rest}") + } + } + } +} + +impl fmt::Display for MsSqlConvert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{}CONVERT({}, {}", + if self.is_try { "TRY_" } else { "" }, + self.data_type, + self.expr + )?; + if !self.styles.is_empty() { + write!(f, ", {}", comma(&self.styles))?; + } + f.write_str(")") + } +} + +impl fmt::Display for MsSqlJsonArg<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Value(expr) => expr.fmt(f), + Self::KeyValue(key, value) => write!(f, "{key} : {value}"), + } + } +} + +impl fmt::Display for MsSqlJsonCall<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}({}", self.name, comma(&self.args))?; + if let Some(ref clause) = self.null_clause { + if !self.args.is_empty() { + f.write_str(" ")?; + } + f.write_str(clause)?; + } + f.write_str(")") + } +} + +impl fmt::Display for MsSqlExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Convert(convert) => convert.fmt(f), + Self::JsonCall(call) => call.fmt(f), + // Written without `write!`, since chains of these can be long. + Self::Method(method) => { + method.expr.fmt(f)?; + f.write_str(".")?; + method.name.fmt(f)?; + f.write_str("(")?; + comma(&method.args).fmt(f)?; + f.write_str(")") + } + } + } +} + +impl fmt::Display for MsSqlTop<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.parenthesized { + write!(f, "TOP ({})", self.quantity)?; + } else { + write!(f, "TOP {}", self.quantity)?; + } + if self.percent { + f.write_str(" PERCENT")?; + } + if self.with_ties { + f.write_str(" WITH TIES")?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlTableFactor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Hinted(hinted) => { + write!(f, "{} WITH ({})", hinted.table, comma(&hinted.hints)) + } + Self::OpenJson(openjson) => openjson.fmt(f), + } + } +} + +impl fmt::Display for MsSqlOpenJsonColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {}", self.name, self.data_type)?; + if let Some(path) = &self.path { + write!(f, " '{}'", path.text)?; + } + if self.as_json { + f.write_str(" AS JSON")?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlOpenJson<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "OPENJSON({}", self.expr)?; + if let Some(path) = &self.path { + write!(f, ", {path}")?; + } + f.write_str(")")?; + if !self.columns.is_empty() { + write!(f, " WITH ({})", comma(&self.columns))?; + } + Ok(()) + } +} + +impl fmt::Display for MsSqlForClause<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Browse => f.write_str("FOR BROWSE"), + Self::Xml(xml) => { + write!(f, "FOR XML {}", xml.mode)?; + if let Some(name) = &xml.mode_name { + write!(f, "('{}')", name.text)?; + } + if xml.binary_base64 { + f.write_str(", BINARY BASE64")?; + } + if xml.type_directive { + f.write_str(", TYPE")?; + } + if let Some(root) = &xml.root { + write!(f, ", ROOT('{}')", root.text)?; + } + if xml.elements { + f.write_str(", ELEMENTS")?; + } + Ok(()) + } + Self::Json(json) => { + write!(f, "FOR JSON {}", json.mode)?; + if let Some(root) = &json.root { + write!(f, ", ROOT('{}')", root.text)?; + } + if json.include_null_values { + f.write_str(", INCLUDE_NULL_VALUES")?; + } + if json.without_array_wrapper { + f.write_str(", WITHOUT_ARRAY_WRAPPER")?; + } + Ok(()) + } + } + } +} diff --git a/sqlparser_v2/src/dialect/mysql.rs b/sqlparser_v2/src/dialect/mysql.rs new file mode 100644 index 0000000000..3df1706c5c --- /dev/null +++ b/sqlparser_v2/src/dialect/mysql.rs @@ -0,0 +1,1703 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! MySQL. + +use crate::ast::Span; +use std::borrow::Cow; +use std::fmt::{self, Write as _}; + +use crate::PResult; +use crate::ast::{ + AlterTableOp, BinaryOp, CastStyle, ColumnDef, ColumnOption, ColumnPosition, CreateFlags, + DataType, DataTypeSuffix, Delete, Expr, ExprKind, Generated, GeneratedKind, GeneratedStorage, + GeneratedWhen, GrantName, Grantee, GroupByModifier, Ident, InsertSource, Join, JoinKind, + LikeKind, Limit, Literal, MultiTableDelete, ObjectName, ObjectType, OffsetRows, OrderByItem, + Query, SelectInto, SelectItem, SelectItemKind, SetExpr, SetQuantifier, SetStatement, + SpecialExpr, Statement, StringLiteral, StringPrefix, TableConstraint, TableFactor, TableRef, + TableWithJoins, Update, +}; +use crate::dialect::builtin::{BuiltinInsert, BuiltinSelect, BuiltinTableFactor}; +use crate::dialect::{AstExt, Builtin, Dialect, ExprExtOf}; +use crate::grammar::{self, prec}; +use crate::lexer::{ + LexResult, Lexeme, Token, TokenKind, block_comment, lex_core_comment, line_comment, quoted, + quoted_with_backslash, +}; +use crate::parser::{InfixRule, Parser}; + +mod statements; + +pub use statements::*; + +#[derive(Debug, Clone, PartialEq)] +pub struct MySql; + +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlExpr<'a, X: AstExt> { + /// `left DIV right` + IntDiv { + left: Box>, + right: Box>, + }, + /// `MATCH (columns) AGAINST (value [modifier])` + MatchAgainst { + columns: Vec>, + value: Box>, + modifier: Option, + }, + /// `value MEMBER OF(array)` + MemberOf { + value: Box>, + array: Box>, + }, + /// `CONVERT(expr USING charset)` or `CONVERT(expr, type [CHARACTER SET charset])` + Convert(Box>), + /// A literal with a character set introducer: `_utf8mb4 'text'`. + Introduced(Box>), + /// Adjacent string literals, which MySQL concatenates: `'a' "b"`. + ConcatenatedStrings(Vec>), +} + +/// `CONVERT(expr USING charset)` when `using` is set, otherwise +/// `CONVERT(expr, data_type [CHARACTER SET charset])`. +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlConvert<'a, X: AstExt> { + pub expr: Expr<'a, X>, + pub using: Option>, + pub data_type: Option>, + pub charset: Option>, +} + +/// A character set introducer and the literal it applies to. +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlIntroduced<'a> { + pub charset: Ident<'a>, + pub value: Literal<'a>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SearchModifier { + NaturalLanguage, + NaturalLanguageWithQueryExpansion, + Boolean, + WithQueryExpansion, +} + +/// Backticks quote identifiers, double quotes delimit strings, and `@name` +/// is a variable. +#[inline] +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) + }; + match rest.as_bytes() { + [b'`', ..] => Some(quoted(rest, TokenKind::QuotedIdent)), + [b'"' | b'\'', ..] => Some(quoted_with_backslash(rest, TokenKind::String)), + [b'b' | b'B', b'\'', ..] => Some(bit_string(rest)), + [b'n' | b'N', b'\'', ..] => Some(national_string(rest)), + [b'<', b'=', b'>', ..] | [b'-', b'>', b'>', ..] => op(3), + [b'-', b'>', ..] | [b':', b'=', ..] | [b'&', b'&', ..] => op(2), + [b'@', b'\'' | b'"' | b'`', ..] => op(1), + [b'{' | b'}', ..] => op(1), + [b'@', ..] => user_variable(rest), + _ => word_or_number(rest), + } +} + +/// Lexes `b'101'` as a string token, keeping the prefix. +fn bit_string(rest: &str) -> LexResult { + let string = quoted(&rest[1..], TokenKind::String)?; + Ok(Lexeme { + kind: TokenKind::String, + len: string.len + 1, + }) +} + +/// Lexes `N'text'` as a string token, keeping the prefix. +fn national_string(rest: &str) -> LexResult { + let string = quoted_with_backslash(&rest[1..], TokenKind::String)?; + Ok(Lexeme { + kind: TokenKind::String, + len: string.len + 1, + }) +} + +#[inline] +fn is_word_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || !b.is_ascii() +} + +fn word_run(bytes: &[u8]) -> usize { + bytes.iter().take_while(|&&b| is_word_byte(b)).count() +} + +/// True if a run of word bytes that starts with a digit reads as a number. +fn run_is_number(run: &[u8]) -> bool { + let digits = run.iter().take_while(|b| b.is_ascii_digit()).count(); + if digits == run.len() { + return true; + } + if let [b'0', b'x' | b'X', hex @ ..] = run { + return !hex.is_empty() && hex.iter().all(u8::is_ascii_hexdigit); + } + if let [b'0', b'b' | b'B', bits @ ..] = run { + return !bits.is_empty() && bits.iter().all(|b| matches!(b, b'0' | b'1')); + } + match run[digits] { + b'e' | b'E' => { + let exponent = &run[digits + 1..]; + !exponent.is_empty() && exponent.iter().all(u8::is_ascii_digit) + } + _ => false, + } +} + +/// Lexes names containing `$` or starting with a digit, and `0b101`. Returns +/// `None` for anything the core lexes the same way. +#[inline] +fn word_or_number(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let first = *bytes.first()?; + if !is_word_byte(first) { + return None; + } + let len = word_run(bytes); + let run = &bytes[..len]; + let token = |kind| Some(Ok(Lexeme { kind, len })); + if first.is_ascii_digit() { + return match run { + [b'0', b'b' | b'B', bits @ ..] + if !bits.is_empty() && bits.iter().all(|b| matches!(b, b'0' | b'1')) => + { + token(TokenKind::Number) + } + run if run_is_number(run) || matches!(run, [b'0', b'x' | b'X', ..]) => None, + // `1e+5`: the core reads the sign and exponent. + [.., b'e' | b'E'] + if run[..len - 1].iter().all(u8::is_ascii_digit) + && matches!(bytes.get(len), Some(b'+' | b'-')) + && bytes.get(len + 1).is_some_and(u8::is_ascii_digit) => + { + None + } + _ => token(TokenKind::Word), + }; + } + (first == b'$' && len > 1 || run.contains(&b'$')).then_some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })) +} + +/// Lexes the parts of a qualified name that start with a digit, such as the +/// `.15to29` in `t.15to29`, where the core would read a number. +#[inline] +pub fn lex_after(prev: Option>, rest: &str) -> Option { + let prev = prev?; + let bytes = rest.as_bytes(); + if !bytes[0].is_ascii_digit() && bytes[0] != b'.' { + return None; + } + if prev.is_op(".") && bytes[0].is_ascii_digit() { + let len = word_run(bytes); + return bytes[..len] + .iter() + .any(|b| !b.is_ascii_digit()) + .then_some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })); + } + if matches!(prev.kind, TokenKind::Word | TokenKind::QuotedIdent) + && bytes[0] == b'.' + && bytes.get(1).is_some_and(u8::is_ascii_digit) + { + return Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })); + } + None +} + +/// Lexes `@name` or `@@name` as a word. +#[inline] +fn user_variable(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let sigils = if bytes.get(1) == Some(&b'@') { 2 } else { 1 }; + let name = bytes[sigils..] + .iter() + .take_while(|&&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || !b.is_ascii()) + .count(); + (name > 0).then_some(Ok(Lexeme { + kind: TokenKind::Word, + len: sigils + name, + })) +} + +/// `#` starts a comment, block comments do not nest, and `--` only starts a +/// comment when followed by whitespace or the end of the input. +#[inline] +pub fn lex_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'#', ..] => Some(Ok(line_comment(rest))), + [b'/', b'*', ..] => Some(block_comment(rest, false)), + [b'-', b'-', next, ..] if !next.is_ascii_whitespace() => None, + _ => lex_core_comment(rest), + } +} + +/// Words MySQL does not allow as an alias without `AS`. +#[inline] +pub fn is_reserved_for_alias(word: &str) -> bool { + [ + "USE", + "FORCE", + "IGNORE", + "PARTITION", + "ANALYZE", + "EXPLAIN", + "MATCH", + "REGEXP", + "RLIKE", + ] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved_for_alias(word) +} + +#[inline] +pub fn is_reserved(word: &str) -> bool { + [ + "DIV", + "HIGH_PRIORITY", + "STRAIGHT_JOIN", + "SQL_CALC_FOUND_ROWS", + "SQL_SMALL_RESULT", + "SQL_BIG_RESULT", + ] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved(word) +} + +/// Reads a quoted collation name as written, with its quotes. +fn parse_string_collation<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.advance(); + let quote = char::from(token.text.as_bytes()[0]); + Ok(ObjectName { + parts: vec![Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some(quote), + span: token.span, + }], + }) +} + +/// Parses `expr COLLATE 'name'`, where the name is a string. +fn parse_collate_string<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + let collation = parse_string_collation(p)?; + p.deepen_by(2)?; + Ok(ExprKind::Special(Box::new(SpecialExpr::Collate { + expr: left, + collation, + })) + .into()) +} + +pub fn infix_rule<'a, D>(p: &Parser<'a, D>) -> Option> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + if p.at_keyword("DIV") { + Some(InfixRule::custom(prec::MUL, parse_int_div)) + } else if p.at_op(":=") { + Some(InfixRule::custom(ASSIGNMENT, parse_assignment_expr)) + } else if p.at_op("&&") { + Some(InfixRule::binary(prec::AND, BinaryOp::And)) + } else if p.at_keyword("MEMBER") && p.peek_nth(1).is_word("OF") && p.peek_nth(2).is_op("(") { + Some(InfixRule::custom(prec::COMPARE, parse_member_of)) + } else if p.at_keyword("COLLATE") && p.peek_nth(1).kind == TokenKind::String { + Some(InfixRule::custom(prec::POSTFIX, parse_collate_string)) + } else if p.at_keyword("XOR") { + Some(InfixRule::binary(XOR, BinaryOp::Named("XOR".into()))) + } else if at_regexp(p, 0) || (p.at_keyword("NOT") && at_regexp(p, 1)) { + Some(InfixRule::custom(prec::COMPARE, parse_regexp)) + } else if p.at_op("<<") { + Some(InfixRule::binary(prec::BIT_XOR, BinaryOp::ShiftLeft)) + } else if p.at_op(">>") { + Some(InfixRule::binary(prec::BIT_XOR, BinaryOp::ShiftRight)) + } else if p.at_op("<=>") { + Some(InfixRule::binary( + prec::COMPARE, + BinaryOp::Named("<=>".into()), + )) + } else if p.at_op("->") { + Some(InfixRule::binary(prec::OTHER, BinaryOp::Named("->".into()))) + } else if p.at_op("->>") { + Some(InfixRule::binary( + prec::OTHER, + BinaryOp::Named("->>".into()), + )) + } else { + grammar::infix_rule(p) + } +} + +/// Between `AND` and `OR`. +const XOR: u8 = 15; + +/// Below every other operator. +const ASSIGNMENT: u8 = 5; + +/// `@a := expr`, which associates to the right. +fn parse_assignment_expr<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + bp: u8, +) -> PResult> { + p.advance(); + let right = p.parse_expr_bp(bp - 1)?; + Ok(ExprKind::Binary { + left: Box::new(left), + op: BinaryOp::Named(":=".into()), + right: Box::new(right), + } + .into()) +} + +fn parse_member_of<'a, D>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + p.advance(); + p.advance(); + p.expect_op("(")?; + let array = Box::new(p.parse_expr()?); + p.expect_op(")")?; + let node = MySqlExpr::MemberOf { + value: Box::new(left), + array, + }; + Ok(ExprKind::Ext(node.into()).into()) +} + +pub fn at_regexp<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + let token = p.peek_nth(n); + token.is_word("REGEXP") || token.is_word("RLIKE") +} + +pub fn parse_regexp<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + let negated = p.eat_keyword("NOT"); + let kind = if p.eat_keyword("REGEXP") { + LikeKind::Named("REGEXP".into()) + } else { + p.expect_keyword("RLIKE")?; + LikeKind::Named("RLIKE".into()) + }; + grammar::parse_like_operand(p, left, negated, kind) +} + +/// True if `token` can start an expression, for `BINARY expr`, as opposed to +/// a column named `binary` before a comma, `FROM` and the like. +fn starts_expression<'a, D: Dialect>(p: &Parser<'a, D>, token: Token<'a>) -> bool { + match token.kind { + TokenKind::Word => !D::is_reserved(token.text) && !D::is_reserved_for_alias(token.text), + TokenKind::QuotedIdent + | TokenKind::String + | TokenKind::Number + | TokenKind::HexString + | TokenKind::Placeholder => true, + TokenKind::Op => matches!(token.text, "-" | "+" | "~" | "!"), + _ => { + let _ = p; + false + } + } +} + +/// True at a plain string, as opposed to a prefixed or national one. +fn at_plain_string<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let token = p.peek(); + token.kind == TokenKind::String && !token.text.starts_with(['b', 'B', 'n', 'N']) +} + +/// True if `CONVERT` at the current token is MySQL's rather than a plain call: +/// its parentheses hold a top-level `USING`, or exactly one comma before a name. +fn at_mysql_convert<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let (mut n, mut depth, mut commas, mut after_comma) = (2, 0_usize, 0, None); + loop { + let token = p.peek_nth(n); + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + if depth == 0 { + return commas == 1 && after_comma == Some(TokenKind::Word); + } + depth -= 1; + } + TokenKind::Op if token.text == "," && depth == 0 => { + commas += 1; + after_comma = Some(p.peek_nth(n + 1).kind); + } + TokenKind::Word if depth == 0 && token.is_word("USING") => return true, + _ => {} + } + n += 1; + } +} + +/// Parses the arguments of `CONVERT`, with the current token on `(`. +pub fn parse_convert<'a, D>(p: &mut Parser<'a, D>) -> PResult> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + p.expect_op("(")?; + let expr = p.parse_expr()?; + let mut node = MySqlConvert { + expr, + using: None, + data_type: None, + charset: None, + }; + if p.eat_keyword("USING") { + node.using = Some(grammar::parse_object_name(p)?); + } else { + p.expect_op(",")?; + node.data_type = Some(D::parse_data_type(p)?); + if p.at_keyword("CHARACTER") && p.peek_nth(1).is_word("SET") { + p.advance(); + p.advance(); + node.charset = Some(grammar::parse_object_name(p)?); + } + } + p.expect_op(")")?; + Ok(ExprKind::Ext(MySqlExpr::Convert(Box::new(node)).into()).into()) +} + +/// Parses `MATCH (...) AGAINST (...)`, `CONVERT`, `BINARY expr`, character set +/// introducers and adjacent strings, or else a core prefix expression. +pub fn parse_prefix<'a, D>(p: &mut Parser<'a, D>) -> PResult> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + if grammar::at_odbc_escape(p) { + return grammar::parse_odbc_escape(p); + } + let next = p.peek_nth(1); + if p.at_keyword("CONVERT") && next.is_op("(") && at_mysql_convert(p) { + p.advance(); + return parse_convert(p); + } + if p.at_keyword("BINARY") && starts_expression(p, next) { + let keyword = p.advance(); + let expr = p.parse_expr_bp(prec::UNARY)?; + return Ok(ExprKind::Cast { + expr: Box::new(expr), + ty: Box::new(DataType { + qualifier: Vec::new(), + name: Ident { + text: "BINARY".into(), + quote: None, + span: keyword.span, + }, + angle: None, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: crate::ast::ArrayType::None, + }), + style: CastStyle::Function, + } + .into()); + } + if p.peek().kind == TokenKind::Word + && p.peek().text.starts_with('_') + && matches!(next.kind, TokenKind::String | TokenKind::HexString) + { + let charset = p.parse_ident()?; + let value = match grammar::parse_prefix(p)?.kind { + ExprKind::Literal(value) => value, + _ => return Err(p.expected("a string after a character set")), + }; + let node = MySqlIntroduced { charset, value }; + return Ok(ExprKind::Ext(MySqlExpr::Introduced(Box::new(node)).into()).into()); + } + if !(p.at_keyword("MATCH") && next.kind == TokenKind::Op && next.text == "(") { + let expr = grammar::parse_prefix(p)?; + return match expr.kind { + ExprKind::Literal(Literal::String(first)) + if first.prefix == StringPrefix::None && !first.national && at_plain_string(p) => + { + let mut parts = vec![first]; + while at_plain_string(p) { + let token = p.advance(); + parts.push(D::string_literal(token)); + } + Ok(ExprKind::Ext(MySqlExpr::ConcatenatedStrings(parts).into()).into()) + } + other => Ok(other.into()), + }; + } + p.advance(); + p.expect_op("(")?; + let columns = p.parse_comma_separated(grammar::parse_object_name)?; + p.expect_op(")")?; + p.expect_keyword("AGAINST")?; + p.expect_op("(")?; + let value = Box::new(p.nested(Parser::parse_prefix)?); + let modifier = parse_search_modifier(p)?; + p.expect_op(")")?; + let node = MySqlExpr::MatchAgainst { + columns, + value, + modifier, + }; + Ok(ExprKind::Ext(node.into()).into()) +} + +fn parse_search_modifier<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let expansion = |p: &mut Parser<'a, D>| -> PResult { + if !p.eat_keyword("WITH") { + return Ok(false); + } + p.expect_keyword("QUERY")?; + p.expect_keyword("EXPANSION")?; + Ok(true) + }; + if !p.eat_keyword("IN") { + return Ok(expansion(p)?.then_some(SearchModifier::WithQueryExpansion)); + } + if p.eat_keyword("BOOLEAN") { + p.expect_keyword("MODE")?; + return Ok(Some(SearchModifier::Boolean)); + } + p.expect_keyword("NATURAL")?; + p.expect_keyword("LANGUAGE")?; + p.expect_keyword("MODE")?; + Ok(Some(if expansion(p)? { + SearchModifier::NaturalLanguageWithQueryExpansion + } else { + SearchModifier::NaturalLanguage + })) +} + +pub fn parse_column_position<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("FIRST") { + return Ok(Some(ColumnPosition::First)); + } + if p.eat_keyword("AFTER") { + return p + .parse_ident() + .map(|name| Some(ColumnPosition::After(name))); + } + Ok(None) +} + +/// Parses a column definition whose name can be a reserved word. +fn parse_changed_column<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_name_part()?; + grammar::parse_column_def_after_name(p, name) +} + +fn parse_table_setting<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: &'static str, +) -> PResult> { + p.advance(); + let equals = p.eat_op("="); + let token = p.peek(); + if !matches!(token.kind, TokenKind::Word | TokenKind::Number) { + return Err(p.expected("a value")); + } + p.advance(); + Ok(AlterTableOp::Setting { + name: name.into(), + equals, + value: token.text.into(), + }) +} + +pub fn parse_alter_table_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + for name in ["ALGORITHM", "LOCK", "AUTO_INCREMENT"] { + if p.at_keyword(name) { + return parse_table_setting(p, name); + } + } + if p.at_keyword("RENAME") && next.is_word("AS") { + p.advance(); + p.advance(); + return grammar::parse_object_name(p).map(AlterTableOp::RenameAs); + } + if p.eat_keyword("CHANGE") { + p.eat_keyword("COLUMN"); + let old = p.parse_ident()?; + let column = parse_changed_column(p)?; + let position = parse_column_position(p)?; + return Ok(AlterTableOp::ChangeColumn { + old, + column, + position, + }); + } + if p.eat_keyword("MODIFY") { + p.eat_keyword("COLUMN"); + let column = parse_changed_column(p)?; + let position = parse_column_position(p)?; + return Ok(AlterTableOp::ModifyColumn { column, position }); + } + if p.at_keyword("DROP") && next.is_word("PRIMARY") { + p.advance(); + p.advance(); + p.expect_keyword("KEY")?; + return Ok(AlterTableOp::Phrase("DROP PRIMARY KEY".into())); + } + if p.at_keyword("DROP") && next.is_word("FOREIGN") { + p.advance(); + p.advance(); + p.expect_keyword("KEY")?; + let name = p.parse_ident()?; + return Ok(AlterTableOp::PhraseName { + phrase: "DROP FOREIGN KEY".into(), + name, + }); + } + if p.at_keyword("DROP") && next.is_word("INDEX") { + p.advance(); + p.advance(); + let name = p.parse_ident()?; + return Ok(AlterTableOp::PhraseName { + phrase: "DROP INDEX".into(), + name, + }); + } + let mut operation = grammar::parse_alter_table_op(p)?; + if let AlterTableOp::AddColumn { position, .. } = &mut operation { + *position = parse_column_position(p)?; + } + Ok(operation) +} + +/// `ALL`, `DISTINCT` and the MySQL modifiers can appear in any order. +pub fn parse_select_head<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + let mut select = BuiltinSelect::default(); + let mut quantifier = SetQuantifier::None; + loop { + let unset = quantifier == SetQuantifier::None; + if !unset + && (p.at_keyword("ALL") || p.at_keyword("DISTINCT") || p.at_keyword("DISTINCTROW")) + { + return Err(p.expected("one of ALL and DISTINCT")); + } + if unset && p.eat_keyword("ALL") { + quantifier = SetQuantifier::All; + } else if unset && (p.eat_keyword("DISTINCT") || p.eat_keyword("DISTINCTROW")) { + quantifier = SetQuantifier::Distinct; + } else if p.eat_keyword("HIGH_PRIORITY") { + select.mysql.high_priority = true; + } else if p.eat_keyword("STRAIGHT_JOIN") { + select.mysql.straight_join = true; + } else if p.eat_keyword("SQL_SMALL_RESULT") { + select.mysql.small_result = true; + } else if p.eat_keyword("SQL_BIG_RESULT") { + select.mysql.big_result = true; + } else if p.eat_keyword("SQL_BUFFER_RESULT") { + select.mysql.buffer_result = true; + } else if p.eat_keyword("SQL_NO_CACHE") { + select.mysql.no_cache = true; + } else if p.eat_keyword("SQL_CALC_FOUND_ROWS") { + select.mysql.calc_found_rows = true; + } else { + return Ok((select, quantifier)); + } + } +} + +pub fn parse_int_div<'a, D>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + bp: u8, +) -> PResult> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + p.advance(); + let right = p.parse_expr_bp(bp)?; + let node = MySqlExpr::IntDiv { + left: Box::new(left), + right: Box::new(right), + }; + Ok(ExprKind::Ext(node.into()).into()) +} + +/// Accepts `LIMIT offset, count` as well as the standard form. +pub fn parse_limit<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let first = p.parse_expr()?; + if p.eat_op(",") { + let count = p.parse_expr()?; + Ok(Limit { + count: Some(count), + offset: Some(first), + offset_rows: OffsetRows::None, + offset_comma: true, + all: false, + by: Vec::new(), + }) + } else { + grammar::parse_limit_offset(p, first) + } +} + +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let next = p.peek_nth(1); + let keyword = |keyword: &'static str, expr| ColumnOption::Keyword { + keyword: keyword.into(), + expr, + }; + if p.eat_keyword("AUTO_INCREMENT") { + return Ok(Some(ColumnOption::AutoIncrement)); + } + if p.at_keyword("CHARACTER") && next.is_word("SET") { + p.advance(); + p.advance(); + let name = p.parse_name_part()?; + return Ok(Some(keyword( + "CHARACTER SET", + Some(Expr::new(ExprKind::Ident(name.clone()), name.span)), + ))); + } + if p.at_keyword("COMMENT") && next.kind == TokenKind::String { + p.advance(); + let token = p.advance(); + return Ok(Some(ColumnOption::Comment(D::string_literal(token)))); + } + if p.at_keyword("SRID") { + p.advance(); + return Ok(Some(keyword("SRID", Some(p.parse_expr()?)))); + } + if p.at_keyword("ON") && next.is_word("UPDATE") { + p.advance(); + p.advance(); + return Ok(Some(keyword("ON UPDATE", Some(p.parse_expr()?)))); + } + if p.at_keyword("KEY") { + p.advance(); + return Ok(Some(ColumnOption::PrimaryKey)); + } + if p.at_keyword("COLLATE") && next.kind == TokenKind::String { + p.advance(); + return parse_string_collation(p).map(|name| Some(ColumnOption::Collate(name))); + } + if p.eat_keyword("INVISIBLE") { + return Ok(Some(keyword("INVISIBLE", None))); + } + if p.at_keyword("UNIQUE") && next.is_word("KEY") { + p.advance(); + p.advance(); + return Ok(Some(keyword("UNIQUE KEY", None))); + } + if p.at_keyword("AS") && next.is_op("(") { + p.advance(); + p.advance(); + let expr = p.parse_expr()?; + p.expect_op(")")?; + let storage = if p.eat_keyword("STORED") { + Some(GeneratedStorage::Stored) + } else if p.eat_keyword("VIRTUAL") { + Some(GeneratedStorage::Virtual) + } else { + None + }; + let generated = Generated { + when: Some(GeneratedWhen::Omitted), + kind: GeneratedKind::Expr { expr, storage }, + }; + return Ok(Some(ColumnOption::Generated(Box::new(generated)))); + } + grammar::parse_column_option(p) +} + +/// Parses a data type, with `SIGNED`, `UNSIGNED` and `ZEROFILL` after the +/// arguments, and the integer and string-list types. +pub fn parse_data_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + let next = p.peek_nth(1); + let is_list = (token.is_word("ENUM") || token.is_word("SET")) && next.is_op("("); + if is_list { + let name = plain_name(p.advance()); + p.expect_op("(")?; + let args = p.parse_comma_separated(|p| parse_string_text(p).map(Cow::Borrowed))?; + p.expect_op(")")?; + return Ok(DataType { + qualifier: Vec::new(), + name, + angle: None, + args, + suffix: DataTypeSuffix::SignedArgs([0, 0]), + array: crate::ast::ArrayType::None, + }); + } + if token.is_word("SIGNED") || token.is_word("UNSIGNED") { + let name = plain_name(p.advance()); + let suffix = if p.eat_keyword("INTEGER") { + DataTypeSuffix::Integer + } else { + DataTypeSuffix::None + }; + if p.at_op("(") { + return Err(p.expected("no display width")); + } + return Ok(DataType { + qualifier: Vec::new(), + name, + angle: None, + args: Vec::new(), + suffix, + array: grammar::parse_array_suffix(p)?, + }); + } + if token.is_word("ARRAY") { + return Err(p.expected("a data type")); + } + let mut ty = grammar::parse_data_type(p)?; + if !is_numeric_type(&ty.name.text) { + return Ok(ty); + } + let unsigned = if p.eat_keyword("UNSIGNED") { + true + } else { + p.eat_keyword("SIGNED"); + false + }; + let zerofill = p.eat_keyword("ZEROFILL"); + ty.suffix = match (ty.suffix, unsigned, zerofill) { + (DataTypeSuffix::None, true, false) => DataTypeSuffix::Unsigned, + (DataTypeSuffix::None, false, true) => DataTypeSuffix::Zerofill, + (DataTypeSuffix::None, true, true) => DataTypeSuffix::UnsignedZerofill, + (DataTypeSuffix::Precision, true, false) => DataTypeSuffix::PrecisionUnsigned, + (other, false, false) => other, + _ => return Err(p.expected("a type with one sign suffix")), + }; + Ok(ty) +} + +/// True for the types that can take `SIGNED`, `UNSIGNED` or `ZEROFILL`. +fn is_numeric_type(name: &str) -> bool { + [ + "TINYINT", + "SMALLINT", + "MEDIUMINT", + "INT", + "INTEGER", + "BIGINT", + "DECIMAL", + "DEC", + "NUMERIC", + "FIXED", + "FLOAT", + "DOUBLE", + "REAL", + ] + .iter() + .any(|numeric| numeric.eq_ignore_ascii_case(name)) +} + +fn plain_name<'a>(token: Token<'a>) -> Ident<'a> { + Ident { + text: token.text.into(), + quote: None, + span: token.span, + } +} + +fn parse_string_text<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + if p.peek().kind != TokenKind::String { + return Err(p.expected("a string")); + } + Ok(p.advance().text) +} + +impl Dialect for MySql { + type Ext = Builtin; + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, true) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_variables(p) + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, false, true) + } + + fn parse_create_table_query<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_table_or_query(p) + } + + fn parse_insert_into<'a>(p: &mut Parser<'a, Self>) -> PResult { + Ok(p.eat_keyword("INTO")) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert_statement(p) + } + + fn parse_insert_columns<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_insert_columns(p) + } + + fn parse_insert_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert_source(p) + } + + fn parse_update<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_update(p) + } + + fn parse_delete<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_delete(p) + } + + fn parse_table_constraint<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_table_constraint(p) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn eat_drop_temporary<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("TEMPORARY") + } + + fn parse_grant_name<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_grant_name(p) + } + + fn parse_grantee<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_mysql_grantee(p) + } + + fn parse_function_separator<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_function_separator(p) + } + + fn at_query_values<'a>(p: &Parser<'a, Self>, n: usize) -> bool { + at_row_values(p, n) || grammar::at_query_values(p, n) + } + + fn parse_query_values<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_query_values(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_join(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_group_by_modifier<'a>(p: &mut Parser<'a, Self>) -> Option { + grammar::parse_group_by_with(p, false) + } + + fn parse_index_settings<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_index_settings(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_alter_table_op(p) + } + + fn parse_set<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if grammar::at_set_names(p) { + return grammar::parse_set_names(p); + } + if grammar::at_special_set(p) { + return grammar::parse_set(p); + } + grammar::parse_set_assignments(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + grammar::eat_drop_object_type(p, &["TRIGGER"]) + } + + fn parse_select_head<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + parse_select_head(p) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + string_literal(token) + } + + /// MySQL has no `FILTER` clause. + fn parse_function_filter<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + lex_comment(rest) + } + + fn parse_insert_modifiers<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let priority = ["LOW_PRIORITY", "DELAYED", "HIGH_PRIORITY"] + .into_iter() + .find(|word| p.eat_keyword(word)); + Ok(BuiltinInsert { + ignore: p.eat_keyword("IGNORE"), + priority: priority.map(Cow::Borrowed), + ..Default::default() + }) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_after(prev: Option>, rest: &str) -> Option { + lex_after(prev, rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + is_reserved(word) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + is_reserved_for_alias(word) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_limit<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_limit(p) + } +} + +/// Builds a string literal from its token. `B'101'` keeps its prefix, and a +/// backslash only escapes in the other strings. +#[inline] +pub fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + let text = token.text; + let (prefix, national, body) = match text.as_bytes()[0] { + b'b' | b'B' => (StringPrefix::Byte, false, &text[1..]), + b'n' | b'N' => (StringPrefix::None, true, &text[1..]), + _ => (StringPrefix::None, false, text), + }; + StringLiteral { + text: Cow::Borrowed(&body[1..body.len() - 1]), + quote: char::from(body.as_bytes()[0]), + backslash_escapes: prefix == StringPrefix::None, + national, + prefix, + triple: false, + } +} + +/// Writes adjacent strings as one literal in the quotes of the first, as +/// the original does. +fn write_concatenated(f: &mut fmt::Formatter<'_>, parts: &[StringLiteral<'_>]) -> fmt::Result { + let quote = parts[0].quote; + f.write_char(quote)?; + for part in parts { + for c in part.value().chars() { + if c == quote { + f.write_char(quote)?; + } + if c == '\\' { + f.write_char('\\')?; + } + f.write_char(c)?; + } + } + f.write_char(quote) +} + +impl fmt::Display for MySqlExpr<'_, X> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MySqlExpr::IntDiv { left, right } => { + fmt::Display::fmt(&**left, f)?; + f.write_str(" DIV ")?; + fmt::Display::fmt(&**right, f) + } + MySqlExpr::MemberOf { value, array } => { + fmt::Display::fmt(&**value, f)?; + f.write_str(" MEMBER OF(")?; + fmt::Display::fmt(&**array, f)?; + f.write_str(")") + } + MySqlExpr::Convert(convert) => convert.fmt(f), + MySqlExpr::Introduced(introduced) => { + write!(f, "{} {}", introduced.charset, introduced.value) + } + MySqlExpr::ConcatenatedStrings(parts) => write_concatenated(f, parts), + MySqlExpr::MatchAgainst { + columns, + value, + modifier, + } => { + f.write_str("MATCH (")?; + for (i, column) in columns.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{column}")?; + } + write!(f, ") AGAINST ({value}")?; + f.write_str(match modifier { + Some(SearchModifier::NaturalLanguage) => " IN NATURAL LANGUAGE MODE", + Some(SearchModifier::NaturalLanguageWithQueryExpansion) => { + " IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION" + } + Some(SearchModifier::Boolean) => " IN BOOLEAN MODE", + Some(SearchModifier::WithQueryExpansion) => " WITH QUERY EXPANSION", + None => "", + })?; + f.write_str(")") + } + } + } +} + +/// Parses `ALGORITHM` and `LOCK` after an index definition. +pub fn parse_index_settings<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let mut settings = Vec::new(); + while let Some(name) = ["ALGORITHM", "LOCK"] + .into_iter() + .find(|word| p.at_keyword(word)) + { + p.advance(); + p.eat_op("="); + let token = p.expect_kind(TokenKind::Word, "a value")?; + settings.push((name, token.text)); + } + Ok(settings) +} + +impl fmt::Display for MySqlConvert<'_, X> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "CONVERT({}", self.expr)?; + if let Some(using) = &self.using { + write!(f, " USING {using}")?; + } + if let Some(data_type) = &self.data_type { + write!(f, ", {data_type}")?; + } + if let Some(charset) = &self.charset { + write!(f, " CHARACTER SET {charset}")?; + } + f.write_str(")") + } +} + +/// Reads a string as a name, for places that take either. +fn string_ident<'a>(token: Token<'a>) -> Ident<'a> { + Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: token.text.chars().next(), + span: token.span, + } +} + +/// Parses `SEPARATOR 'text'` if it is here. +pub fn parse_function_separator<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.eat_keyword("SEPARATOR") { + return Ok(None); + } + if p.peek().kind != TokenKind::String { + return Err(p.expected("a string after SEPARATOR")); + } + let token = p.advance(); + Ok(Some(D::string_literal(token))) +} + +/// Parses a select item's alias, which can be a string. +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, D::Ext>, +) -> PResult> { + let with_as = p.at_keyword("AS") && p.peek_nth(1).kind == TokenKind::String; + if with_as { + p.advance(); + } + if with_as || p.peek().kind == TokenKind::String { + let token = p.advance(); + return Ok(SelectItemKind::Expr { + expr, + alias: Some(string_ident(token)), + } + .into()); + } + grammar::parse_select_item_alias(p, expr) +} + +/// True if the token `n` ahead starts `VALUES ROW(...)`, which is only a query +/// when `(` follows `ROW`. +pub fn at_row_values<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + p.peek_nth(n).is_word("VALUES") + && p.peek_nth(n + 1).is_word("ROW") + && p.peek_nth(n + 2).is_op("(") +} + +/// Parses `(a, b)`, or `()` in `INSERT`. +fn parse_row<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + p.expect_op("(")?; + let row = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op(")")?; + Ok(row) +} + +/// Parses a list of rows that each start with `ROW`. +fn parse_row_list<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>>> { + p.parse_comma_separated(|p| { + p.expect_keyword("ROW")?; + parse_row(p) + }) +} + +/// Parses the rows of a `VALUES` query, where `ROW` is optional. +pub fn parse_query_values<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_keyword("ROW") { + return parse_row_list(p).map(SetExpr::RowValues); + } + grammar::parse_query_values(p) +} + +/// Parses the column list of an `INSERT`, which can be empty. +pub fn parse_insert_columns<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.at_op("(") && p.peek_nth(1).is_op(")") { + p.advance(); + p.advance(); + return Ok(Vec::new()); + } + grammar::parse_insert_columns(p) +} + +/// Parses what follows the table of an `INSERT`: rows, which can be empty and +/// can use `VALUE` or `ROW`, `SET` assignments, or a query. +pub fn parse_insert_source<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("SET") { + p.advance(); + return p + .parse_comma_separated(D::parse_assignment) + .map(InsertSource::Set); + } + let value_keyword = + p.at_keyword("VALUES") || (p.at_keyword("VALUE") && p.peek_nth(1).is_op("(")); + if !value_keyword { + return grammar::parse_insert_source(p); + } + p.advance(); + if p.at_keyword("ROW") { + return parse_row_list(p).map(InsertSource::RowValues); + } + p.parse_comma_separated(parse_row).map(InsertSource::Values) +} + +pub fn parse_update<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("UPDATE")?; + let table = p.parse_table_ref()?; + let mut joins = Vec::new(); + while let Some(join) = D::parse_join(p)? { + joins.push(join); + } + p.expect_keyword("SET")?; + let assignments = p.parse_comma_separated(D::parse_assignment)?; + let output = D::parse_output_clause(p)?; + let selection = grammar::parse_optional_where(p)?; + let order_by = parse_order_by(p)?; + let limit = parse_trailing_limit(p)?; + let returning = D::parse_returning(p)?; + Ok(Update { + table, + joins, + assignments, + from: Vec::new(), + from_before_set: false, + output, + selection, + order_by, + limit, + returning, + }) +} + +pub fn parse_delete<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("DELETE")?; + if !p.at_keyword("FROM") { + let targets = p.parse_comma_separated(grammar::parse_object_name)?; + p.expect_keyword("FROM")?; + let using = D::parse_from_list(p)?; + return finish_multi_table_delete(p, targets, using, true); + } + p.advance(); + let table = p.parse_table_ref()?; + if p.at_op(",") { + let TableFactor::Named(first) = table.factor else { + return Err(p.expected("a table name")); + }; + let mut targets = vec![first]; + while p.eat_op(",") { + targets.push(grammar::parse_object_name(p)?); + } + p.expect_keyword("USING")?; + let using = D::parse_from_list(p)?; + return finish_multi_table_delete(p, targets, using, false); + } + let using = grammar::parse_optional_delete_using(p)?; + let output = D::parse_output_clause(p)?; + let selection = grammar::parse_optional_where(p)?; + let order_by = parse_order_by(p)?; + let limit = parse_trailing_limit(p)?; + let returning = D::parse_returning(p)?; + Ok(Delete { + table, + multi: None, + using, + output, + selection, + order_by, + limit, + returning, + }) +} + +/// Finishes `DELETE a, b FROM ...` or `DELETE FROM a, b USING ...`. +fn finish_multi_table_delete<'a, D: Dialect>( + p: &mut Parser<'a, D>, + targets: Vec>, + using: Vec>, + from_keyword: bool, +) -> PResult> { + let selection = grammar::parse_optional_where(p)?; + let table = TableRef { + factor: TableFactor::Named(targets[0].clone()), + alias: None, + span: Span::default(), + }; + Ok(Delete { + table, + multi: Some(Box::new(MultiTableDelete { + targets, + from_keyword, + })), + using, + output: None, + selection, + order_by: Vec::new(), + limit: None, + returning: Vec::new(), + }) +} + +fn parse_order_by<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + return p.parse_comma_separated(D::parse_order_by_item); + } + Ok(Vec::new()) +} + +fn parse_trailing_limit<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if p.eat_keyword("LIMIT") { + return Ok(Some(Box::new(D::parse_limit(p)?))); + } + Ok(None) +} + +/// Parses a name in `GRANT ... ON`, which can be `*`, `*.*` or `db.*`. +pub fn parse_grant_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let star = |span| Ident { + text: "*".into(), + quote: None, + span, + }; + let mut parts = Vec::with_capacity(2); + if p.at_op("*") { + parts.push(star(p.advance().span)); + } else if p.peek_nth(1).is_op(".") && p.peek_nth(2).is_op("*") { + parts.push(p.parse_ident()?); + } else { + return grammar::parse_grant_name(p); + } + if p.eat_op(".") { + p.expect_op("*")?; + parts.push(star(p.peek().span)); + } + Ok(GrantName { + name: ObjectName { parts }, + args: None, + }) +} + +/// True if the name just read is followed by `@host`, which the lexer may +/// have read as a variable. +fn at_host<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + let token = p.peek_nth(n); + token.is_op("@") || (token.kind == TokenKind::Word && token.text.starts_with('@')) +} + +/// Parses a grantee: a role or other named kind as in the core, or a user +/// written as a string or `name@host`. +fn parse_mysql_grantee<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.peek().kind == TokenKind::String || at_host(p, 1) { + parse_user_host(p) + } else { + grammar::parse_grantee(p) + } +} + +/// Parses a user as `name`, `'name'` or `name@host`. +pub fn parse_user_host<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + let name = if token.kind == TokenKind::String { + p.advance(); + ObjectName { + parts: vec![string_ident(token)], + } + } else { + grammar::parse_object_name(p)? + }; + let mut grantee = Grantee { + kind: Vec::new(), + name, + host: None, + }; + if p.eat_op("@") { + let host = p.peek(); + grantee.host = Some(match host.kind { + TokenKind::String | TokenKind::QuotedIdent => string_ident(p.advance()), + TokenKind::Word => plain_name(p.advance()), + _ => return Err(p.expected("a host name")), + }); + } else if p.peek().kind == TokenKind::Word && p.peek().text.starts_with('@') { + // `user@host` lexes `@host` as a variable. + let token = p.advance(); + grantee.host = Some(Ident { + text: Cow::Borrowed(&token.text[1..]), + quote: None, + span: token.span, + }); + } + Ok(grantee) +} + +/// Parses `name PARTITION (a, b)`, `JSON_TABLE(...)` or a core table factor. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("JSON_TABLE") && p.peek_nth(1).is_op("(") { + p.advance(); + return parse_json_table(p).map(mysql_factor); + } + let factor = grammar::parse_table_factor(p)?; + let TableFactor::Named(name) = factor else { + return Ok(factor); + }; + if !p.eat_keyword("PARTITION") { + return Ok(TableFactor::Named(name)); + } + let partitions = grammar::parse_ident_list(p)?; + Ok(mysql_factor(MySqlTableFactor::Partitioned { + name, + partitions, + })) +} + +fn mysql_factor(factor: MySqlTableFactor<'_>) -> TableFactor<'_, Builtin> { + TableFactor::Ext(BuiltinTableFactor::MySql(Box::new(factor))) +} + +/// Parses a table and its alias, then any index hints. +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let table = grammar::parse_table_ref(p)?; + let mut hints = Vec::new(); + while let Some(hint) = parse_index_hint(p)? { + hints.push(hint); + } + if hints.is_empty() { + return Ok(table); + } + Ok(TableRef { + factor: mysql_factor(MySqlTableFactor::Hinted { table, hints }), + alias: None, + span: Span::default(), + }) +} + +/// Parses `USE`, `IGNORE` or `FORCE` `INDEX` or `KEY`, if a hint is here. +fn parse_index_hint<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let Some(verb) = ["USE", "IGNORE", "FORCE"] + .into_iter() + .find(|word| p.at_keyword(word)) + else { + return Ok(None); + }; + let next = p.peek_nth(1); + if !(next.is_word("INDEX") || next.is_word("KEY")) { + return Ok(None); + } + p.advance(); + let key = p.advance().is_word("KEY"); + let target = if p.eat_keyword("FOR") { + if p.eat_keyword("JOIN") { + Some("JOIN") + } else if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + Some("ORDER BY") + } else { + p.expect_keyword("GROUP")?; + p.expect_keyword("BY")?; + Some("GROUP BY") + } + } else { + None + }; + p.expect_op("(")?; + let names = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_ident)? + }; + p.expect_op(")")?; + Ok(Some(MySqlIndexHint { + verb: verb.into(), + key, + target: target.map(Cow::Borrowed), + names, + })) +} + +/// Parses a join, adding `STRAIGHT_JOIN` and a condition on `CROSS JOIN`. +pub fn parse_join<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.eat_keyword("STRAIGHT_JOIN") { + let table = p.parse_table_ref()?; + let constraint = grammar::parse_join_constraint(p)?; + return Ok(Some(Join { + kind: JoinKind::Custom("STRAIGHT_JOIN".into()), + spelled_out: false, + table, + constraint, + })); + } + let Some(mut join) = grammar::parse_join(p)? else { + return Ok(None); + }; + if join.kind == JoinKind::Cross { + join.constraint = grammar::parse_join_constraint(p)?; + } + Ok(Some(join)) +} diff --git a/sqlparser_v2/src/dialect/mysql/statements.rs b/sqlparser_v2/src/dialect/mysql/statements.rs new file mode 100644 index 0000000000..0631176913 --- /dev/null +++ b/sqlparser_v2/src/dialect/mysql/statements.rs @@ -0,0 +1,1491 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! MySQL statements and table factors the core does not have. + +use std::borrow::Cow; +use std::fmt; + +use super::{parse_user_host, string_ident}; +use crate::PResult; +use crate::ast::{ + Assignment, CreateTable, CreateView, Expr, ExprKind, Grantee, Ident, IndexColumn, Insert, + KeyOption, Literal, ObjectName, Statement, StatementKind, StringLiteral, TableConstraint, + TableConstraintKind, TableRef, +}; +use crate::dialect::builtin::BuiltinStatement; +use crate::dialect::{Builtin, Dialect}; +use crate::display::{ + CommaLines, Indent, NewLine, SpaceOrNewline, comma, write_columns, write_create_flags, + write_if_not_exists, write_insert_body, +}; +use crate::grammar; +use crate::lexer::TokenKind; +use crate::parser::Parser; + +fn mysql<'a>(statement: MySqlStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::MySql(statement)).into() +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlStatement<'a> { + /// `RENAME TABLE a TO b, c TO d` + RenameTable(Vec<(ObjectName<'a>, ObjectName<'a>)>), + /// `LOCK TABLES t [[AS] alias] lock_type, ...` + LockTables(Vec>), + UnlockTables, + Flush(Box>), + /// `KILL [CONNECTION | QUERY] id` + Kill { + modifier: Option>, + id: Cow<'a, str>, + }, + Insert(Box>), + CreateTable(Box>), + CreateDatabase(Box>), + CreateView(Box>), + CreateTrigger(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlLockedTable<'a> { + pub table: ObjectName<'a>, + pub alias: Option>, + pub lock: MySqlLock, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MySqlLock { + Read { local: bool }, + Write { low_priority: bool }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlFlush<'a> { + /// `NO_WRITE_TO_BINLOG` or `LOCAL`. + pub location: Option>, + /// What is flushed, such as `RELAY LOGS` or `TABLES`. + pub object: Cow<'a, str>, + /// The channel in `RELAY LOGS FOR CHANNEL name`. + pub channel: Option>, + pub tables: Vec>, + pub read_lock: bool, + pub export: bool, +} + +/// `INSERT` or `REPLACE`, with what MySQL adds after its source. +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlInsert<'a> { + pub replace: bool, + pub insert: Box>, + /// `AS name [(columns)]` + pub alias: Option<(Ident<'a>, Vec>)>, + /// The assignments in `ON DUPLICATE KEY UPDATE`. + pub on_duplicate: Vec>, +} + +/// Table options such as `ENGINE = InnoDB`, which come before any `AS`. +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlCreateTable<'a> { + pub table: Box>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlTableOption<'a> { + /// A keyword or words and a value, always rendered with `=`. + KeyValue { + name: Cow<'a, str>, + value: Expr<'a, Builtin>, + }, + /// `COMMENT [=] 'text'` + Comment { + equals: bool, + text: StringLiteral<'a>, + }, + /// `ENGINE [=] name` + Engine(Ident<'a>), + /// `LIKE source` + Like(ObjectName<'a>), + /// `TABLESPACE name [STORAGE {DISK | MEMORY}]` + Tablespace { + name: Ident<'a>, + storage: Option>, + }, + /// `UNION [=] (a, b)` + Union(Vec>), + StartTransaction, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlCreateDatabase<'a> { + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub charset: Option>, + pub collation: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlCreateView<'a> { + /// `UNDEFINED`, `MERGE` or `TEMPTABLE`. + pub algorithm: Option>, + pub definer: Option>, + /// `DEFINER` or `INVOKER`. + pub security: Option>, + pub view: Box>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlCreateTrigger<'a> { + pub definer: Option>, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + /// `BEFORE` or `AFTER`. + pub period: Cow<'a, str>, + /// `INSERT`, `UPDATE` or `DELETE`. + pub event: Cow<'a, str>, + pub table: ObjectName<'a>, + /// `FOLLOWS` or `PRECEDES` and the other trigger. + pub order: Option<(Cow<'a, str>, ObjectName<'a>)>, + pub body: MySqlTriggerBody<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlTriggerBody<'a> { + Statement(Box>), + /// `BEGIN statement; ... END` + Block(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlTableFactor<'a> { + /// `name PARTITION (a, b)` + Partitioned { + name: ObjectName<'a>, + partitions: Vec>, + }, + /// A table followed by index hints. + Hinted { + table: TableRef<'a, Builtin>, + hints: Vec>, + }, + JsonTable(MySqlJsonTable<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlIndexHint<'a> { + /// `USE`, `IGNORE` or `FORCE`. + pub verb: Cow<'a, str>, + /// True if written `KEY` rather than `INDEX`. + pub key: bool, + /// `JOIN`, `ORDER BY` or `GROUP BY`. + pub target: Option>, + pub names: Vec>, +} + +/// `JSON_TABLE(json, path COLUMNS(...))` +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlJsonTable<'a> { + pub json: Expr<'a, Builtin>, + pub path: StringLiteral<'a>, + pub columns: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlJsonColumn<'a> { + /// `name FOR ORDINALITY` + Ordinality(Ident<'a>), + /// `NESTED [PATH] path COLUMNS (...)` + Nested { + path: StringLiteral<'a>, + columns: Vec>, + }, + /// `name type [EXISTS] PATH path [on_empty] [on_error]` + Named(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MySqlJsonNamedColumn<'a> { + pub name: Ident<'a>, + pub data_type: crate::ast::DataType<'a>, + pub exists: bool, + pub path: StringLiteral<'a>, + pub on_empty: Option>, + pub on_error: Option>, +} + +/// What a `JSON_TABLE` column does when its path finds nothing or fails. +#[derive(Debug, Clone, PartialEq)] +pub enum MySqlJsonFallback<'a> { + Null, + Error, + /// `DEFAULT 'value'` + Default(StringLiteral<'a>), +} + +/// Parses `RENAME TABLE a TO b, c TO d`. +fn parse_rename_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("RENAME")?; + p.expect_keyword("TABLE")?; + let renames = p.parse_comma_separated(|p| { + let from = grammar::parse_object_name(p)?; + p.expect_keyword("TO")?; + let to = grammar::parse_object_name(p)?; + Ok((from, to)) + })?; + Ok(MySqlStatement::RenameTable(renames)) +} + +/// Parses a statement, including those only MySQL has. +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if grammar::at_alter_view(p) { + return grammar::parse_alter_view(p, true) + .map(|a| StatementKind::AlterView(Box::new(a)).into()); + } + let next = p.peek_nth(1); + if p.at_keyword("ANALYZE") && next.is_word("TABLE") { + return grammar::parse_analyze(p); + } + if p.at_keyword("RENAME") && next.is_word("TABLE") { + return parse_rename_table(p).map(mysql); + } + if p.at_keyword("LOCK") && next.is_word("TABLES") { + p.advance(); + p.advance(); + let tables = p.parse_comma_separated(parse_locked_table)?; + return Ok(mysql(MySqlStatement::LockTables(tables))); + } + if p.at_keyword("UNLOCK") && next.is_word("TABLES") { + p.advance(); + p.advance(); + return Ok(mysql(MySqlStatement::UnlockTables)); + } + if p.at_keyword("FLUSH") { + p.advance(); + return parse_flush(p).map(|flush| mysql(MySqlStatement::Flush(Box::new(flush)))); + } + if p.at_keyword("KILL") + && (next.kind == TokenKind::Number || next.is_word("CONNECTION") || next.is_word("QUERY")) + { + p.advance(); + return parse_kill(p); + } + if p.at_keyword("REPLACE") { + return parse_replace(p); + } + grammar::parse_statement(p) +} + +fn parse_locked_table<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let table = grammar::parse_object_name(p)?; + let bare_alias = p.at_ident() + && !p.at_keyword("READ") + && !p.at_keyword("WRITE") + && !p.at_keyword("LOW_PRIORITY"); + let alias = if p.eat_keyword("AS") || bare_alias { + Some(p.parse_ident()?) + } else { + None + }; + let lock = if p.eat_keyword("READ") { + MySqlLock::Read { + local: p.eat_keyword("LOCAL"), + } + } else { + let low_priority = p.eat_keyword("LOW_PRIORITY"); + p.expect_keyword("WRITE")?; + MySqlLock::Write { low_priority } + }; + Ok(MySqlLockedTable { table, alias, lock }) +} + +const FLUSH_LOG_KINDS: [(&str, &str); 6] = [ + ("BINARY", "BINARY LOGS"), + ("ENGINE", "ENGINE LOGS"), + ("ERROR", "ERROR LOGS"), + ("GENERAL", "GENERAL LOGS"), + ("SLOW", "SLOW LOGS"), + ("RELAY", "RELAY LOGS"), +]; + +const FLUSH_WORDS: [&str; 6] = [ + "HOSTS", + "PRIVILEGES", + "OPTIMIZER_COSTS", + "STATUS", + "USER_RESOURCES", + "LOGS", +]; + +fn parse_flush<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let location = if p.eat_keyword("NO_WRITE_TO_BINLOG") { + Some("NO_WRITE_TO_BINLOG") + } else if p.eat_keyword("LOCAL") { + Some("LOCAL") + } else { + None + }; + let mut flush = MySqlFlush { + location: location.map(Cow::Borrowed), + object: "".into(), + channel: None, + tables: Vec::new(), + read_lock: false, + export: false, + }; + if p.eat_keyword("TABLES") { + flush.object = "TABLES".into(); + if p.at_ident() && !p.at_keyword("WITH") && !p.at_keyword("FOR") { + flush.tables = p.parse_comma_separated(grammar::parse_object_name)?; + } + if p.eat_keyword("WITH") { + p.expect_keyword("READ")?; + p.expect_keyword("LOCK")?; + flush.read_lock = true; + } else if p.eat_keyword("FOR") { + p.expect_keyword("EXPORT")?; + flush.export = true; + } + return Ok(flush); + } + if let Some(&(first, object)) = FLUSH_LOG_KINDS.iter().find(|(word, _)| p.at_keyword(word)) { + p.advance(); + p.expect_keyword("LOGS")?; + flush.object = object.into(); + if first == "RELAY" && p.eat_keyword("FOR") { + p.expect_keyword("CHANNEL")?; + flush.channel = Some(grammar::parse_object_name(p)?); + } + return Ok(flush); + } + let Some(word) = FLUSH_WORDS.iter().find(|word| p.at_keyword(word)) else { + return Err(p.expected("something to flush")); + }; + p.advance(); + flush.object = (*word).into(); + Ok(flush) +} + +fn parse_kill<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let modifier = if p.eat_keyword("CONNECTION") { + Some("CONNECTION") + } else if p.eat_keyword("QUERY") { + Some("QUERY") + } else { + None + }; + let id = grammar::parse_number_text(p)?; + Ok(mysql(MySqlStatement::Kill { + modifier: modifier.map(Cow::Borrowed), + id: id.into(), + })) +} + +fn parse_replace<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("REPLACE")?; + let insert = grammar::parse_insert_after_verb(p)?; + finish_insert(p, insert, true) +} + +/// Parses `INSERT`, with what MySQL adds after its source. +pub fn parse_insert_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let insert = D::parse_insert(p)?; + finish_insert(p, insert, false) +} + +fn finish_insert<'a, D: Dialect>( + p: &mut Parser<'a, D>, + insert: Insert<'a, Builtin>, + replace: bool, +) -> PResult> { + let alias = if p.eat_keyword("AS") { + let name = p.parse_ident()?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + Some((name, columns)) + } else { + None + }; + let on_duplicate = if p.at_keyword("ON") && p.peek_nth(1).is_word("DUPLICATE") { + p.advance(); + p.advance(); + p.expect_keyword("KEY")?; + p.expect_keyword("UPDATE")?; + p.parse_comma_separated(D::parse_assignment)? + } else { + Vec::new() + }; + if !replace && alias.is_none() && on_duplicate.is_empty() { + return Ok(StatementKind::Insert(Box::new(insert)).into()); + } + Ok(mysql(MySqlStatement::Insert(Box::new(MySqlInsert { + replace, + insert: Box::new(insert), + alias, + on_duplicate, + })))) +} + +/// Parses a `CREATE` statement, taking those only MySQL has before the core. +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + let or_replace = n == 3; + let temporary = p.peek_nth(n).is_word("TEMPORARY"); + if temporary { + n += 1; + } + let target = p.peek_nth(n); + let plain = !or_replace && !temporary; + let at_definer = target.is_word("ALGORITHM") + || target.is_word("DEFINER") + || (target.is_word("SQL") && p.peek_nth(n + 1).is_word("SECURITY")); + if !(target.is_word("TABLE") + || (plain && (target.is_word("DATABASE") || target.is_word("TRIGGER"))) + || (!temporary && at_definer)) + { + return grammar::parse_create(p); + } + let flags = crate::ast::CreateFlags { + or_replace, + temporary, + }; + (0..n).for_each(|_| { + p.advance(); + }); + if p.eat_keyword("TABLE") { + return parse_create_table(p, flags); + } + if p.eat_keyword("DATABASE") { + return parse_create_database(p); + } + let (algorithm, definer, security) = parse_view_params(p)?; + if p.eat_keyword("TRIGGER") { + if algorithm.is_some() || security.is_some() { + return Err(p.expected("VIEW")); + } + return parse_create_trigger(p, definer); + } + let view = Box::new(D::parse_create_view(p, flags)?); + Ok(mysql(MySqlStatement::CreateView(Box::new( + MySqlCreateView { + algorithm: algorithm.map(Cow::Borrowed), + definer, + security: security.map(Cow::Borrowed), + view, + }, + )))) +} + +type ViewParams<'a> = ( + Option<&'static str>, + Option>, + Option<&'static str>, +); + +fn parse_view_params<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let algorithm = if p.eat_keyword("ALGORITHM") { + p.expect_op("=")?; + let value = ["UNDEFINED", "MERGE", "TEMPTABLE"] + .into_iter() + .find(|word| p.eat_keyword(word)); + Some(value.ok_or_else(|| p.expected("UNDEFINED, MERGE or TEMPTABLE"))?) + } else { + None + }; + let definer = if p.eat_keyword("DEFINER") { + p.expect_op("=")?; + Some(parse_user_host(p)?) + } else { + None + }; + let security = if p.at_keyword("SQL") && p.peek_nth(1).is_word("SECURITY") { + p.advance(); + p.advance(); + let value = ["DEFINER", "INVOKER"] + .into_iter() + .find(|word| p.eat_keyword(word)); + Some(value.ok_or_else(|| p.expected("DEFINER or INVOKER"))?) + } else { + None + }; + Ok((algorithm, definer, security)) +} + +fn parse_create_trigger<'a, D: Dialect>( + p: &mut Parser<'a, D>, + definer: Option>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let period = if p.eat_keyword("BEFORE") { + "BEFORE" + } else { + p.expect_keyword("AFTER")?; + "AFTER" + }; + let event = ["INSERT", "UPDATE", "DELETE"] + .into_iter() + .find(|word| p.eat_keyword(word)) + .ok_or_else(|| p.expected("INSERT, UPDATE or DELETE"))?; + p.expect_keyword("ON")?; + let table = grammar::parse_object_name(p)?; + p.expect_keyword("FOR")?; + p.expect_keyword("EACH")?; + p.expect_keyword("ROW")?; + let order = if p.eat_keyword("FOLLOWS") { + Some(("FOLLOWS", grammar::parse_object_name(p)?)) + } else if p.eat_keyword("PRECEDES") { + Some(("PRECEDES", grammar::parse_object_name(p)?)) + } else { + None + }; + let body = if p.eat_keyword("BEGIN") { + let mut statements = Vec::new(); + while !p.at_keyword("END") { + statements.push(p.nested(Parser::parse_statement)?); + p.expect_op(";")?; + } + p.advance(); + MySqlTriggerBody::Block(statements) + } else { + let statement = p.nested(Parser::parse_statement)?; + MySqlTriggerBody::Statement(Box::new(statement)) + }; + Ok(mysql(MySqlStatement::CreateTrigger(Box::new( + MySqlCreateTrigger { + definer, + if_not_exists, + name, + period: period.into(), + event: event.into(), + table, + order: order.map(|(kind, name)| (kind.into(), name)), + body, + }, + )))) +} + +fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: crate::ast::CreateFlags, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let like = if columns.is_empty() && p.eat_keyword("LIKE") { + Some(MySqlTableOption::Like(grammar::parse_object_name(p)?)) + } else { + None + }; + let mut options = parse_table_options(p)?; + options.extend(like); + let query = if p.eat_keyword("AS") || grammar::query_starts_at(p, 0) { + Some(Box::new(D::parse_create_table_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() && options.is_empty() { + return Err(p.expected("column definitions or AS")); + } + let table = Box::new(CreateTable { + or_replace: flags.or_replace, + temporary: flags.temporary, + name, + if_not_exists, + columns, + constraints, + query, + }); + if options.is_empty() { + return Ok(StatementKind::CreateTable(table).into()); + } + Ok(mysql(MySqlStatement::CreateTable(Box::new( + MySqlCreateTable { table, options }, + )))) +} + +/// Option keywords that take a single value. +const TABLE_OPTION_KEYS: [(&[&str], &str); 28] = [ + (&["DEFAULT", "CHARSET"], "DEFAULT CHARSET"), + (&["DEFAULT", "CHARACTER", "SET"], "DEFAULT CHARACTER SET"), + (&["DEFAULT", "COLLATE"], "DEFAULT COLLATE"), + (&["CHARACTER", "SET"], "CHARACTER SET"), + (&["CHARSET"], "CHARSET"), + (&["COLLATE"], "COLLATE"), + (&["DATA", "DIRECTORY"], "DATA DIRECTORY"), + (&["INDEX", "DIRECTORY"], "INDEX DIRECTORY"), + (&["KEY_BLOCK_SIZE"], "KEY_BLOCK_SIZE"), + (&["ROW_FORMAT"], "ROW_FORMAT"), + (&["PACK_KEYS"], "PACK_KEYS"), + (&["STATS_AUTO_RECALC"], "STATS_AUTO_RECALC"), + (&["STATS_PERSISTENT"], "STATS_PERSISTENT"), + (&["STATS_SAMPLE_PAGES"], "STATS_SAMPLE_PAGES"), + (&["DELAY_KEY_WRITE"], "DELAY_KEY_WRITE"), + (&["COMPRESSION"], "COMPRESSION"), + (&["ENCRYPTION"], "ENCRYPTION"), + (&["MAX_ROWS"], "MAX_ROWS"), + (&["MIN_ROWS"], "MIN_ROWS"), + (&["AUTOEXTEND_SIZE"], "AUTOEXTEND_SIZE"), + (&["AVG_ROW_LENGTH"], "AVG_ROW_LENGTH"), + (&["CHECKSUM"], "CHECKSUM"), + (&["CONNECTION"], "CONNECTION"), + (&["ENGINE_ATTRIBUTE"], "ENGINE_ATTRIBUTE"), + (&["PASSWORD"], "PASSWORD"), + ( + &["SECONDARY_ENGINE_ATTRIBUTE"], + "SECONDARY_ENGINE_ATTRIBUTE", + ), + (&["INSERT_METHOD"], "INSERT_METHOD"), + (&["AUTO_INCREMENT"], "AUTO_INCREMENT"), +]; + +fn parse_table_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut options = Vec::new(); + while let Some(option) = parse_table_option(p)? { + options.push(option); + p.eat_op(","); + } + Ok(options) +} + +fn parse_table_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let next = p.peek_nth(1); + if p.at_keyword("START") && next.is_word("TRANSACTION") { + p.advance(); + p.advance(); + return Ok(Some(MySqlTableOption::StartTransaction)); + } + if p.at_keyword("COMMENT") { + p.advance(); + let equals = p.eat_op("="); + let token = p.expect_kind(TokenKind::String, "a string")?; + return Ok(Some(MySqlTableOption::Comment { + equals, + text: D::string_literal(token), + })); + } + if p.at_keyword("ENGINE") { + p.advance(); + p.eat_op("="); + return Ok(Some(MySqlTableOption::Engine(p.parse_name_part()?))); + } + if p.at_keyword("TABLESPACE") { + p.advance(); + p.eat_op("="); + let name = p.parse_name_part()?; + let storage = if p.eat_keyword("STORAGE") { + p.eat_op("="); + if p.eat_keyword("DISK") { + Some("DISK") + } else { + p.expect_keyword("MEMORY")?; + Some("MEMORY") + } + } else { + None + }; + return Ok(Some(MySqlTableOption::Tablespace { + name, + storage: storage.map(Cow::Borrowed), + })); + } + if p.at_keyword("UNION") && (next.is_op("=") || next.is_op("(")) { + p.advance(); + p.eat_op("="); + return Ok(Some(MySqlTableOption::Union(grammar::parse_ident_list(p)?))); + } + for (words, name) in TABLE_OPTION_KEYS { + if words + .iter() + .enumerate() + .all(|(i, word)| p.peek_nth(i).is_word(word)) + { + for _ in words { + p.advance(); + } + p.eat_op("="); + let value = p.spanned_expr(parse_option_value)?; + return Ok(Some(MySqlTableOption::KeyValue { + name: name.into(), + value, + })); + } + } + Ok(None) +} + +/// Parses an option's value: a number, a string or a name. +fn parse_option_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::Number => { + p.advance(); + Ok(ExprKind::Literal(Literal::Number(token.text.into())).into()) + } + TokenKind::String => { + p.advance(); + Ok(ExprKind::Literal(Literal::String(D::string_literal(token))).into()) + } + TokenKind::Word | TokenKind::QuotedIdent => p + .parse_name_part() + .map(|ident| ExprKind::Ident(ident).into()), + _ => Err(p.expected("an option value")), + } +} + +fn parse_create_database<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let (mut charset, mut collation) = (None, None); + loop { + let start = p.peek(); + let _ = p.eat_keyword("DEFAULT"); + let at_charset = + p.at_keyword("CHARSET") || (p.at_keyword("CHARACTER") && p.peek_nth(1).is_word("SET")); + let target = if at_charset && charset.is_none() { + if !p.eat_keyword("CHARSET") { + p.advance(); + p.advance(); + } + &mut charset + } else if p.at_keyword("COLLATE") && collation.is_none() { + p.advance(); + &mut collation + } else if p.peek().span == start.span { + break; + } else { + return Err(p.expected("CHARACTER SET or COLLATE")); + }; + p.eat_op("="); + let token = p.peek(); + *target = Some(if token.kind == TokenKind::String { + string_ident(p.advance()) + } else { + p.parse_name_part()? + }); + } + if charset.is_none() && collation.is_none() { + return Ok( + StatementKind::CreateDatabase(Box::new(crate::ast::CreateDatabase { + if_not_exists, + name, + })) + .into(), + ); + } + Ok(mysql(MySqlStatement::CreateDatabase(Box::new( + MySqlCreateDatabase { + if_not_exists, + name, + charset, + collation, + }, + )))) +} + +/// Parses `(key_part, ...)`. +fn parse_key_parts<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + p.expect_op("(")?; + let columns = p.parse_comma_separated(D::parse_index_column)?; + p.expect_op(")")?; + Ok(columns) +} + +fn parse_key_options<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let mut options = Vec::new(); + loop { + if p.at_keyword("USING") { + p.advance(); + options.push(KeyOption::Using(p.parse_ident()?)); + } else if p.at_keyword("COMMENT") { + p.advance(); + let token = p.expect_kind(TokenKind::String, "a comment string")?; + options.push(KeyOption::Comment(D::string_literal(token))); + } else { + return Ok(options); + } + } +} + +/// Parses an optional index name, which is absent at `(` or `USING`. +fn parse_key_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.at_op("(") || p.at_keyword("USING") { + return Ok(None); + } + p.parse_name_part().map(Some) +} + +/// True if `token` can start what comes after an index keyword. +fn after_index_keyword<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + let token = p.peek_nth(n); + token.is_op("(") + || token.is_word("USING") + || (matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) + && (p.peek_nth(n + 1).is_op("(") || p.peek_nth(n + 1).is_word("USING"))) +} + +/// Parses `USING INDEX name` if it is here. +fn parse_using_index<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.at_keyword("USING") && p.peek_nth(1).is_word("INDEX") { + p.advance(); + p.advance(); + return p.parse_ident().map(Some); + } + Ok(None) +} + +/// Parses `INCLUDE (columns)` if it is here. +fn parse_include<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.eat_keyword("INCLUDE") { + return grammar::parse_ident_list(p); + } + Ok(Vec::new()) +} + +/// Builds a key, which is the core node when it only has plain columns. +fn finish_key<'a>( + keyword: &'static str, + name: Option>, + using: Option>, + columns: Vec>, + options: Vec>, + plain: impl FnOnce(Vec>) -> TableConstraintKind<'a, Builtin>, +) -> TableConstraintKind<'a, Builtin> { + let is_plain = name.is_none() + && using.is_none() + && options.is_empty() + && columns.iter().all(|column| { + column.operator_class.is_none() + && column.item.asc.is_none() + && column.item.nulls_first.is_none() + && matches!(column.item.expr.kind, ExprKind::Ident(_)) + }); + if is_plain { + let names = columns + .into_iter() + .map(|column| match column.item.expr.kind { + ExprKind::Ident(name) => name, + _ => unreachable!("checked above"), + }) + .collect(); + return plain(names); + } + TableConstraintKind::Key { + keyword: keyword.into(), + name, + using, + columns, + options, + } +} + +/// Parses a table constraint or index definition, or returns `None` if this +/// element is a column. The keyword `CONSTRAINT` can come without a name, and +/// `KEY` and `INDEX` are reserved in MySQL so cannot start a column. +pub fn parse_table_constraint<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut name = None; + if p.at_keyword("CONSTRAINT") { + let next = p.peek_nth(1); + let keyword_next = next.is_word("CHECK") + || next.is_word("PRIMARY") + || next.is_word("UNIQUE") + || next.is_word("FOREIGN"); + p.advance(); + if !keyword_next { + name = Some(p.parse_ident()?); + } + } + let next = p.peek_nth(1); + let mut include = Vec::new(); + let mut nulls_distinct = None; + let kind = if p.at_keyword("PRIMARY") && next.is_word("KEY") { + p.advance(); + p.advance(); + if let Some(index) = parse_using_index(p)? { + TableConstraintKind::PrimaryKeyUsingIndex(index) + } else { + let index = parse_key_name(p)?; + let using = grammar::parse_optional_using(p)?; + let columns = parse_key_parts(p)?; + include = parse_include(p)?; + let options = parse_key_options(p)?; + finish_key( + "PRIMARY KEY", + index, + using, + columns, + options, + TableConstraintKind::PrimaryKey, + ) + } + } else if p.at_keyword("UNIQUE") + && (next.is_op("(") + || next.is_word("KEY") + || next.is_word("INDEX") + || next.is_word("NULLS") + || after_index_keyword(p, 1)) + { + p.advance(); + if let Some(index) = parse_using_index(p)? { + TableConstraintKind::UniqueUsingIndex(index) + } else { + let (keyword, had_keyword) = if p.eat_keyword("KEY") { + ("UNIQUE KEY", true) + } else if p.eat_keyword("INDEX") { + ("UNIQUE INDEX", true) + } else { + ("UNIQUE", false) + }; + nulls_distinct = grammar::parse_nulls_distinct(p)?; + let index = parse_key_name(p)?; + let using = grammar::parse_optional_using(p)?; + let columns = parse_key_parts(p)?; + include = parse_include(p)?; + let options = parse_key_options(p)?; + if had_keyword || index.is_some() || using.is_some() { + TableConstraintKind::Key { + keyword: keyword.into(), + name: index, + using, + columns, + options, + } + } else { + finish_key( + keyword, + index, + using, + columns, + options, + TableConstraintKind::Unique, + ) + } + } + } else if p.at_keyword("FOREIGN") && next.is_word("KEY") { + p.advance(); + p.advance(); + let index_name = if p.at_op("(") { + None + } else { + Some(p.parse_ident()?) + }; + let columns = grammar::parse_ident_list(p)?; + p.expect_keyword("REFERENCES")?; + let references = grammar::parse_foreign_key_ref(p)?; + TableConstraintKind::ForeignKey { + index_name, + columns, + references, + } + } else if p.at_keyword("CHECK") && next.is_op("(") { + p.advance(); + p.advance(); + let expr = p.parse_expr()?; + p.expect_op(")")?; + TableConstraintKind::Check(expr) + } else if (p.at_keyword("KEY") || p.at_keyword("INDEX")) + && name.is_none() + && after_index_keyword(p, 1) + { + let keyword = if p.at_keyword("KEY") { "KEY" } else { "INDEX" }; + p.advance(); + let index = parse_key_name(p)?; + let using = grammar::parse_optional_using(p)?; + let columns = parse_key_parts(p)?; + let options = parse_key_options(p)?; + TableConstraintKind::Key { + keyword: keyword.into(), + name: index, + using, + columns, + options, + } + } else if (p.at_keyword("FULLTEXT") || p.at_keyword("SPATIAL")) + && name.is_none() + && (next.is_word("KEY") || next.is_word("INDEX") || after_index_keyword(p, 1)) + { + let fulltext = p.at_keyword("FULLTEXT"); + p.advance(); + let keyword = match (fulltext, p.eat_keyword("KEY"), p.eat_keyword("INDEX")) { + (true, true, _) => "FULLTEXT KEY", + (true, _, true) => "FULLTEXT INDEX", + (true, _, _) => "FULLTEXT", + (false, true, _) => "SPATIAL KEY", + (false, _, true) => "SPATIAL INDEX", + (false, _, _) => "SPATIAL", + }; + let index = parse_key_name(p)?; + let columns = parse_key_parts(p)?; + TableConstraintKind::Key { + keyword: keyword.into(), + name: index, + using: None, + columns, + options: Vec::new(), + } + } else if name.is_some() { + return Err(p.expected("a table constraint")); + } else { + return Ok(None); + }; + let mut attributes = Vec::new(); + while let Some(attribute) = grammar::parse_constraint_attribute(p)? { + attributes.push(attribute); + } + grammar::check_constraint_attributes(p, attributes.iter().copied())?; + Ok(Some(TableConstraint { + name, + kind, + include, + nulls_distinct, + attributes, + })) +} + +/// Parses the arguments of `JSON_TABLE`, with the current token on `(`. +pub fn parse_json_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("(")?; + let json = p.parse_expr()?; + p.expect_op(",")?; + let path = parse_path(p)?; + p.expect_keyword("COLUMNS")?; + let columns = parse_json_columns(p)?; + p.expect_op(")")?; + Ok(MySqlTableFactor::JsonTable(MySqlJsonTable { + json, + path, + columns, + })) +} + +fn parse_json_columns<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + let columns = p.parse_comma_separated(parse_json_column)?; + p.expect_op(")")?; + Ok(columns) +} + +fn parse_path<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.expect_kind(TokenKind::String, "a JSON path string")?; + Ok(D::string_literal(token)) +} + +fn parse_json_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("NESTED") { + p.eat_keyword("PATH"); + let path = parse_path(p)?; + p.expect_keyword("COLUMNS")?; + let columns = p.nested(parse_json_columns)?; + return Ok(MySqlJsonColumn::Nested { path, columns }); + } + let name = p.parse_ident()?; + if p.eat_keyword("FOR") { + p.expect_keyword("ORDINALITY")?; + return Ok(MySqlJsonColumn::Ordinality(name)); + } + let data_type = D::parse_data_type(p)?; + let exists = p.eat_keyword("EXISTS"); + p.expect_keyword("PATH")?; + let path = parse_path(p)?; + let (mut on_empty, mut on_error) = (None, None); + while let Some(fallback) = parse_json_fallback(p)? { + p.expect_keyword("ON")?; + if p.eat_keyword("EMPTY") { + on_empty = Some(fallback); + } else { + p.expect_keyword("ERROR")?; + on_error = Some(fallback); + } + } + Ok(MySqlJsonColumn::Named(Box::new(MySqlJsonNamedColumn { + name, + data_type, + exists, + path, + on_empty, + on_error, + }))) +} + +fn parse_json_fallback<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("NULL") { + Ok(Some(MySqlJsonFallback::Null)) + } else if p.eat_keyword("ERROR") { + Ok(Some(MySqlJsonFallback::Error)) + } else if p.eat_keyword("DEFAULT") { + parse_path(p).map(|value| Some(MySqlJsonFallback::Default(value))) + } else { + Ok(None) + } +} + +impl fmt::Display for MySqlStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::RenameTable(renames) => { + f.write_str("RENAME TABLE ")?; + for (i, (from, to)) in renames.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{from} TO {to}")?; + } + Ok(()) + } + Self::LockTables(tables) => write!(f, "LOCK TABLES {}", comma(tables)), + Self::UnlockTables => f.write_str("UNLOCK TABLES"), + Self::Flush(flush) => flush.fmt(f), + Self::Kill { modifier, id } => match modifier { + Some(modifier) => write!(f, "KILL {modifier} {id}"), + None => write!(f, "KILL {id}"), + }, + Self::Insert(insert) => insert.fmt(f), + Self::CreateTable(table) => table.fmt(f), + Self::CreateDatabase(database) => database.fmt(f), + Self::CreateView(view) => view.fmt(f), + Self::CreateTrigger(trigger) => trigger.fmt(f), + } + } +} + +impl fmt::Display for MySqlLockedTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.table.fmt(f)?; + if let Some(alias) = &self.alias { + write!(f, " AS {alias}")?; + } + f.write_str(match self.lock { + MySqlLock::Read { local: false } => " READ", + MySqlLock::Read { local: true } => " READ LOCAL", + MySqlLock::Write { + low_priority: false, + } => " WRITE", + MySqlLock::Write { low_priority: true } => " LOW_PRIORITY WRITE", + }) + } +} + +impl fmt::Display for MySqlFlush<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("FLUSH ")?; + if let Some(ref location) = self.location { + write!(f, "{location} ")?; + } + f.write_str(&self.object)?; + if let Some(channel) = &self.channel { + write!(f, " FOR CHANNEL {channel}")?; + } + if !self.tables.is_empty() { + write!(f, " {}", comma(&self.tables))?; + } + if self.read_lock { + f.write_str(" WITH READ LOCK")?; + } else if self.export { + f.write_str(" FOR EXPORT")?; + } + Ok(()) + } +} + +impl fmt::Display for MySqlInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(if self.replace { "REPLACE " } else { "INSERT " })?; + write_insert_body(f, &self.insert)?; + if let Some((name, columns)) = &self.alias { + write!(f, " AS {name}")?; + if !columns.is_empty() { + write!(f, " ({})", comma(columns))?; + } + } + if !self.on_duplicate.is_empty() { + write!(f, " ON DUPLICATE KEY UPDATE {}", comma(&self.on_duplicate))?; + } + Ok(()) + } +} + +impl fmt::Display for MySqlTableOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::KeyValue { name, value } => write!(f, "{name} = {value}"), + Self::Comment { equals, text } => { + let equals = if *equals { "= " } else { "" }; + write!(f, "COMMENT {equals}{}", text) + } + Self::Engine(name) => write!(f, "ENGINE = {name}"), + Self::Like(source) => write!(f, "LIKE {source}"), + Self::Tablespace { name, storage } => { + write!(f, "TABLESPACE {name}")?; + match storage { + Some(storage) => write!(f, " STORAGE {storage}"), + None => Ok(()), + } + } + Self::Union(tables) => write!(f, "UNION = ({})", comma(tables)), + Self::StartTransaction => f.write_str("START TRANSACTION"), + } + } +} + +impl fmt::Display for MySqlCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + write_create_flags(f, table.or_replace, table.temporary)?; + f.write_str("TABLE ")?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + if !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + for option in &self.options { + write!(f, " {option}")?; + } + match &table.query { + Some(query) => write!(f, " AS {query}"), + None => Ok(()), + } + } +} + +impl fmt::Display for MySqlCreateDatabase<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE DATABASE ")?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if let Some(charset) = &self.charset { + write!(f, " DEFAULT CHARACTER SET {charset}")?; + } + if let Some(collation) = &self.collation { + write!(f, " DEFAULT COLLATE {collation}")?; + } + Ok(()) + } +} + +fn write_view_params( + f: &mut fmt::Formatter<'_>, + algorithm: Option<&str>, + definer: Option<&Grantee<'_>>, + security: Option<&str>, +) -> fmt::Result { + if let Some(algorithm) = algorithm { + write!(f, "ALGORITHM = {algorithm} ")?; + } + if let Some(definer) = definer { + write!(f, "DEFINER = {definer} ")?; + } + if let Some(security) = security { + write!(f, "SQL SECURITY {security} ")?; + } + Ok(()) +} + +impl fmt::Display for MySqlCreateView<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let view = &self.view; + write_create_flags(f, view.or_replace, view.temporary)?; + write_view_params( + f, + self.algorithm.as_deref(), + self.definer.as_ref(), + self.security.as_deref(), + )?; + if view.materialized { + f.write_str("MATERIALIZED ")?; + } + f.write_str("VIEW ")?; + write_if_not_exists(f, view.if_not_exists)?; + view.name.fmt(f)?; + if !view.columns.is_empty() { + write!(f, " ({})", comma(&view.columns))?; + } + crate::display::write_view_query(f, &view.query) + } +} + +impl fmt::Display for MySqlCreateTrigger<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + write_view_params(f, None, self.definer.as_ref(), None)?; + f.write_str("TRIGGER ")?; + write_if_not_exists(f, self.if_not_exists)?; + write!( + f, + "{} {} {} ON {} FOR EACH ROW", + self.name, self.period, self.event, self.table + )?; + if let Some((word, other)) = &self.order { + write!(f, " {word} {other}")?; + } + match &self.body { + MySqlTriggerBody::Statement(statement) => write!(f, " {statement}"), + MySqlTriggerBody::Block(statements) => { + f.write_str(" BEGIN ")?; + for statement in statements { + write!(f, "{statement}; ")?; + } + f.write_str("END") + } + } + } +} + +impl fmt::Display for MySqlTableFactor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Partitioned { name, partitions } => { + write!(f, "{name} PARTITION ({})", comma(partitions)) + } + Self::Hinted { table, hints } => { + table.fmt(f)?; + for hint in hints { + write!(f, " {hint}")?; + } + Ok(()) + } + Self::JsonTable(table) => table.fmt(f), + } + } +} + +impl fmt::Display for MySqlIndexHint<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} {}", + self.verb, + if self.key { "KEY" } else { "INDEX" } + )?; + if let Some(ref target) = self.target { + write!(f, " FOR {target}")?; + } + write!(f, " ({})", comma(&self.names)) + } +} + +impl fmt::Display for MySqlJsonTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if !f.alternate() { + return write!( + f, + "JSON_TABLE({}, {} COLUMNS({}))", + self.json, + self.path, + comma(&self.columns) + ); + } + f.write_str("JSON_TABLE(")?; + NewLine.fmt(f)?; + Indent(JsonTableArguments(self)).fmt(f)?; + NewLine.fmt(f)?; + f.write_str(")") + } +} + +/// The arguments of `JSON_TABLE`, in its multi-line form. +struct JsonTableArguments<'s, 'a>(&'s MySqlJsonTable<'a>); + +impl fmt::Display for JsonTableArguments<'_, '_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{},", self.0.json)?; + SpaceOrNewline.fmt(f)?; + write!(f, "{} COLUMNS (", self.0.path)?; + NewLine.fmt(f)?; + Indent(CommaLines(&self.0.columns)).fmt(f)?; + NewLine.fmt(f)?; + f.write_str(")") + } +} + +impl fmt::Display for MySqlJsonColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Ordinality(name) => write!(f, "{name} FOR ORDINALITY"), + Self::Nested { path, columns } => { + write!(f, "NESTED PATH {} COLUMNS ({})", path, comma(columns)) + } + Self::Named(column) => column.fmt(f), + } + } +} + +impl fmt::Display for MySqlJsonNamedColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {}", self.name, self.data_type)?; + if self.exists { + f.write_str(" EXISTS")?; + } + write!(f, " PATH {}", self.path)?; + if let Some(fallback) = &self.on_empty { + write!(f, " {fallback} ON EMPTY")?; + } + if let Some(fallback) = &self.on_error { + write!(f, " {fallback} ON ERROR")?; + } + Ok(()) + } +} + +impl fmt::Display for MySqlJsonFallback<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Null => f.write_str("NULL"), + Self::Error => f.write_str("ERROR"), + Self::Default(value) => write!(f, "DEFAULT {}", value), + } + } +} diff --git a/sqlparser_v2/src/dialect/oracle.rs b/sqlparser_v2/src/dialect/oracle.rs new file mode 100644 index 0000000000..5aca442602 --- /dev/null +++ b/sqlparser_v2/src/dialect/oracle.rs @@ -0,0 +1,883 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Oracle Database. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + BinaryOp, ColumnOption, ConnectBy, CreateFlags, CreateSchema, CreateTable, Delete, Expr, + ExprKind, Ident, Insert, InsertSource, IsTest, ListAggOnOverflow, Merge, NullTreatment, + ObjectName, ObjectType, Query, SelectInto, SelectItem, SpecialExpr, Statement, StatementKind, + StringLiteral, TableFactor, TableRef, TableWithJoins, Update, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinSelect, BuiltinStatement}; +use crate::dialect::{Builtin, Dialect, hive, postgres, snowflake}; +use crate::display::{ + comma, write_delete_body, write_list_clause, write_merge_body, write_update_body, +}; +use crate::grammar::{self, prec}; +use crate::lexer::{self, LexResult, Lexeme, Token, TokenKind}; +use crate::parser::{InfixRule, Parser, SetOperatorRule}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Oracle; + +/// Expressions only Oracle Database has. +#[derive(Debug, Clone, PartialEq)] +pub enum OracleExpr<'a> { + QuoteDelimited(Box>), +} + +/// `Q'[text]'` or `NQ'[text]'` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QuoteDelimitedString<'a> { + pub national: bool, + pub start: char, + pub value: Cow<'a, str>, + pub end: char, +} + +/// A comment read as instructions to the optimizer: `/*+ text */` or +/// `--+ text`, with any letters and digits before the `+` in `prefix`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OptimizerHint<'a> { + pub prefix: Cow<'a, str>, + pub text: Cow<'a, str>, + pub style: HintStyle, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HintStyle { + SingleLine, + MultiLine, +} + +/// Statements only Oracle Database has. +#[derive(Debug, Clone, PartialEq)] +pub enum OracleStatement<'a> { + Insert(Box>), + /// `UPDATE` with optimizer hints. + Update { + hints: Vec>, + update: Box>, + }, + /// `DELETE` with optimizer hints or without `FROM`. + Delete { + hints: Vec>, + from_keyword: bool, + delete: Box>, + }, + /// `MERGE` with optimizer hints. + Merge { + hints: Vec>, + merge: Box>, + }, + /// `EXECUTE IMMEDIATE sql [INTO a, ...] [USING expr [AS name], ...]` + ExecuteImmediate { + sql: Expr<'a, Builtin>, + into: Vec>, + using: Vec<(Expr<'a, Builtin>, Option>)>, + }, + /// `SET name [, name ...] value`, with no `=` or `TO`. + SetParameters { + names: Vec>, + value: Expr<'a, Builtin>, + }, +} + +/// `INSERT` with syntax the core node cannot hold. +#[derive(Debug, Clone, PartialEq)] +pub struct OracleInsert<'a> { + pub hints: Vec>, + pub target: InsertTarget<'a>, + pub alias: Option>, + pub columns: Vec>, + pub source: InsertSource<'a, Builtin>, + pub returning: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum InsertTarget<'a> { + Table(ObjectName<'a>), + /// `INSERT INTO (SELECT ...) ...` + Query(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct InsertAlias<'a> { + pub name: Ident<'a>, + pub explicit: bool, +} + +#[inline] +fn is_name_char(c: char) -> bool { + c.is_alphanumeric() || matches!(c, '_' | '$' | '#' | '@') +} + +/// Lexes a name, which must start with a letter. +#[inline] +fn lex_name(rest: &str) -> Option { + let first = rest.chars().next()?; + if !first.is_alphabetic() { + return (first == '_' || !first.is_ascii()).then_some(Err("unexpected character")); + } + let len = rest + .char_indices() + .find(|&(_, c)| !is_name_char(c)) + .map_or(rest.len(), |(i, _)| i); + Some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })) +} + +/// The length of the prefix of a quote-delimited string starting `rest`. +#[inline] +fn quote_delimited_prefix(bytes: &[u8]) -> Option { + match bytes { + [b'q' | b'Q', b'\'', ..] => Some(1), + [b'n' | b'N', b'q' | b'Q', b'\'', ..] => Some(2), + _ => None, + } +} + +fn closing_delimiter(start: char) -> char { + match start { + '[' => ']', + '{' => '}', + '<' => '>', + '(' => ')', + other => other, + } +} + +/// Lexes `Q'text'`, starting at its opening quote. +fn lex_quote_delimited(rest: &str, prefix: usize) -> LexResult { + let after_quote = &rest[prefix + 1..]; + let start = match after_quote.chars().next() { + None | Some(' ' | '\t' | '\r' | '\n') => { + return Err("invalid space, tab, newline or end of input after Q'"); + } + Some(c) => c, + }; + let end = closing_delimiter(start); + let body = &after_quote[start.len_utf8()..]; + let close = body + .char_indices() + .find(|&(i, c)| c == end && body[i + c.len_utf8()..].starts_with('\'')) + .ok_or("unterminated quoted text")?; + Ok(Lexeme { + kind: TokenKind::DialectLiteral, + len: prefix + 1 + start.len_utf8() + close.0 + end.len_utf8() + 1, + }) +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + let bytes = rest.as_bytes(); + if let Some(prefix) = quote_delimited_prefix(bytes) { + return Some(lex_quote_delimited(rest, prefix)); + } + if matches!(bytes, [b'n' | b'N', b'\'', ..]) { + return Some( + lexer::quoted(&rest[1..], TokenKind::String).map(|string| Lexeme { + kind: TokenKind::String, + len: string.len + 1, + }), + ); + } + match bytes[0] { + // `x'AB'` is a hex string, which the core lexes. + b'x' | b'X' if bytes.get(1) == Some(&b'\'') => None, + b'{' | b'}' => Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })), + // A lone `$` is the end anchor of a `MATCH_RECOGNIZE` pattern. + b'$' if !bytes + .get(1) + .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_') => + { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })) + } + _ => lex_name(rest), + } +} + +/// `--` starts a line comment, and block comments do not nest. +#[inline] +pub fn lex_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'-', b'-', ..] => Some(Ok(lexer::line_comment(rest))), + [b'/', b'*', ..] => Some(lexer::block_comment(rest, false)), + _ => None, + } +} + +/// Builds the node for a token from [`lex_quote_delimited`]. +fn quote_delimited_string(text: &str) -> QuoteDelimitedString<'_> { + let (prefix, national) = match quote_delimited_prefix(text.as_bytes()) { + Some(2) => (2, true), + _ => (1, false), + }; + let after_quote = &text[prefix + 1..]; + let start = after_quote.chars().next().unwrap_or_default(); + let end = closing_delimiter(start); + let value = &after_quote[start.len_utf8()..after_quote.len() - end.len_utf8() - 1]; + QuoteDelimitedString { + national, + start, + value: value.into(), + end, + } +} + +/// Splits a comment's text at a `+` that only letters and digits come before. +fn hint_parts(comment: &str) -> Option<(&str, &str)> { + let (prefix, text) = comment.split_once('+')?; + prefix + .bytes() + .all(|b| b.is_ascii_alphanumeric()) + .then_some((prefix, text)) +} + +/// Finds the optimizer hints in text holding only whitespace and comments. +fn parse_hints(mut gap: &str) -> Vec> { + let mut hints = Vec::new(); + loop { + gap = gap.trim_ascii_start(); + let (comment, style, len) = if gap.starts_with("--") { + let len = lexer::line_comment(gap); + let comment = gap[2..len].strip_suffix('\n').unwrap_or(&gap[2..len]); + (comment, HintStyle::SingleLine, len) + } else if gap.starts_with("/*") { + let Ok(len) = lexer::block_comment(gap, false) else { + return hints; + }; + (&gap[2..len - 2], HintStyle::MultiLine, len) + } else { + return hints; + }; + if let Some((prefix, text)) = hint_parts(comment) { + hints.push(OptimizerHint { + prefix: prefix.into(), + text: text.into(), + style, + }); + } + gap = &gap[len..]; + } +} + +/// True at the `(SELECT` or `(WITH` of an `INSERT` into a query. +fn at_insert_query(p: &Parser<'_, D>) -> bool { + let next = p.peek_nth(1); + p.at_op("(") && (next.is_word("SELECT") || next.is_word("WITH")) +} + +fn parse_insert_alias<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let explicit = p.eat_keyword("AS"); + if !explicit && (!p.at_implicit_alias() || p.at_keyword("VALUES") || p.at_keyword("DEFAULT")) { + return Ok(None); + } + Ok(Some(InsertAlias { + name: p.parse_ident()?, + explicit, + })) +} + +fn parse_insert_target<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !at_insert_query(p) { + return grammar::parse_object_name(p).map(InsertTarget::Table); + } + p.advance(); + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + Ok(InsertTarget::Query(Box::new(query))) +} + +/// Parses `INSERT`, keeping the core node when nothing needs more than it holds. +pub fn parse_insert<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INSERT")?; + let hints = parse_hints(p.gap_before_nth(0)); + p.expect_keyword("INTO")?; + let target = parse_insert_target(p)?; + let alias = parse_insert_alias(p)?; + let columns = if grammar::at_column_list(p) { + p.advance(); + let columns = p.parse_comma_separated(grammar::parse_object_name)?; + p.expect_op(")")?; + columns + } else { + Vec::new() + }; + let source = grammar::parse_insert_source(p)?; + let returning = D::parse_returning(p)?; + let plain = hints.is_empty() && alias.is_none() && columns.iter().all(|c| c.parts.len() == 1); + let target = match target { + InsertTarget::Table(table) if plain => { + return Ok(StatementKind::Insert(Box::new(Insert { + into: true, + output: None, + modifiers: Default::default(), + table, + columns: columns.into_iter().map(|mut c| c.parts.remove(0)).collect(), + source, + returning, + })) + .into()); + } + other => other, + }; + Ok(oracle(OracleStatement::Insert(Box::new(OracleInsert { + hints, + target, + alias, + columns, + source, + returning, + })))) +} + +fn parse_delete<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DELETE")?; + let hints = parse_hints(p.gap_before_nth(0)); + let from_keyword = p.eat_keyword("FROM"); + let table = p.parse_table_ref()?; + let selection = if p.eat_keyword("WHERE") { + Some(p.parse_expr()?) + } else { + None + }; + let returning = D::parse_returning(p)?; + let delete = Box::new(Delete { + output: None, + multi: None, + using: Vec::new(), + table, + selection, + order_by: Vec::new(), + limit: None, + returning, + }); + if from_keyword && hints.is_empty() { + return Ok(StatementKind::Delete(delete).into()); + } + Ok(oracle(OracleStatement::Delete { + hints, + from_keyword, + delete, + })) +} + +pub fn parse_execute_immediate<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("EXECUTE")?; + p.expect_keyword("IMMEDIATE")?; + let sql = p.parse_expr()?; + let into = if p.eat_keyword("INTO") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + let using = if p.eat_keyword("USING") { + p.parse_comma_separated(|p| { + let value = p.parse_expr()?; + let alias = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + Ok((value, alias)) + })? + } else { + Vec::new() + }; + Ok(OracleStatement::ExecuteImmediate { sql, into, using }) +} + +/// True at `SET name [, name ...] value`, where no `=` or `TO` comes after the +/// names. +fn at_set_parameters(p: &Parser<'_, D>) -> bool { + if !p.at_keyword("SET") || grammar::at_special_set(p) { + return false; + } + let first = p.peek_nth(1); + if ["LOCAL", "SESSION", "GLOBAL"] + .iter() + .any(|scope| first.is_word(scope)) + { + return false; + } + let mut n = 1; + loop { + if p.peek_nth(n).kind != TokenKind::Word { + return false; + } + n += 1; + if !p.peek_nth(n).is_op(",") { + break; + } + n += 1; + } + let next = p.peek_nth(n); + next.kind != TokenKind::Eof + && !next.is_op("=") + && !next.is_op(".") + && !next.is_op(";") + && !next.is_word("TO") +} + +fn parse_set_parameters<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SET")?; + let names = p.parse_comma_separated(|p| Ok(p.advance().text))?; + let token = p.peek(); + // A reserved word such as `ON` is the value's whole text. + let value = if token.kind == TokenKind::Word && D::is_reserved(token.text) { + p.advance(); + Expr::new( + ExprKind::Ident(Ident { + text: token.text.into(), + quote: None, + span: token.span, + }), + token.span, + ) + } else { + p.parse_expr()? + }; + Ok(OracleStatement::SetParameters { + names: names.into_iter().map(Cow::Borrowed).collect(), + value, + }) +} + +fn oracle<'a>(statement: OracleStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::Oracle(statement)).into() +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("ALTER") && p.peek_nth(1).is_word("INDEX") { + return grammar::parse_alter_index_rename(p); + } + if p.at_keyword("DELETE") { + return parse_delete(p); + } + if p.at_keyword("UPDATE") { + let hints = parse_hints(p.gap_before_nth(1)); + if !hints.is_empty() { + let update = Box::new(D::parse_update(p)?); + return Ok(oracle(OracleStatement::Update { hints, update })); + } + } + if p.at_keyword("MERGE") { + let hints = parse_hints(p.gap_before_nth(1)); + if !hints.is_empty() { + let merge = Box::new(D::parse_merge(p)?); + return Ok(oracle(OracleStatement::Merge { hints, merge })); + } + } + if p.at_keyword("COMMENT") { + return grammar::parse_comment_on(p).map(|c| StatementKind::Comment(Box::new(c)).into()); + } + if p.at_keyword("EXECUTE") && p.peek_nth(1).is_word("IMMEDIATE") { + return parse_execute_immediate(p).map(oracle); + } + if at_set_parameters(p) { + return parse_set_parameters(p).map(oracle); + } + grammar::parse_statement(p) +} + +/// Parses what follows `CREATE ... TABLE`, where `AS` before `SELECT` is optional. +pub fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let query = if p.eat_keyword("AS") || p.at_keyword("SELECT") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() { + return Err(p.expected("column definitions, AS or SELECT")); + } + Ok(CreateTable { + or_replace: flags.or_replace, + temporary: flags.temporary, + name, + if_not_exists, + columns, + constraints, + query, + }) +} + +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::DialectLiteral { + p.advance(); + let string = quote_delimited_string(token.text); + return Ok( + ExprKind::Ext(BuiltinExpr::Oracle(OracleExpr::QuoteDelimited(Box::new( + string, + )))) + .into(), + ); + } + if token.kind != TokenKind::Word { + return grammar::parse_prefix(p); + } + if p.has_context(grammar::CONTEXT_CONNECT_BY) && p.eat_keyword("PRIOR") { + let expr = p.parse_expr_bp(prec::ADD)?; + return Ok(ExprKind::Special(Box::new(SpecialExpr::Prior(expr))).into()); + } + if p.eat_keyword("CONNECT_BY_ROOT") { + let expr = p.parse_expr_bp(prec::UNARY)?; + return Ok(ExprKind::Special(Box::new(SpecialExpr::ConnectByRoot(expr))).into()); + } + // Oracle has no boolean literals here, so these are ordinary names. + if p.at_keyword("TRUE") || p.at_keyword("FALSE") { + return grammar::parse_name_expr(p); + } + grammar::parse_prefix(p) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + if snowflake::at_outer_join_mark(p) { + return Some(InfixRule::custom( + prec::POSTFIX, + snowflake::parse_outer_join_mark, + )); + } + if p.at_op("||") { + return Some(InfixRule::binary(prec::ADD, BinaryOp::StringConcat)); + } + grammar::infix_rule(p) +} + +pub fn parse_select_modifiers<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + Ok(BuiltinSelect { + hints: parse_hints(p.gap_before_nth(0)), + ..Default::default() + }) +} + +impl Dialect for Oracle { + /// Recursive CTEs need no keyword here, and `RECURSIVE` is rejected. + fn eat_with_recursive<'a>(_p: &mut Parser<'a, Self>) -> bool { + false + } + + type Ext = Builtin; + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, false) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + if p.eat_keyword("INVISIBLE") { + return Ok(Some(ColumnOption::Keyword { + keyword: "INVISIBLE".into(), + expr: None, + })); + } + grammar::parse_column_option(p) + } + + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + if flags != CreateFlags::default() { + return Err(p.expected("TABLE or VIEW")); + } + grammar::parse_create_schema_authorization(p, false) + } + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_variables(p) + } + + fn parse_is_test<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_is_json(p) + } + + fn parse_function_on_overflow<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_on_overflow(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + grammar::eat_drop_object_type(p, &["TYPE"]) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + grammar::national_string_literal(token) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + lex_comment(rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + if word.eq_ignore_ascii_case("TRUE") || word.eq_ignore_ascii_case("FALSE") { + return false; + } + // A prefix operator rather than a name. + word.eq_ignore_ascii_case("CONNECT_BY_ROOT") || grammar::is_reserved(word) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + [ + "MINUS", + "START", + "CONNECT", + "MATCH_RECOGNIZE", + "PIVOT", + "UNPIVOT", + "SAMPLE", + "TABLESAMPLE", + "RETURNING", + ] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved_for_alias(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert(p) + } + + fn parse_returning<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + postgres::parse_returning(p) + } + + fn parse_create_table<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + parse_create_table(p, flags) + } + + fn parse_select_modifiers<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_modifiers(p) + } + + fn parse_connect_by<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_connect_by_clauses(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + snowflake::parse_table_ref(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if grammar::at_xml_table(p) { + return grammar::parse_xml_table(p, false); + } + hive::parse_table_factor(p) + } + + fn parse_function_arg_null_treatment<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult> { + Ok(grammar::parse_null_treatment(p)) + } + + fn parse_function_filter<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + fn at_function_call<'a>(p: &Parser<'a, Self>) -> bool { + p.at_op("(") && !snowflake::at_outer_join_mark(p) + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + snowflake::set_operator_rule(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } +} + +impl fmt::Display for OracleExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::QuoteDelimited(string) => string.fmt(f), + } + } +} + +impl fmt::Display for QuoteDelimitedString<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let prefix = if self.national { "NQ" } else { "Q" }; + write!(f, "{prefix}'{}{}{}'", self.start, self.value, self.end) + } +} + +impl fmt::Display for OptimizerHint<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.style { + HintStyle::SingleLine => writeln!(f, "--{}+{}", self.prefix, self.text), + HintStyle::MultiLine => write!(f, "/*{}+{}*/", self.prefix, self.text), + } + } +} + +/// Writes hints in the place a statement's modifiers go, each ending in a space. +pub(crate) fn write_hints(f: &mut fmt::Formatter<'_>, hints: &[OptimizerHint<'_>]) -> fmt::Result { + hints.iter().try_for_each(|hint| write!(f, "{hint} ")) +} + +impl fmt::Display for InsertTarget<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Table(name) => name.fmt(f), + Self::Query(query) => write!(f, "({query})"), + } + } +} + +impl fmt::Display for OracleInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("INSERT ")?; + write_hints(f, &self.hints)?; + write!(f, "INTO {}", self.target)?; + if let Some(alias) = &self.alias { + let keyword = if alias.explicit { "AS " } else { "" }; + write!(f, " {keyword}{}", alias.name)?; + } + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + crate::display::write_insert_source(f, &self.source, !self.columns.is_empty())?; + write_list_clause(f, "RETURNING", &self.returning) + } +} + +impl fmt::Display for OracleStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Insert(insert) => insert.fmt(f), + Self::Update { hints, update } => { + f.write_str("UPDATE ")?; + write_hints(f, hints)?; + write_update_body(f, update) + } + Self::Delete { + hints, + from_keyword, + delete, + } => { + f.write_str("DELETE")?; + for hint in hints { + write!(f, " {hint}")?; + } + if *from_keyword { + f.write_str(" FROM")?; + } + write_delete_body(f, delete) + } + Self::Merge { hints, merge } => { + f.write_str("MERGE ")?; + write_hints(f, hints)?; + write_merge_body(f, merge) + } + Self::ExecuteImmediate { sql, into, using } => { + write!(f, "EXECUTE IMMEDIATE {sql}")?; + if !into.is_empty() { + write!(f, " INTO {}", comma(into))?; + } + for (i, (value, alias)) in using.iter().enumerate() { + f.write_str(if i == 0 { " USING " } else { ", " })?; + write!(f, "{value}")?; + if let Some(alias) = alias { + write!(f, " AS {alias}")?; + } + } + Ok(()) + } + Self::SetParameters { names, value } => { + write!(f, "SET {} {value}", names.join(", ")) + } + } + } +} diff --git a/sqlparser_v2/src/dialect/postgres.rs b/sqlparser_v2/src/dialect/postgres.rs new file mode 100644 index 0000000000..c26e0ace8a --- /dev/null +++ b/sqlparser_v2/src/dialect/postgres.rs @@ -0,0 +1,2833 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! PostgreSQL. +//! +//! The rules are public and generic over the host dialect so that dialects +//! derived from PostgreSQL can reuse them. See [`super::redshift`]. + +use crate::ast::Span; +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +pub use crate::ast::PartitionBound; +use crate::ast::{ + AlterTable, AlterTableOp, ArrayType, Assignment, BinaryOp, CastStyle, ColumnOption, + CreateFlags, CreateSchema, CreateView, Cte, DataType, DataTypeSuffix, DropBehavior, DropObject, + ExplainOption, Expr, ExprKind, FunctionArg, GeneratedKind, GeneratedStorage, Grant, Ident, + IndexFlags, IndexStorage, Insert, InsertSource, IntervalFields, IsTest, Join, JoinConstraint, + JoinKind, LikeKind, Limit, ObjectName, ObjectType, OperatorName, OrderByItem, Privileges, + Query, SelectInto, SelectItem, SetExpr, SetStatement, SpecialExpr, Statement, StatementKind, + StringLiteral, StringPrefix, TableAlias, TableConstraint, TableFactor, TableRef, + TableWithJoins, TypedString, +}; +use crate::dialect::builtin::{ + BuiltinExpr, BuiltinJoinConstraint, BuiltinSelect, BuiltinTableFactor, +}; +use crate::dialect::{Builtin, Dialect}; +use crate::display::{comma, write_insert_source, write_list_clause}; +use crate::grammar::{self, prec}; +use crate::lexer::{LexResult, Lexeme, Token, TokenKind, quoted, quoted_with_backslash}; +use crate::parser::{InfixRule, Parser}; + +pub mod ddl; +pub mod table; +pub mod utility; + +pub use ddl::*; +pub use table::*; +pub use utility::*; + +#[derive(Debug, Clone, PartialEq)] +pub struct Postgres; + +/// PostgreSQL's operators with their binding powers, longest first so that +/// a prefix cannot match before the whole operator. +const OPERATORS: [(&str, u8); 21] = [ + ("!~~*", prec::COMPARE), + ("!~~", prec::COMPARE), + ("!~*", prec::COMPARE), + ("~~*", prec::COMPARE), + ("->>", prec::OTHER), + ("#>>", prec::OTHER), + ("!~", prec::COMPARE), + ("~~", prec::COMPARE), + ("~*", prec::COMPARE), + ("->", prec::OTHER), + ("#>", prec::OTHER), + // Deletes a path from a `jsonb` value. + ("#-", prec::OTHER), + ("@>", prec::OTHER), + ("<@", prec::OTHER), + ("@?", prec::OTHER), + ("@@", prec::OTHER), + ("?|", prec::OTHER), + ("?&", prec::OTHER), + ("&&", prec::OTHER), + ("~", prec::COMPARE), + ("?", prec::OTHER), +]; + +/// True for the functions PostgreSQL calls without parentheses: the standard +/// ones, plus `USER`, `CURRENT_CATALOG`, `CURRENT_SCHEMA` and `SYSTEM_USER`. +pub fn is_niladic_function(word: &str) -> bool { + grammar::is_niladic_function(word) + || ["USER", "CURRENT_CATALOG", "CURRENT_SCHEMA", "SYSTEM_USER"] + .iter() + .any(|name| word.eq_ignore_ascii_case(name)) +} + +#[inline] +fn may_start_operator(byte: u8) -> bool { + matches!(byte, b'!' | b'~' | b'-' | b'#' | b'@' | b'<' | b'?' | b'&') +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Ok(Lexeme { + kind: TokenKind::Op, + len, + }) + }; + if rest.starts_with("::") { + return Some(op(2)); + } + if rest.as_bytes()[0] == b'$' { + return dollar_string(rest); + } + if !may_start_operator(rest.as_bytes()[0]) { + return None; + } + OPERATORS + .iter() + .find(|(text, _)| rest.starts_with(text)) + .map(|(text, _)| op(text.len())) +} + +/// Lexes `$tag$text$tag$`. Returns `None` for what is not one, such as `$1`. +#[inline] +pub fn dollar_string(rest: &str) -> Option { + let bytes = rest.as_bytes(); + if bytes.get(1).is_some_and(u8::is_ascii_digit) { + return None; + } + let tag = bytes[1..] + .iter() + .take_while(|&&b| b.is_ascii_alphanumeric() || b == b'_' || !b.is_ascii()) + .count(); + if bytes.get(tag + 1) != Some(&b'$') { + return None; + } + let delimiter = &rest[..tag + 2]; + let body = tag + 2; + Some(match rest[body..].find(delimiter) { + Some(end) => Ok(Lexeme { + kind: TokenKind::DollarString, + len: body + end + delimiter.len(), + }), + None => Err("unterminated dollar-quoted string"), + }) +} + +/// Everything PostgreSQL ranks differently from the core. +fn operator_rule<'a, D: Dialect>(text: &str) -> Option> { + let core = |op| Some(InfixRule::binary(prec::OTHER, op)); + match text { + "||" => core(BinaryOp::StringConcat), + "|" => core(BinaryOp::BitOr), + "&" => core(BinaryOp::BitAnd), + "<<" => core(BinaryOp::ShiftLeft), + ">>" => core(BinaryOp::ShiftRight), + // Exponentiation; PostgreSQL writes XOR as `#`. + "^" => Some(InfixRule::binary(prec::EXP, BinaryOp::Named("^".into()))), + _ if may_start_operator(text.as_bytes()[0]) => OPERATORS + .iter() + .find(|(operator, _)| *operator == text) + .map(|(operator, bp)| InfixRule::binary(*bp, BinaryOp::Named((*operator).into()))), + _ => None, + } +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + if p.at_keyword("NOTNULL") || p.at_keyword("ISNULL") { + return Some(InfixRule::custom(prec::IS, parse_postfix_null)); + } + infix_rule_without_null_tests(p) +} + +/// The operators of [`infix_rule`] apart from the postfix `ISNULL` and +/// `NOTNULL`, which Redshift does not have. +pub fn infix_rule_without_null_tests<'a, D: Dialect>( + p: &Parser<'a, D>, +) -> Option> { + let token = p.peek(); + if token.kind == TokenKind::Op + && let Some(rule) = operator_rule(token.text) + { + return Some(rule); + } + if p.at_op("::") { + Some(InfixRule::custom(prec::POSTFIX, parse_double_colon)) + } else if p.at_keyword("ILIKE") { + Some(InfixRule::custom(prec::COMPARE, parse_ilike)) + } else if p.at_keyword("NOT") && next_is_ilike(p) { + Some(InfixRule::custom(prec::COMPARE, parse_not_ilike)) + } else { + grammar::infix_rule(p) + } +} + +pub fn next_is_ilike<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.peek_nth(1).is_word("ILIKE") +} + +pub fn parse_ilike<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + grammar::parse_like_operand(p, left, false, LikeKind::ILike) +} + +pub fn parse_not_ilike<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + grammar::parse_like_operand(p, left, true, LikeKind::ILike) +} + +pub fn parse_double_colon<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + let ty = Box::new(D::parse_data_type(p)?); + Ok(ExprKind::Cast { + expr: Box::new(left), + ty, + style: CastStyle::DoubleColon, + } + .into()) +} + +/// Accepts `INTERVAL [fields] [(precision)]` as well as the core types. +pub fn parse_data_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut qualifier = Vec::new(); + while matches!(p.peek().kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(1).is_op(".") + && matches!(p.peek_nth(2).kind, TokenKind::Word | TokenKind::QuotedIdent) + { + qualifier.push(p.parse_name_part()?); + p.advance(); + } + if !p.at_keyword("INTERVAL") { + let mut ty = grammar::parse_data_type(p)?; + if ty.array == ArrayType::None && p.at_op("[") { + ty.array = grammar::parse_array_brackets(p)?; + } + ty.qualifier = qualifier; + return Ok(ty); + } + let name = p.parse_ident()?; + let suffix = + parse_interval_fields(p)?.map_or(DataTypeSuffix::None, DataTypeSuffix::IntervalFields); + let args = grammar::parse_optional_precision(p)? + .into_iter() + .map(Cow::Borrowed) + .collect(); + Ok(DataType { + qualifier, + angle: None, + name, + args, + suffix, + array: ArrayType::None, + }) +} + +/// Parses `ISNULL` and `NOTNULL`, which render in their standard spelling. +fn parse_postfix_null<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + let negated = p.at_keyword("NOTNULL"); + p.advance(); + Ok(ExprKind::Is { + expr: Box::new(left), + test: IsTest::Null, + negated, + } + .into()) +} + +/// Parses `DISTINCT ON (...)` if present. +pub fn parse_distinct_on<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if !(p.at_keyword("DISTINCT") && next.is_word("ON")) { + return Ok(BuiltinSelect::default()); + } + p.advance(); + p.advance(); + p.expect_op("(")?; + let exprs = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op(")")?; + Ok(BuiltinSelect { + distinct_on: Some(exprs), + ..BuiltinSelect::default() + }) +} + +fn parse_interval_fields<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + use IntervalFields::*; + // Each leading unit, with the units it can run to. + type Range = (&'static str, IntervalFields); + let (ranges, plain): (&[Range], IntervalFields) = if p.eat_keyword("YEAR") { + (&[("MONTH", YearToMonth)], Year) + } else if p.eat_keyword("DAY") { + ( + &[ + ("HOUR", DayToHour), + ("MINUTE", DayToMinute), + ("SECOND", DayToSecond), + ], + Day, + ) + } else if p.eat_keyword("HOUR") { + (&[("MINUTE", HourToMinute), ("SECOND", HourToSecond)], Hour) + } else if p.eat_keyword("MINUTE") { + (&[("SECOND", MinuteToSecond)], Minute) + } else if p.eat_keyword("MONTH") { + return Ok(Some(Month)); + } else if p.eat_keyword("SECOND") { + return Ok(Some(Second)); + } else { + return Ok(None); + }; + if !p.eat_keyword("TO") { + return Ok(Some(plain)); + } + for (unit, fields) in ranges { + if p.eat_keyword(unit) { + return Ok(Some(*fields)); + } + } + Err(p.expected("a smaller interval unit")) +} + +/// Consumes `CONCURRENTLY` and `ASYNC`, the second of which can name an index. +pub fn parse_index_flags(p: &mut Parser<'_, D>) -> IndexFlags { + let concurrently = p.eat_keyword("CONCURRENTLY"); + let asynchronous = p.at_keyword("ASYNC") && !p.peek_nth(1).is_word("ON"); + if asynchronous { + p.advance(); + } + IndexFlags { + concurrently, + asynchronous, + } +} + +fn phrase_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, + phrase: &'static str, +) -> PResult> { + Ok(AlterTableOp::PhraseName { + phrase: phrase.into(), + name: p.parse_name_part()?, + }) +} + +fn expect_row_level_security(p: &mut Parser<'_, D>) -> PResult<()> { + ["ROW", "LEVEL", "SECURITY"] + .iter() + .try_for_each(|word| p.expect_keyword(word)) +} + +/// Parses what follows `ENABLE`. +fn parse_enable<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_keyword("ROW") { + expect_row_level_security(p)?; + return Ok(AlterTableOp::Phrase("ENABLE ROW LEVEL SECURITY".into())); + } + let always = p.eat_keyword("ALWAYS"); + let replica = !always && p.eat_keyword("REPLICA"); + let phrase = if p.eat_keyword("TRIGGER") { + match (always, replica) { + (true, _) => "ENABLE ALWAYS TRIGGER", + (_, true) => "ENABLE REPLICA TRIGGER", + _ => "ENABLE TRIGGER", + } + } else { + p.expect_keyword("RULE")?; + match (always, replica) { + (true, _) => "ENABLE ALWAYS RULE", + (_, true) => "ENABLE REPLICA RULE", + _ => "ENABLE RULE", + } + }; + phrase_name(p, phrase) +} + +/// Parses what follows `DISABLE`. +fn parse_disable<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_keyword("ROW") { + expect_row_level_security(p)?; + return Ok(AlterTableOp::Phrase("DISABLE ROW LEVEL SECURITY".into())); + } + if p.eat_keyword("TRIGGER") { + return phrase_name(p, "DISABLE TRIGGER"); + } + p.expect_keyword("RULE")?; + phrase_name(p, "DISABLE RULE") +} + +fn parse_replica_identity<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("IDENTITY")?; + if p.eat_keyword("USING") { + p.expect_keyword("INDEX")?; + return phrase_name(p, "REPLICA IDENTITY USING INDEX"); + } + if p.eat_keyword("DEFAULT") { + return Ok(AlterTableOp::Phrase("REPLICA IDENTITY DEFAULT".into())); + } + if p.eat_keyword("FULL") { + return Ok(AlterTableOp::Phrase("REPLICA IDENTITY FULL".into())); + } + p.expect_keyword("NOTHING")?; + Ok(AlterTableOp::Phrase("REPLICA IDENTITY NOTHING".into())) +} + +pub fn parse_alter_table_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if p.eat_keyword("ENABLE") { + return parse_enable(p); + } + if p.eat_keyword("DISABLE") { + return parse_disable(p); + } + if p.eat_keyword("FORCE") { + expect_row_level_security(p)?; + return Ok(AlterTableOp::Phrase("FORCE ROW LEVEL SECURITY".into())); + } + if p.at_keyword("NO") && next.is_word("FORCE") { + p.advance(); + p.advance(); + expect_row_level_security(p)?; + return Ok(AlterTableOp::Phrase("NO FORCE ROW LEVEL SECURITY".into())); + } + if p.eat_keyword("REPLICA") { + return parse_replica_identity(p); + } + if p.eat_keyword("VALIDATE") { + p.expect_keyword("CONSTRAINT")?; + return phrase_name(p, "VALIDATE CONSTRAINT"); + } + if p.eat_keyword("OWNER") { + p.expect_keyword("TO")?; + return phrase_name(p, "OWNER TO"); + } + if p.at_keyword("RENAME") && next.is_word("CONSTRAINT") { + p.advance(); + p.advance(); + let old = p.parse_ident()?; + p.expect_keyword("TO")?; + let new = p.parse_ident()?; + return Ok(AlterTableOp::RenameConstraint { old, new }); + } + if p.at_keyword("SET") && next.kind == TokenKind::Op && next.text == "(" { + p.advance(); + return grammar::parse_storage_parameter_list(p).map(AlterTableOp::SetOptions); + } + if p.at_keyword("SET") && (next.is_word("LOGGED") || next.is_word("UNLOGGED")) { + p.advance(); + let phrase = if p.eat_keyword("LOGGED") { + "SET LOGGED" + } else { + p.advance(); + "SET UNLOGGED" + }; + return Ok(AlterTableOp::Phrase(phrase.into())); + } + grammar::parse_alter_table_op(p) +} + +/// Statements only PostgreSQL has. +#[derive(Debug, Clone, PartialEq)] +pub enum PostgresStatement<'a> { + DropOperator { + if_exists: bool, + operators: Vec>, + behavior: Option, + }, + /// `DROP OPERATOR {CLASS | FAMILY}` + DropOperatorGroup { + family: bool, + if_exists: bool, + names: Vec>, + using: Ident<'a>, + behavior: Option, + }, + CreateOperator { + name: OperatorName<'a>, + definition: Vec>, + }, + CreateOperatorFamily { + name: ObjectName<'a>, + using: Ident<'a>, + }, + CreateOperatorClass(Box>), + AlterOperator { + name: OperatorName<'a>, + /// The left and right argument types. + types: Box<(DataType<'a>, DataType<'a>)>, + op: AlterOperatorOp<'a>, + }, + AlterOperatorClass { + family: bool, + name: ObjectName<'a>, + using: Ident<'a>, + op: AlterFamilyOp<'a>, + }, + CreateAggregate(Box>), + AlterAggregate(Box>), + CreateFunction(Box>), + /// The first field is `FUNCTION`, `PROCEDURE` or `ROUTINE`. + AlterFunction(Cow<'a, str>, Box>), + CreateRole(Box>), + AlterRole(Box>), + CreateExtension(Box>), + CreateDomain(Box>), + CreateType(Box>), + AlterType(Box>), + CreateCollation(Box>), + AlterCollation(Box>), + CreateTextSearch { + kind: TextSearchKind, + name: ObjectName<'a>, + definition: Vec>, + }, + AlterTextSearch { + kind: TextSearchKind, + name: ObjectName<'a>, + op: AlterTextSearchOp<'a>, + }, + CreateForeignDataWrapper { + name: Ident<'a>, + clauses: Vec>, + }, + CreateServer(Box>), + CreateUserMapping(Box>), + AlterDefaultPrivileges(Box>), + CreateTrigger(Box>), + CreateRule(Box>), + CreateTable(Box>), + /// `ALTER {MATERIALIZED VIEW | FOREIGN TABLE} ...` + AlterRelation { + keyword: Cow<'a, str>, + alter: Box>, + }, + AlterSchema { + name: ObjectName<'a>, + action: ObjectAction<'a>, + }, + /// `RETURN expr`, inside `BEGIN ATOMIC`. + Return(Box>), + Copy(Box>), + Truncate(Box>), + Insert(Box>), + Declare(Box>), + Fetch(Box>), + Lock(Box>), + Prepare(Box>), + Execute(Box>), + Deallocate { + prepare: bool, + /// `None` for `DEALLOCATE ALL`. + name: Option>, + }, + Do(Vec>), + Analyze { + verbose: bool, + tables: Vec>, + }, + Notify { + channel: Ident<'a>, + payload: Option>, + }, + Listen(Ident<'a>), + /// `None` for `UNLISTEN *`. + Unlisten(Option>), + /// `DISCARD ALL`, `PLANS`, `SEQUENCES`, `TEMP` or `TEMPORARY`. + Discard(Cow<'a, str>), + /// `RESET name`, `RESET ALL` or `RESET SESSION AUTHORIZATION`. + Reset(ResetTarget<'a>), + /// `CLOSE name`, or `CLOSE ALL` for `None`. + Close(Option>), + /// `LOAD 'file'` + Load(StringLiteral<'a>), + CreatePolicy(Box>), + AlterPolicy(Box>), +} + +/// What `RESET` applies to. +#[derive(Debug, Clone, PartialEq)] +pub enum ResetTarget<'a> { + All, + SessionAuthorization, + Name(ObjectName<'a>), +} + +/// `CREATE POLICY name ON table [AS kind] [FOR command] [TO roles] [USING (e)] [WITH CHECK (e)]` +#[derive(Debug, Clone, PartialEq)] +pub struct CreatePolicy<'a> { + pub name: Ident<'a>, + pub table: ObjectName<'a>, + pub kind: Option>, + pub command: Option>, + pub to: Vec>, + pub using: Option>, + pub with_check: Option>, +} + +/// `ALTER POLICY name ON table ...` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterPolicy<'a> { + pub name: Ident<'a>, + pub table: ObjectName<'a>, + pub rename_to: Option>, + pub to: Vec>, + pub using: Option>, + pub with_check: Option>, +} + +/// `[schema.]operator (left, right)` +#[derive(Debug, Clone, PartialEq)] +pub struct OperatorSignature<'a> { + pub schema: Vec>, + pub operator: Cow<'a, str>, + pub left: DataType<'a>, + pub right: DataType<'a>, +} + +/// `INSERT` with clauses the core does not have. +#[derive(Debug, Clone, PartialEq)] +pub struct PostgresInsert<'a> { + pub insert: Insert<'a, Builtin>, + /// The table's alias: `INSERT INTO t AS x`. + pub alias: Option>, + /// `OVERRIDING {SYSTEM | USER} VALUE`, holding the middle word. + pub overriding: Option>, + pub on_conflict: Option>, +} + +/// `ON CONFLICT [target] {DO NOTHING | DO UPDATE ...}` +#[derive(Debug, Clone, PartialEq)] +pub struct OnConflict<'a> { + pub target: OnConflictTarget<'a>, + pub predicate: Option>, + /// The `SET` assignments, or `None` for `DO NOTHING`. + pub update: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum OnConflictTarget<'a> { + None, + Columns(Vec>), + /// `ON CONSTRAINT name` + Constraint(Ident<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct OnConflictUpdate<'a> { + pub assignments: Vec>, + pub selection: Option>, +} + +/// Expressions only PostgreSQL has. +#[derive(Debug, Clone, PartialEq)] +pub enum PostgresExpr<'a> { + /// A prefix operator not in the core, written with its operator text. + Prefix { + op: Cow<'a, str>, + expr: Box>, + }, + /// `expr !` + Postfix { + expr: Box>, + op: Cow<'a, str>, + }, + /// A binary operator not in the core. + Binary(Box>), + /// `ARRAY(subquery)` + ArraySubquery(Box>), + /// `XMLFOREST(a AS x, b)` + XmlForest(Vec<(Expr<'a, Builtin>, Option>)>), + /// `XMLPARSE(CONTENT expr)` or `XMLPARSE(DOCUMENT expr)` + XmlParse { + document: bool, + value: Box>, + }, + /// `JSON_OBJECT(key VALUE value, ...)`, with `:` for `VALUE` if `colon`. + JsonObject(Box>), +} + +/// `left OPERATOR(schema.op) right`, or a custom operator written directly. +#[derive(Debug, Clone, PartialEq)] +pub struct PostgresBinary<'a> { + pub left: Expr<'a, Builtin>, + /// `Some` if written with `OPERATOR(...)`. + pub qualified: Option>, + pub op: Cow<'a, str>, + pub right: Expr<'a, Builtin>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct JsonObjectCall<'a> { + pub entries: Vec<(Expr<'a, Builtin>, bool, Expr<'a, Builtin>)>, + /// `Some(true)` for `NULL ON NULL`, `Some(false)` for `ABSENT ON NULL`. + pub null_on_null: Option, + pub returning: Option>, +} + +/// A table with `ONLY` before it, or `*` after it. +#[derive(Debug, Clone, PartialEq)] +pub struct InheritedTable<'a> { + pub only: bool, + /// True if written `ONLY (name)`. + pub parenthesized: bool, + pub name: ObjectName<'a>, + pub star: bool, +} + +/// PostgreSQL's table factors. +#[derive(Debug, Clone, PartialEq)] +pub enum PostgresTableFactor<'a> { + Inherited(InheritedTable<'a>), +} + +/// `USING (columns) AS alias` +#[derive(Debug, Clone, PartialEq)] +pub struct PostgresUsingConstraint<'a> { + pub columns: Vec>, + pub alias: Ident<'a>, +} + +impl fmt::Display for PostgresTableFactor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PostgresTableFactor::Inherited(table) => { + if table.only { + f.write_str("ONLY ")?; + } + if table.parenthesized { + write!(f, "({})", table.name)?; + } else { + table.name.fmt(f)?; + } + if table.star { + f.write_str(" *")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for PostgresUsingConstraint<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "USING({}) AS {}", comma(&self.columns), self.alias) + } +} + +fn parse_operator_signature<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = ddl::parse_operator_name(p)?; + p.expect_op("(")?; + let left = D::parse_data_type(p)?; + p.expect_op(",")?; + let right = D::parse_data_type(p)?; + p.expect_op(")")?; + Ok(OperatorSignature { + schema: name.schema, + operator: name.operator, + left, + right, + }) +} + +fn parse_drop_operator<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + if p.at_keyword("CLASS") || p.at_keyword("FAMILY") { + return ddl::parse_drop_operator_group(p); + } + let if_exists = p.at_keyword("IF"); + if if_exists { + p.advance(); + p.expect_keyword("EXISTS")?; + } + let operators = p.parse_comma_separated(parse_operator_signature)?; + let behavior = if p.eat_keyword("CASCADE") { + Some(DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(DropBehavior::Restrict) + } else { + None + }; + Ok(PostgresStatement::DropOperator { + if_exists, + operators, + behavior, + }) +} + +impl fmt::Display for PostgresStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PostgresStatement::DropOperator { + if_exists, + operators, + behavior, + } => { + f.write_str("DROP OPERATOR ")?; + if *if_exists { + f.write_str("IF EXISTS ")?; + } + for (i, operator) in operators.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + for part in &operator.schema { + write!(f, "{part}.")?; + } + write!( + f, + "{} ({}, {})", + operator.operator, operator.left, operator.right + )?; + } + ddl::write_behavior(f, *behavior) + } + PostgresStatement::DropOperatorGroup { + family, + if_exists, + names, + using, + behavior, + } => { + write!( + f, + "DROP OPERATOR {}", + if *family { "FAMILY" } else { "CLASS" } + )?; + if *if_exists { + f.write_str(" IF EXISTS")?; + } + write!(f, " {} USING {using}", comma(names))?; + ddl::write_behavior(f, *behavior) + } + PostgresStatement::CreateOperator { name, definition } => { + write!(f, "CREATE OPERATOR {name} ({})", comma(definition)) + } + PostgresStatement::CreateOperatorFamily { name, using } => { + write!(f, "CREATE OPERATOR FAMILY {name} USING {using}") + } + PostgresStatement::CreateOperatorClass(class) => { + write!(f, "CREATE OPERATOR CLASS {} ", class.name)?; + if class.default { + f.write_str("DEFAULT ")?; + } + write!(f, "FOR TYPE {} USING {}", class.for_type, class.using)?; + if let Some(family) = &class.family { + write!(f, " FAMILY {family}")?; + } + write!(f, " AS {}", comma(&class.items)) + } + PostgresStatement::AlterOperator { name, types, op } => { + let (left, right) = &**types; + write!(f, "ALTER OPERATOR {name} ({left}, {right}) {op}") + } + PostgresStatement::AlterOperatorClass { + family, + name, + using, + op, + } => write!( + f, + "ALTER OPERATOR {} {name} USING {using} {op}", + if *family { "FAMILY" } else { "CLASS" } + ), + PostgresStatement::CreateAggregate(create) => create.fmt(f), + PostgresStatement::AlterAggregate(alter) => { + write!( + f, + "ALTER AGGREGATE {}({}) {}", + alter.name, alter.args, alter.action + ) + } + PostgresStatement::CreateFunction(create) => create.fmt(f), + PostgresStatement::AlterFunction(keyword, alter) => { + write!(f, "ALTER {keyword} {alter}") + } + PostgresStatement::CreateRole(create) => create.fmt(f), + PostgresStatement::AlterRole(alter) => alter.fmt(f), + PostgresStatement::CreateExtension(create) => create.fmt(f), + PostgresStatement::CreateDomain(create) => create.fmt(f), + PostgresStatement::CreateType(create) => create.fmt(f), + PostgresStatement::AlterType(alter) => alter.fmt(f), + PostgresStatement::CreateCollation(create) => create.fmt(f), + PostgresStatement::AlterCollation(alter) => alter.fmt(f), + PostgresStatement::CreateTextSearch { + kind, + name, + definition, + } => write!( + f, + "CREATE TEXT SEARCH {} {name} ({})", + kind.keyword(), + comma(definition) + ), + PostgresStatement::AlterTextSearch { kind, name, op } => { + write!(f, "ALTER TEXT SEARCH {} {name} ", kind.keyword())?; + match op { + AlterTextSearchOp::Options(options) => write!(f, "({})", comma(options)), + AlterTextSearchOp::Action(action) => action.fmt(f), + } + } + PostgresStatement::CreateForeignDataWrapper { name, clauses } => { + write!(f, "CREATE FOREIGN DATA WRAPPER {name}")?; + for clause in clauses { + write!(f, " {clause}")?; + } + Ok(()) + } + PostgresStatement::CreateServer(create) => create.fmt(f), + PostgresStatement::CreateUserMapping(create) => create.fmt(f), + PostgresStatement::AlterDefaultPrivileges(alter) => alter.fmt(f), + PostgresStatement::CreateTrigger(create) => create.fmt(f), + PostgresStatement::CreateRule(create) => create.fmt(f), + PostgresStatement::CreateTable(create) => create.fmt(f), + PostgresStatement::AlterRelation { keyword, alter } => { + write!(f, "ALTER {keyword} ")?; + if alter.if_exists { + f.write_str("IF EXISTS ")?; + } + if alter.only { + f.write_str("ONLY ")?; + } + write!(f, "{} {}", alter.name, comma(&alter.operations)) + } + PostgresStatement::AlterSchema { name, action } => { + write!(f, "ALTER SCHEMA {name} {action}") + } + PostgresStatement::Return(value) => write!(f, "RETURN {value}"), + PostgresStatement::Copy(copy) => copy.fmt(f), + PostgresStatement::Truncate(truncate) => truncate.fmt(f), + PostgresStatement::Insert(insert) => insert.fmt(f), + PostgresStatement::Declare(declare) => declare.fmt(f), + PostgresStatement::Fetch(fetch) => fetch.fmt(f), + PostgresStatement::Lock(lock) => lock.fmt(f), + PostgresStatement::Prepare(prepare) => prepare.fmt(f), + PostgresStatement::Execute(execute) => execute.fmt(f), + PostgresStatement::Deallocate { prepare, name } => { + f.write_str("DEALLOCATE ")?; + if *prepare { + f.write_str("PREPARE ")?; + } + match name { + Some(name) => name.fmt(f), + None => f.write_str("ALL"), + } + } + PostgresStatement::Do(items) => { + f.write_str("DO")?; + for item in items { + write!(f, " {item}")?; + } + Ok(()) + } + PostgresStatement::Analyze { verbose, tables } => { + f.write_str("ANALYZE")?; + if *verbose { + f.write_str(" VERBOSE")?; + } + if !tables.is_empty() { + write!(f, " {}", comma(tables))?; + } + Ok(()) + } + PostgresStatement::Notify { channel, payload } => { + write!(f, "NOTIFY {channel}")?; + if let Some(payload) = payload { + write!(f, ", {}", payload)?; + } + Ok(()) + } + PostgresStatement::Discard(target) => write!(f, "DISCARD {target}"), + PostgresStatement::Reset(ResetTarget::All) => f.write_str("RESET ALL"), + PostgresStatement::Reset(ResetTarget::SessionAuthorization) => { + f.write_str("RESET SESSION AUTHORIZATION") + } + PostgresStatement::Reset(ResetTarget::Name(name)) => write!(f, "RESET {name}"), + PostgresStatement::Close(None) => f.write_str("CLOSE ALL"), + PostgresStatement::Close(Some(name)) => write!(f, "CLOSE {name}"), + PostgresStatement::Load(file) => write!(f, "LOAD {}", file), + PostgresStatement::CreatePolicy(policy) => { + write!(f, "CREATE POLICY {} ON {}", policy.name, policy.table)?; + if let Some(ref kind) = policy.kind { + write!(f, " AS {kind}")?; + } + if let Some(ref command) = policy.command { + write!(f, " FOR {command}")?; + } + if !policy.to.is_empty() { + write!(f, " TO {}", comma(&policy.to))?; + } + if let Some(using) = &policy.using { + write!(f, " USING ({using})")?; + } + if let Some(check) = &policy.with_check { + write!(f, " WITH CHECK ({check})")?; + } + Ok(()) + } + PostgresStatement::AlterPolicy(policy) => { + write!(f, "ALTER POLICY {} ON {}", policy.name, policy.table)?; + if let Some(new_name) = &policy.rename_to { + return write!(f, " RENAME TO {new_name}"); + } + if !policy.to.is_empty() { + write!(f, " TO {}", comma(&policy.to))?; + } + if let Some(using) = &policy.using { + write!(f, " USING ({using})")?; + } + if let Some(check) = &policy.with_check { + write!(f, " WITH CHECK ({check})")?; + } + Ok(()) + } + PostgresStatement::Listen(channel) => write!(f, "LISTEN {channel}"), + PostgresStatement::Unlisten(Some(channel)) => write!(f, "UNLISTEN {channel}"), + PostgresStatement::Unlisten(None) => f.write_str("UNLISTEN *"), + } + } +} + +impl fmt::Display for PostgresInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let insert = &self.insert; + write!(f, "INSERT {}INTO {}", insert.modifiers, insert.table)?; + if let Some(alias) = &self.alias { + write!(f, " AS {alias}")?; + } + if !insert.columns.is_empty() { + write!(f, " ({})", comma(&insert.columns))?; + } + if let Some(ref word) = self.overriding { + write!(f, " OVERRIDING {word} VALUE")?; + } + write_insert_source(f, &insert.source, !insert.columns.is_empty())?; + if let Some(on_conflict) = &self.on_conflict { + write!(f, " {on_conflict}")?; + } + write_list_clause(f, "RETURNING", &insert.returning) + } +} + +impl fmt::Display for OnConflict<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ON CONFLICT")?; + match &self.target { + OnConflictTarget::None => {} + OnConflictTarget::Columns(columns) => write!(f, "({})", comma(columns))?, + OnConflictTarget::Constraint(name) => write!(f, " ON CONSTRAINT {name}")?, + } + if let Some(predicate) = &self.predicate { + write!(f, " WHERE {predicate}")?; + } + match &self.update { + None => f.write_str(" DO NOTHING"), + Some(update) => { + write!(f, " DO UPDATE SET {}", comma(&update.assignments))?; + if let Some(selection) = &update.selection { + write!(f, " WHERE {selection}")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for PostgresExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PostgresExpr::Prefix { op, expr } if op == "!!" => write!(f, "!!{expr}"), + PostgresExpr::Prefix { op, expr } => write!(f, "{op} {expr}"), + PostgresExpr::Postfix { expr, op } => { + let spaced = matches!( + &expr.kind, + ExprKind::Ext(BuiltinExpr::Postgres(PostgresExpr::Postfix { .. })) + ); + write!(f, "{expr}{}{op}", if spaced { " " } else { "" }) + } + PostgresExpr::Binary(binary) => { + let PostgresBinary { + left, + qualified, + op, + right, + } = &**binary; + match qualified { + Some(name) => write!(f, "{left} OPERATOR({name}) {right}"), + None => write!(f, "{left} {op} {right}"), + } + } + PostgresExpr::ArraySubquery(query) => write!(f, "ARRAY({query})"), + PostgresExpr::XmlForest(items) => { + f.write_str("XMLFOREST(")?; + for (i, (expr, name)) in items.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + expr.fmt(f)?; + if let Some(name) = name { + write!(f, " AS {name}")?; + } + } + f.write_str(")") + } + PostgresExpr::XmlParse { document, value } => { + write!( + f, + "XMLPARSE({} {value})", + if *document { "DOCUMENT" } else { "CONTENT" } + ) + } + PostgresExpr::JsonObject(call) => { + f.write_str("JSON_OBJECT(")?; + let mut sep = ""; + for (key, colon, value) in &call.entries { + write!( + f, + "{sep}{key}{}{value}", + if *colon { " : " } else { " VALUE " } + )?; + sep = ", "; + } + let mut gap = if call.entries.is_empty() { "" } else { " " }; + match call.null_on_null { + Some(true) => { + write!(f, "{gap}NULL ON NULL")?; + gap = " "; + } + Some(false) => { + write!(f, "{gap}ABSENT ON NULL")?; + gap = " "; + } + None => {} + } + if let Some(returning) = &call.returning { + write!(f, "{gap}RETURNING {returning}")?; + } + f.write_str(")") + } + } + } +} + +#[inline] +pub fn is_reserved(word: &str) -> bool { + ["RETURNING", "ONLY", "NOTNULL", "ISNULL"] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved(word) +} + +pub fn parse_returning<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("RETURNING") { + p.parse_comma_separated(Parser::parse_select_item) + } else { + Ok(Vec::new()) + } +} + +/// The dispatch shared with [`super::redshift`]: what both dialects' `COPY` +/// and comments accept. +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if p.at_keyword("DROP") && next.is_word("OPERATOR") { + let drop = parse_drop_operator(p)?; + return Ok(statement(drop)); + } + if p.at_keyword("COMMENT") { + return grammar::parse_comment_on_with(p, &[&["FOREIGN", "TABLE"]]) + .map(|c| StatementKind::Comment(Box::new(c)).into()); + } + grammar::parse_statement(p) +} + +/// Parses a statement with PostgreSQL's whole statement set. +pub fn parse_full_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("ALTER") { + let next = p.peek_nth(1); + if next.is_word("INDEX") { + return grammar::parse_alter_index_rename(p); + } + if next.is_word("MATERIALIZED") && p.peek_nth(2).is_word("VIEW") { + p.advance(); + let alter = table::parse_alter_relation(p, "MATERIALIZED VIEW")?; + return Ok(statement(alter)); + } + if next.is_word("FOREIGN") && p.peek_nth(2).is_word("TABLE") { + p.advance(); + let alter = table::parse_alter_relation(p, "FOREIGN TABLE")?; + return Ok(statement(alter)); + } + if next.is_word("SCHEMA") { + p.advance(); + p.advance(); + let name = grammar::parse_object_name(p)?; + if p.at_keyword("RENAME") || p.at_keyword("OWNER") { + let action = ddl::parse_rename_or_owner(p)?; + return Ok(statement(PostgresStatement::AlterSchema { name, action })); + } + return Err(p.expected("RENAME TO or OWNER TO")); + } + if !next.is_word("TABLE") { + p.advance(); + if let Some(alter) = ddl::parse_alter_object(p)? { + return Ok(statement(alter)); + } + return Err(p.expected("TABLE")); + } + } + if p.at_keyword("ABORT") { + return grammar::parse_abort(p); + } + if let Some(parsed) = utility::parse_utility(p, utility::LEGACY_OPTIONS)? { + return Ok(parsed); + } + parse_statement(p) +} + +/// Parses `CREATE` with everything PostgreSQL adds. +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let or_replace = p.peek_nth(1).is_word("OR") && p.peek_nth(2).is_word("REPLACE"); + let n = if or_replace { 3 } else { 1 }; + let is_foreign_table = p.peek_nth(n).is_word("FOREIGN") && p.peek_nth(n + 1).is_word("TABLE"); + if table::at_create_table_at(p, n) || is_foreign_table { + p.advance(); + if or_replace { + p.advance(); + p.advance(); + } + return table::parse_create_table_statement(p, or_replace); + } + let word = p.peek_nth(n); + let next = p.peek_nth(n + 1); + let is_object = !or_replace + && ([ + "OPERATOR", + "EXTENSION", + "DOMAIN", + "TYPE", + "COLLATION", + "SERVER", + "ROLE", + "GROUP", + "POLICY", + ] + .iter() + .any(|kind| word.is_word(kind)) + || word.is_word("USER") + || (word.is_word("TEXT") && next.is_word("SEARCH")) + || (word.is_word("FOREIGN") && next.is_word("DATA"))); + let is_replaceable = ["AGGREGATE", "FUNCTION", "RULE", "TRIGGER"] + .iter() + .any(|kind| word.is_word(kind)) + || (word.is_word("CONSTRAINT") && next.is_word("TRIGGER")); + if is_object || is_replaceable { + p.advance(); + if or_replace { + p.advance(); + p.advance(); + } + if let Some(parsed) = ddl::parse_create_object(p, or_replace)? { + return Ok(statement(parsed)); + } + return Err(p.expected("an object type after CREATE")); + } + grammar::parse_create(p) +} + +/// Parses a table and its alias, whose columns can carry types. +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let factor = D::parse_table_factor(p)?; + let explicit = p.eat_keyword("AS"); + if !explicit && !p.at_implicit_alias() { + return Ok(TableRef { + factor, + alias: None, + span: Span::default(), + }); + } + let name = p.parse_ident()?; + let mut columns = Vec::new(); + let mut column_types = Vec::new(); + if p.eat_op("(") { + let items = p.parse_comma_separated(|p| { + let column = p.parse_ident()?; + let data_type = if p.at_op(",") || p.at_op(")") { + None + } else { + Some(D::parse_data_type(p)?) + }; + Ok((column, data_type)) + })?; + p.expect_op(")")?; + for (column, data_type) in items { + columns.push(column); + if let Some(data_type) = data_type { + column_types.push(data_type); + } + } + if !column_types.is_empty() && column_types.len() != columns.len() { + return Err(p.expected("a type for each column")); + } + } + Ok(TableRef { + factor, + alias: Some(TableAlias { + name, + explicit, + columns, + column_types, + }), + span: Span::default(), + }) +} + +/// Parses an `ORDER BY` item, which can name an operator with `USING`. +pub fn parse_order_by_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let expr = p.parse_expr()?; + let using = if p.eat_keyword("USING") { + Some(Box::new(if p.at_keyword("OPERATOR") { + p.advance(); + p.expect_op("(")?; + let name = ddl::parse_operator_name(p)?; + p.expect_op(")")?; + name + } else { + ddl::parse_operator_name(p)? + })) + } else { + None + }; + let (asc, nulls_first) = grammar::parse_order_by_modifiers(p)?; + Ok(OrderByItem { + expr, + asc, + nulls_first, + using, + ext: Default::default(), + }) +} + +/// Parses `WITH (name = value, name)`, in which a value is a simple one: a +/// literal or a word, unlike an expression such as a function call. +pub fn parse_storage_parameters<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let parameters = grammar::parse_index_storage_parameters(p)?; + let plain = parameters.iter().all(|(_, value)| { + matches!( + value.as_ref().map(|value| &value.kind), + None | Some( + ExprKind::Literal(_) + | ExprKind::Ident(_) + | ExprKind::Unary { .. } + | ExprKind::TypedString(_) + ) + ) + }); + if !plain { + return Err(p.expected("a literal or a word as the value of a storage parameter")); + } + Ok(parameters) +} + +/// Parses `CREATE [OR REPLACE] [TEMP] [MATERIALIZED] VIEW`, adding `WITH (...)`. +pub fn parse_create_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + let materialized = p.eat_keyword("MATERIALIZED"); + p.expect_keyword("VIEW")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let with = parse_storage_parameters(p)?; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + Ok(CreateView { + or_replace: flags.or_replace, + temporary: flags.temporary, + materialized, + if_not_exists, + name, + columns, + with, + query, + no_schema_binding: false, + }) +} + +pub fn parse_alter_type_using<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("USING") { + p.parse_expr().map(Some) + } else { + Ok(None) + } +} + +/// Parses a column option, adding `CONSTRAINT name`, `NULLS [NOT] DISTINCT` +/// and `OPTIONS (...)`. +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.at_keyword("NULLS") && (p.peek_nth(1).is_word("DISTINCT") || p.peek_nth(1).is_word("NOT")) + { + p.advance(); + let not = p.eat_keyword("NOT"); + p.expect_keyword("DISTINCT")?; + return Ok(Some(ColumnOption::NullsDistinct(!not))); + } + if p.at_keyword("OPTIONS") && p.peek_nth(1).is_op("(") { + return ddl::parse_generic_options(p).map(|o| Some(ColumnOption::GenericOptions(o))); + } + if p.at_keyword("CONSTRAINT") { + p.advance(); + let name = p.parse_ident()?; + let Some(option) = parse_column_option(p)? else { + return Err(p.expected("a column constraint")); + }; + return Ok(Some(ColumnOption::Named { + name, + option: Box::new(option), + })); + } + let option = grammar::parse_column_option(p)?; + if let Some(ColumnOption::Generated(generated)) = &option + && matches!( + generated.kind, + GeneratedKind::Expr { storage, .. } if storage != Some(GeneratedStorage::Stored) + ) + { + return Err(p.expected("STORED")); + } + Ok(option) +} + +/// Parses `DROP`, rejecting `CASCADE` and `RESTRICT` on roles and groups. +pub fn parse_drop<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let drop = grammar::parse_drop(p)?; + if drop.behavior.is_some() && drop.object_type == ObjectType::Named("GROUP".into()) { + return Err(p.expected("end of statement after the names")); + } + Ok(drop) +} + +pub fn parse_set<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if grammar::at_set_names(p) { + return grammar::parse_set_names(p); + } + grammar::parse_set(p) +} + +pub fn parse_drop_object_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option> { + if p.at_keyword("FOREIGN") && p.peek_nth(1).is_word("TABLE") { + p.advance(); + p.advance(); + return Some(ObjectType::Named("FOREIGN TABLE".into())); + } + grammar::eat_drop_object_type( + p, + &[ + "EXTENSION", + "TYPE", + "COLLATION", + "DOMAIN", + "POLICY", + "TRIGGER", + "GROUP", + ], + ) +} + +/// True if a word can start a typed literal in `parse_prefix`: these reserved +/// words are also type or function names in PostgreSQL. +fn is_type_func_keyword(word: &str) -> bool { + [ + "LEFT", "RIGHT", "FULL", "INNER", "CROSS", "NATURAL", "OUTER", "LIKE", "ILIKE", + ] + .iter() + .any(|kw| kw.eq_ignore_ascii_case(word)) +} + +/// True at `type 'text'`, where `type` can be qualified. +fn at_typed_string<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let mut n = 0; + loop { + let name = p.peek_nth(n); + if !matches!(name.kind, TokenKind::Word | TokenKind::QuotedIdent) { + return false; + } + let after = p.peek_nth(n + 1); + if after.is_op(".") { + n += 2; + continue; + } + if !matches!(after.kind, TokenKind::String | TokenKind::DollarString) { + return false; + } + break; + } + let first = p.peek(); + match first.kind { + TokenKind::QuotedIdent => first.text.len() > 2, + TokenKind::Word => { + !grammar::is_reserved(first.text) && !is_core_prefix_word(first.text) + || is_type_func_keyword(first.text) + } + _ => false, + } +} + +/// Words the core reads as the start of an expression, not as a type. +fn is_core_prefix_word(word: &str) -> bool { + [ + "COALESCE", + "GREATEST", + "LEAST", + "NULLIF", + "ROW", + "POSITION", + "SUBSTRING", + "OVERLAY", + "EXTRACT", + "TRIM", + "INTERVAL", + "DATE", + "TIME", + "TIMESTAMP", + "TIMESTAMPTZ", + "DATETIME", + "NOT", + "NULL", + "TRUE", + "FALSE", + "CASE", + "CAST", + "TRY_CAST", + "EXISTS", + "ARRAY", + ] + .iter() + .any(|kw| kw.eq_ignore_ascii_case(word)) +} + +fn parse_typed_string<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let mut qualifier = Vec::new(); + let mut name = p.parse_name_part()?; + while p.eat_op(".") { + qualifier.push(name); + name = p.parse_name_part()?; + } + let token = p.advance(); + let value = if token.kind == TokenKind::DollarString { + let text = token.text.trim_start_matches(|c| c != '$'); + let body = &text[1..]; + let tag_len = body.find('$').unwrap_or(0); + let text = &body[tag_len + 1..body.len() - tag_len - 2]; + crate::ast::StringLiteral { + text: text.into(), + quote: '$', + backslash_escapes: false, + national: false, + prefix: StringPrefix::None, + triple: false, + } + } else { + D::string_literal(token) + }; + Ok(ExprKind::TypedString(Box::new(TypedString { + ty: DataType { + qualifier, + angle: None, + name, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: ArrayType::None, + }, + value, + })) + .into()) +} + +/// Parses a prefix: PostgreSQL's prefix operators and typed strings, and +/// reads `0x1F` as the integer it is here rather than a hex string. +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::Op && is_prefix_operator(token.text) { + p.advance(); + let expr = p.parse_expr_bp(prec::UNARY)?; + return Ok(ExprKind::Ext(BuiltinExpr::Postgres(PostgresExpr::Prefix { + op: token.text.into(), + expr: Box::new(expr), + })) + .into()); + } + if token.is_op("-") + && is_prefix_operator(p.peek_nth(1).text) + && p.peek_nth(1).kind == TokenKind::Op + { + p.advance(); + let expr = p.parse_expr_bp(prec::UNARY)?; + return Ok(ExprKind::Ext(BuiltinExpr::Postgres(PostgresExpr::Prefix { + op: "-".into(), + expr: Box::new(expr), + })) + .into()); + } + if token.is_word("TRIM") && p.peek_nth(1).is_op("(") && p.peek_nth(2).is_word("FROM") { + p.advance(); + p.advance(); + p.advance(); + let expr = p.parse_expr()?; + p.expect_op(")")?; + return Ok(ExprKind::Special(Box::new(SpecialExpr::Trim { + side: None, + what: None, + expr, + })) + .into()); + } + if matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) && at_typed_string(p) { + return parse_typed_string(p); + } + grammar::parse_prefix(p) +} + +/// True for an operator that can start an expression. +fn is_prefix_operator(text: &str) -> bool { + matches!(text, "~" | "@" | "#" | "|/" | "||/" | "!!") +} + +/// Parses a call, reading the forms with their own syntax. +pub fn parse_function_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + if let [only] = name.parts.as_slice() + && only.quote.is_none() + && let Some(expr) = parse_special_call(p, only.text.clone())? + { + return Ok(expr); + } + grammar::parse_function_call(p, name) +} + +fn parse_special_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Cow<'a, str>, +) -> PResult>> { + let eq = |word: &str| name.eq_ignore_ascii_case(word); + let ext = |expr| ExprKind::Ext(BuiltinExpr::Postgres(expr)).into(); + if eq("ARRAY") && (p.peek_nth(1).is_word("SELECT") || p.peek_nth(1).is_word("WITH")) { + p.advance(); + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + return Ok(Some(ext(PostgresExpr::ArraySubquery(Box::new(query))))); + } + if eq("XMLPARSE") && (p.peek_nth(1).is_word("CONTENT") || p.peek_nth(1).is_word("DOCUMENT")) { + let document = p.peek_nth(1).is_word("DOCUMENT"); + p.advance(); + p.advance(); + let value = Box::new(p.parse_expr()?); + p.expect_op(")")?; + return Ok(Some(ext(PostgresExpr::XmlParse { document, value }))); + } + if eq("XMLFOREST") { + p.advance(); + let items = p.parse_comma_separated(|p| { + let expr = p.parse_expr()?; + let name = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + Ok((expr, name)) + })?; + p.expect_op(")")?; + return Ok(Some(ext(PostgresExpr::XmlForest(items)))); + } + if eq("JSON_OBJECT") && at_json_object_syntax(p) { + return parse_json_object(p) + .map(|call| Some(ext(PostgresExpr::JsonObject(Box::new(call))))); + } + Ok(None) +} + +/// True if the `JSON_OBJECT` call at `(` uses `key VALUE value`, `key : value` +/// or ends with `RETURNING` or `... ON NULL`, rather than `key, value` pairs. +fn at_json_object_syntax(p: &Parser<'_, D>) -> bool { + let mut depth = 0usize; + let mut n = 0; + loop { + let token = p.peek_nth(n); + n += 1; + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + depth -= 1; + if depth == 0 { + return false; + } + } + TokenKind::Op if depth == 1 && token.text == ":" => return true, + TokenKind::Word + if depth == 1 + && (token.is_word("VALUE") + || token.is_word("RETURNING") + || (token.is_word("NULL") && p.peek_nth(n).is_word("ON")) + || token.is_word("ABSENT")) => + { + return true; + } + _ => {} + } + } +} + +fn parse_json_object<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let mut entries = Vec::new(); + if !p.at_keyword("RETURNING") && !p.at_keyword("NULL") && !p.at_keyword("ABSENT") { + loop { + let key = p.parse_expr()?; + let colon = if p.eat_op(":") { + true + } else { + p.expect_keyword("VALUE")?; + false + }; + let value = p.parse_expr()?; + entries.push((key, colon, value)); + if !p.eat_op(",") { + break; + } + } + } + let null_on_null = if p.at_keyword("NULL") { + p.advance(); + p.expect_keyword("ON")?; + p.expect_keyword("NULL")?; + Some(true) + } else if p.at_keyword("ABSENT") { + p.advance(); + p.expect_keyword("ON")?; + p.expect_keyword("NULL")?; + Some(false) + } else { + None + }; + let returning = if p.eat_keyword("RETURNING") { + Some(D::parse_data_type(p)?) + } else { + None + }; + p.expect_op(")")?; + Ok(JsonObjectCall { + entries, + null_on_null, + returning, + }) +} + +/// Parses one argument of a call, adding `name := value`. +pub fn parse_function_arg<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if matches!(p.peek().kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(1).is_op(":=") + { + let name = p.parse_name_part()?; + p.advance(); + let value = p.parse_expr()?; + return Ok(FunctionArg::NamedWith { + name, + operator: ":=".into(), + value, + }); + } + grammar::parse_function_arg(p) +} + +/// Lexes PostgreSQL's prefixed strings, numbers and operators. +#[inline] +pub fn lex_postgres_token(rest: &str) -> Option { + if let Some(result) = lex_prefixed_string(rest, true) { + return Some(result); + } + if let Some(result) = lex_national_string(rest) { + return Some(result); + } + if let Some(result) = lex_postgres_number(rest) { + return Some(result); + } + if let Some(result) = lex_named_arg_or_colon(rest) { + return Some(result); + } + if let Some(result) = lex_custom_operator(rest) { + return Some(result); + } + lex_token(rest) +} + +/// Lexes `N'text'`, in which a backslash has no special meaning. +fn lex_national_string(rest: &str) -> Option { + if !matches!(rest.as_bytes(), [b'n' | b'N', b'\'', ..]) { + return None; + } + Some(quoted(&rest[1..], TokenKind::String).map(|string| Lexeme { + kind: TokenKind::String, + len: string.len + 1, + })) +} + +/// Inside a subscript, `:` splits slice bounds even directly before a word. +pub fn lex_slice_colon(prev: Option>, rest: &str) -> Option { + let bytes = rest.as_bytes(); + let starts_bound = bytes[0] == b':' + && bytes + .get(1) + .is_some_and(|&b| b.is_ascii_alphabetic() || b == b'_'); + let after_bound = prev.is_some_and(|token| { + matches!( + token.kind, + TokenKind::Number | TokenKind::Word | TokenKind::QuotedIdent + ) || token.is_op(")") + || token.is_op("]") + || token.is_op("[") + }); + (starts_bound && after_bound).then_some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })) +} + +fn lex_named_arg_or_colon(rest: &str) -> Option { + let bytes = rest.as_bytes(); + if bytes[0] != b':' { + return None; + } + if bytes.get(1) == Some(&b'=') { + return Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 2, + })); + } + if matches!(bytes.get(1), Some(b':')) { + return None; + } + // `:name` remains a placeholder; `:` otherwise is a separator. + match bytes.get(1) { + Some(b) if b.is_ascii_alphabetic() || *b == b'_' => None, + _ => Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })), + } +} + +/// Lexes `E'...'`, and `B'...'` and `U&'...'` when `postgres_only` allows. +#[inline] +pub fn lex_prefixed_string(rest: &str, postgres_only: bool) -> Option { + let bytes = rest.as_bytes(); + match bytes[0] { + b'e' | b'E' if bytes.get(1) == Some(&b'\'') => { + let string = quoted_with_backslash(&rest[1..], TokenKind::String); + Some(string.and_then(|l| { + let body = &rest[2..l.len]; + crate::ast::unescape_escape_string(body, '\'')?; + Ok(Lexeme { + kind: TokenKind::String, + len: l.len + 1, + }) + })) + } + b'b' | b'B' if postgres_only && bytes.get(1) == Some(&b'\'') => { + let string = quoted(&rest[1..], TokenKind::String); + Some(string.map(|l| Lexeme { + kind: TokenKind::String, + len: l.len + 1, + })) + } + b'u' | b'U' + if postgres_only && bytes.get(1) == Some(&b'&') && bytes.get(2) == Some(&b'\'') => + { + let string = quoted(&rest[2..], TokenKind::String); + Some(string.map(|l| Lexeme { + kind: TokenKind::String, + len: l.len + 2, + })) + } + _ => None, + } +} + +/// Builds a string literal from a token that may have a prefix. +#[inline] +pub fn string_literal<'a>(token: Token<'a>, backslash_escapes: bool) -> StringLiteral<'a> { + let text = token.text; + let (prefix, body, escapes) = match text.as_bytes()[0] { + b'e' | b'E' => (StringPrefix::Escape, &text[1..], true), + b'b' | b'B' => (StringPrefix::Bit, &text[1..], false), + b'u' | b'U' => (StringPrefix::Unicode, &text[2..], false), + b'n' | b'N' => (StringPrefix::None, &text[1..], false), + _ => (StringPrefix::None, text, backslash_escapes), + }; + StringLiteral { + text: Cow::Borrowed(&body[1..body.len() - 1]), + quote: char::from(body.as_bytes()[0]), + backslash_escapes: escapes, + national: matches!(text.as_bytes()[0], b'n' | b'N'), + prefix, + triple: false, + } +} + +/// Lexes PostgreSQL's `0x`, `0o` and `0b` integers and `_` digit separators. +fn lex_postgres_number(rest: &str) -> Option { + let bytes = rest.as_bytes(); + if !bytes[0].is_ascii_digit() { + return None; + } + if bytes[0] == b'0' && matches!(bytes.get(1), Some(b'x' | b'X' | b'o' | b'O' | b'b' | b'B')) { + let radix = bytes[1].to_ascii_lowercase(); + let is_digit = |b: u8| match radix { + b'x' => b.is_ascii_hexdigit(), + b'o' => (b'0'..=b'7').contains(&b), + _ => b == b'0' || b == b'1', + }; + let mut len = 2; + let mut digits = 0; + while let Some(&b) = bytes.get(len) { + if is_digit(b) { + digits += 1; + len += 1; + } else if b == b'_' && bytes.get(len + 1).is_some_and(|&n| is_digit(n)) { + len += 1; + } else { + break; + } + } + if digits == 0 { + return Some(Err("expected digits after the radix prefix")); + } + if bytes + .get(len) + .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_') + { + return Some(Err("invalid number")); + } + return Some(Ok(Lexeme { + kind: TokenKind::Number, + len, + })); + } + // Only numbers containing `_` are this lexer's business. + let mut len = 0; + let mut underscore = false; + while let Some(&b) = bytes.get(len) { + if b.is_ascii_digit() { + len += 1; + } else if b == b'_' { + if !bytes.get(len + 1).is_some_and(u8::is_ascii_digit) { + if bytes.get(len + 1) == Some(&b'_') { + return Some(Err("invalid number")); + } + break; + } + underscore = true; + len += 1; + } else { + break; + } + } + if !underscore { + return None; + } + if crate::lexer::point_continues_number(bytes, len) { + len += 1; + loop { + while bytes.get(len).is_some_and(u8::is_ascii_digit) { + len += 1; + } + if bytes.get(len) == Some(&b'_') && bytes.get(len + 1).is_some_and(u8::is_ascii_digit) { + len += 1; + } else { + break; + } + } + } + if bytes + .get(len) + .is_some_and(|&b| b.is_ascii_alphabetic() || b == b'_') + { + return Some(Err("invalid number")); + } + Some(Ok(Lexeme { + kind: TokenKind::Number, + len, + })) +} + +/// Lexes an operator of PostgreSQL's: the longest run of operator characters, +/// shortened so as not to contain `--` or `/*`, and so as not to end in `+` or +/// `-` unless it holds a character that only an operator can. +#[inline] +fn is_special_operator_byte(byte: u8) -> bool { + matches!( + byte, + b'~' | b'!' | b'@' | b'#' | b'%' | b'^' | b'&' | b'|' | b'`' | b'?' + ) +} + +/// True for a byte that can be part of an operator. This runs on every token. +#[inline] +fn is_operator_byte(byte: u8) -> bool { + is_special_operator_byte(byte) || matches!(byte, b'+' | b'-' | b'*' | b'/' | b'<' | b'>' | b'=') +} + +fn lex_custom_operator(rest: &str) -> Option { + let bytes = rest.as_bytes(); + if !is_operator_byte(bytes[0]) { + return None; + } + let mut len = bytes + .iter() + .position(|&b| !is_operator_byte(b)) + .unwrap_or(bytes.len()); + if let Some(at) = bytes[..len] + .windows(2) + .position(|pair| pair == b"--" || pair == b"/*") + { + len = at; + } + if len == 0 { + return None; + } + if bytes[0] == b'!' { + // These are `!` followed by operators of their own. + const BANG_OPERATORS: [&str; 6] = ["!~~*", "!~~", "!~*", "!~", "!=", "!!"]; + let known = BANG_OPERATORS + .iter() + .find(|operator| rest[..len].starts_with(**operator)); + return Some(Ok(Lexeme { + kind: TokenKind::Op, + len: known.map_or(1, |operator| operator.len()), + })); + } + while len > 1 + && matches!(bytes[len - 1], b'+' | b'-') + && !bytes[..len].iter().any(|&b| is_special_operator_byte(b)) + { + len -= 1; + } + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) +} + +/// Parses `COPY ... FROM STDIN` data: the lines after the one holding the `;` +/// that ended the statement, up to a line holding only `\.`. +pub fn lex_copy_payload(sql: &str, tokens: &[Token<'_>], pos: usize) -> Option<(usize, usize)> { + // Only look at statements that end on the line just finished. + let finished = sql[..pos].trim_end_matches(['\r', '\n']); + let line_start = finished.rfind(['\n', '\r']).map_or(0, |at| at + 1); + let last_line_tokens = tokens + .iter() + .rev() + .take_while(|t| (t.span.start as usize) >= line_start) + .count(); + let first_on_line = tokens.len() - last_line_tokens; + let semicolon = (first_on_line..tokens.len()).find(|&i| tokens[i].is_op(";"))?; + let statement_start = tokens[..semicolon] + .iter() + .rposition(|t| t.is_op(";")) + .map_or(0, |at| at + 1); + let statement = &tokens[statement_start..semicolon]; + if !statement.first()?.is_word("COPY") { + return None; + } + let mut depth = 0i32; + let mut from_stdin = false; + for pair in statement.windows(2) { + depth += i32::from(pair[0].is_op("(")) - i32::from(pair[0].is_op(")")); + if depth == 0 && pair[0].is_word("FROM") && pair[1].is_word("STDIN") { + from_stdin = true; + } + } + if !from_stdin { + return None; + } + let bytes = sql.as_bytes(); + let mut end = pos; + loop { + let line_end = sql[end..] + .find(['\n', '\r']) + .map_or(bytes.len(), |at| end + at); + if &sql[end..line_end] == "\\." { + let mut after = line_end; + if bytes.get(after) == Some(&b'\r') { + after += 1; + } + if bytes.get(after) == Some(&b'\n') { + after += 1; + } + return Some((semicolon, after - pos)); + } + if line_end == bytes.len() { + return Some((semicolon, bytes.len() - pos)); + } + end = line_end + 1; + if bytes[line_end] == b'\r' && bytes.get(end) == Some(&b'\n') { + end += 1; + } + } +} + +/// Parses `INSERT`, adding an alias, `OVERRIDING` and `ON CONFLICT`. +pub fn parse_insert_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INSERT")?; + let modifiers = D::parse_insert_modifiers(p)?; + p.expect_keyword("INTO")?; + let table = grammar::parse_object_name(p)?; + let alias = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + let columns = if grammar::at_column_list(p) { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let overriding = if p.eat_keyword("OVERRIDING") { + let word = ["SYSTEM", "USER"] + .into_iter() + .find(|word| p.eat_keyword(word)) + .ok_or_else(|| p.expected("SYSTEM or USER"))?; + p.expect_keyword("VALUE")?; + Some(word) + } else { + None + }; + let source = D::parse_insert_source(p)?; + grammar::check_default_values(p, &columns, &source)?; + let on_conflict = if p.at_keyword("ON") && p.peek_nth(1).is_word("CONFLICT") { + p.advance(); + p.advance(); + Some(parse_on_conflict(p)?) + } else { + None + }; + let returning = D::parse_returning(p)?; + let insert = Insert { + modifiers, + into: true, + table, + columns, + output: None, + source, + returning, + }; + if alias.is_none() && overriding.is_none() && on_conflict.is_none() { + return Ok(StatementKind::Insert(Box::new(insert)).into()); + } + Ok(statement(PostgresStatement::Insert(Box::new( + PostgresInsert { + insert, + alias, + overriding: overriding.map(Cow::Borrowed), + on_conflict, + }, + )))) +} + +fn parse_on_conflict<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let target = if p.eat_op("(") { + let columns = p.parse_comma_separated(D::parse_order_by_item)?; + p.expect_op(")")?; + OnConflictTarget::Columns(columns) + } else if p.at_keyword("ON") { + p.advance(); + p.expect_keyword("CONSTRAINT")?; + OnConflictTarget::Constraint(p.parse_ident()?) + } else { + OnConflictTarget::None + }; + let predicate = if matches!(target, OnConflictTarget::Columns(_)) { + grammar::parse_optional_where(p)? + } else { + None + }; + p.expect_keyword("DO")?; + let update = if p.eat_keyword("NOTHING") { + None + } else { + p.expect_keyword("UPDATE")?; + p.expect_keyword("SET")?; + let assignments = p.parse_comma_separated(D::parse_assignment)?; + let selection = grammar::parse_optional_where(p)?; + Some(OnConflictUpdate { + assignments, + selection, + }) + }; + Ok(OnConflict { + target, + predicate, + update, + }) +} + +/// Parses `name AS [[NOT] MATERIALIZED] (query | DML)`. +pub fn parse_cte<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let columns = D::parse_cte_columns(p)?; + p.expect_keyword("AS")?; + let materialized = if p.eat_keyword("MATERIALIZED") { + Some(true) + } else if p.at_keyword("NOT") && p.peek_nth(1).is_word("MATERIALIZED") { + p.advance(); + p.advance(); + Some(false) + } else { + None + }; + p.expect_op("(")?; + let dml = p.at_keyword("INSERT") || p.at_keyword("UPDATE") || p.at_keyword("DELETE"); + let query = if dml { + let statement = p.nested(Parser::parse_statement)?; + Query { + with: None, + body: SetExpr::Statement(Box::new(statement)), + order_by: Vec::new(), + distribution: None, + limit: None, + fetch: None, + locks: Vec::new(), + tail: Default::default(), + pipes: Vec::new(), + } + } else { + p.nested(D::parse_query)? + }; + p.expect_op(")")?; + Ok(Cte { + name, + columns, + materialized, + query, + }) +} + +/// True at a word that begins another join in a chain. +fn at_join_word(p: &Parser<'_, D>) -> bool { + ["JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "NATURAL"] + .iter() + .any(|word| p.at_keyword(word)) +} + +/// Parses the next join, allowing `a JOIN b JOIN c ON x ON y`, in which the +/// second join nests inside the first without parentheses. +pub fn parse_join<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !at_join_word(p) { + return Ok(None); + } + let natural = p.eat_keyword("NATURAL"); + let Some((kind, spelled_out)) = grammar::parse_join_kind(p)? else { + return Err(p.expected("JOIN")); + }; + if natural && kind == JoinKind::Cross { + return Err(p.expected("a join type other than CROSS after NATURAL")); + } + let mut table = p.parse_table_ref()?; + if !natural && kind != JoinKind::Cross && at_join_word(p) && !p.at_keyword("CROSS") { + let relation = table; + let inner = p.nested(|p| { + let mut joins = Vec::new(); + while let Some(join) = D::parse_join(p)? { + joins.push(join); + if p.at_keyword("ON") || p.at_keyword("USING") { + break; + } + } + Ok(joins) + })?; + table = TableRef { + factor: TableFactor::NestedJoin(Box::new(TableWithJoins { + relation, + joins: inner, + })), + alias: None, + span: Span::default(), + }; + } + let constraint = if natural { + JoinConstraint::Natural + } else if kind == JoinKind::Cross { + JoinConstraint::None + } else if p.at_keyword("USING") { + p.advance(); + let columns = grammar::parse_ident_list(p)?; + if p.eat_keyword("AS") { + let alias = p.parse_ident()?; + JoinConstraint::Ext(BuiltinJoinConstraint::Postgres(PostgresUsingConstraint { + columns, + alias, + })) + } else { + JoinConstraint::Using(columns) + } + } else { + grammar::parse_join_constraint(p)? + }; + Ok(Some(Join { + kind, + spelled_out, + table, + constraint, + })) +} + +/// Parses a table factor, adding `ONLY` and the `*` after a table's name. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if grammar::at_xml_table(p) { + return grammar::parse_xml_table(p, true); + } + if p.at_keyword("ONLY") { + p.advance(); + let parenthesized = p.eat_op("("); + let name = grammar::parse_object_name(p)?; + if parenthesized { + p.expect_op(")")?; + } + return Ok(TableFactor::Ext(BuiltinTableFactor::Postgres(Box::new( + PostgresTableFactor::Inherited(InheritedTable { + only: true, + parenthesized, + name, + star: false, + }), + )))); + } + let factor = grammar::parse_table_factor(p)?; + if p.at_op("*") + && let TableFactor::Named(name) = factor + { + p.advance(); + return Ok(TableFactor::Ext(BuiltinTableFactor::Postgres(Box::new( + PostgresTableFactor::Inherited(InheritedTable { + only: false, + parenthesized: false, + name, + star: true, + }), + )))); + } + Ok(factor) +} + +/// The operators and `OPERATOR(...)` that only PostgreSQL has, or `None`. +fn postgres_infix_rule<'a, D: Dialect>( + p: &Parser<'a, D>, +) -> Option> { + let token = p.peek(); + if token.is_op("!") { + return Some(InfixRule::custom(prec::POSTFIX, parse_factorial)); + } + if token.kind == TokenKind::Word + && token.is_word("OPERATOR") + && p.peek_nth(1).is_op("(") + && !matches!(p.peek_nth(2).kind, TokenKind::Eof) + { + return Some(InfixRule::custom(prec::OTHER, parse_operator_call)); + } + if token.kind == TokenKind::Op && is_custom_binary(token.text) { + return Some(InfixRule::custom(prec::OTHER, parse_custom_binary)); + } + None +} + +/// True for an operator text this module reads rather than the core. +fn is_custom_binary(text: &str) -> bool { + if text == "!" || text == "(" || text == ")" { + return false; + } + let known = operator_rule::(text).is_some() + || matches!( + text, + "=" | "<>" + | "!=" + | "<" + | "<=" + | ">" + | ">=" + | "+" + | "-" + | "*" + | "/" + | "%" + | "[" + | "." + | "," + | ";" + | "::" + | ":=" + | ":" + | "]" + ); + !known + && text + .as_bytes() + .iter() + .all(|b| b"+-*/<>=~!@#%^&|`?".contains(b)) + && text.as_bytes().iter().any(|b| b"~!@#%^&|`?".contains(b)) +} + +fn parse_factorial<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + let op = p.advance().text; + Ok(ExprKind::Ext(BuiltinExpr::Postgres(PostgresExpr::Postfix { + expr: Box::new(left), + op: op.into(), + })) + .into()) +} + +fn parse_custom_binary<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + bp: u8, +) -> PResult> { + let op = p.advance().text; + let right = p.parse_expr_bp(bp)?; + Ok( + ExprKind::Ext(BuiltinExpr::Postgres(PostgresExpr::Binary(Box::new( + PostgresBinary { + left, + qualified: None, + op: op.into(), + right, + }, + )))) + .into(), + ) +} + +fn parse_operator_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + bp: u8, +) -> PResult> { + p.advance(); + p.expect_op("(")?; + let operator = ddl::parse_operator_name(p)?; + p.expect_op(")")?; + let right = p.parse_expr_bp(bp)?; + let op = operator.operator.clone(); + Ok( + ExprKind::Ext(BuiltinExpr::Postgres(PostgresExpr::Binary(Box::new( + PostgresBinary { + left, + qualified: Some(operator), + op, + right, + }, + )))) + .into(), + ) +} + +/// Parses `EXTRACT`'s field: a word, or a string as PostgreSQL allows. +pub fn parse_extract_field<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.peek(); + match token.kind { + TokenKind::String | TokenKind::Word | TokenKind::QuotedIdent => { + p.advance(); + Ok(token.text) + } + _ => Err(p.expected("a date or time field")), + } +} + +/// True if `word` is an interval qualifier in PostgreSQL's `INTERVAL` literals. +fn is_postgres_interval_unit(word: &str) -> bool { + ["YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND"] + .iter() + .any(|unit| unit.eq_ignore_ascii_case(word)) +} + +/// Rejects `GRANT MAINTAIN (columns)`, which has no column form. +pub fn parse_grant<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let grant = grammar::parse_grant(p)?; + if let Privileges::List(list) = &grant.privileges + && list.iter().any(|privilege| { + !privilege.columns.is_empty() + && privilege.words.len() == 1 + && privilege.words[0].eq_ignore_ascii_case("MAINTAIN") + }) + { + return Err(p.expected("a privilege without columns for MAINTAIN")); + } + Ok(grant) +} + +impl Dialect for Postgres { + type Ext = Builtin; + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + grammar::parse_select_item_alias_any_word(p, expr) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_order_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_order_by_item(p) + } + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_delete_using<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_delete_using(p) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_table(p) + } + + fn eat_limit_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_is_test<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + if let Some(test) = grammar::parse_is_json(p)? { + return Ok(Some(test)); + } + grammar::parse_is_normalized(p) + } + + fn parse_create_table_query<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_table_or_query(p) + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, true, true) + } + + fn parse_insert_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_insert_source_with_default(p) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + if flags != CreateFlags::default() { + return Err(p.expected("TABLE or VIEW")); + } + grammar::parse_create_schema_authorization(p, true) + } + + fn lex_after(prev: Option>, rest: &str) -> Option { + lex_slice_colon(prev, rest) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_full_statement(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_create_view<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + parse_create_view(p, flags) + } + + fn parse_table_constraint<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + table::parse_table_constraint(p) + } + + fn parse_index_flags<'a>(p: &mut Parser<'a, Self>) -> IndexFlags { + parse_index_flags(p) + } + + fn parse_index_storage<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_index_storage_parameters(p) + } + + fn parse_alter_type_using<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_alter_type_using(p) + } + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if let Some(op) = table::parse_alter_table_op_extra(p)? { + return Ok(op); + } + parse_alter_table_op(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + fn parse_set<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_set(p) + } + + fn parse_drop<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_drop(p) + } + + fn parse_explain_options<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_explain_option_list(p) + } + + fn is_niladic_function(word: &str) -> bool { + is_niladic_function(word) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + parse_drop_object_type(p) + } + + fn parse_interval<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_interval_with(p, false, is_postgres_interval_unit) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn parse_alter_table_only<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ONLY") + } + + fn parse_add_column_if_not_exists<'a>(p: &mut Parser<'a, Self>) -> PResult { + grammar::parse_if_not_exists(p) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + is_reserved(word) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + word.eq_ignore_ascii_case("END") || grammar::is_reserved_for_alias(word) + } + + fn parse_returning<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_returning(p) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_postgres_token(rest) + } + + #[inline] + fn lex_payload_line(sql: &str, tokens: &[Token<'_>], pos: usize) -> Option<(usize, usize)> { + lex_copy_payload(sql, tokens, pos) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + string_literal(token, false) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + if p.at_op("[") { + return Some(InfixRule::custom( + prec::POSTFIX, + grammar::parse_subscript_or_slice, + )); + } + postgres_infix_rule(p).or_else(|| infix_rule(p)) + } + + fn parse_select_modifiers<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_distinct_on(p) + } + + fn parse_cte<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_cte(p) + } + + /// `SELECT FROM t` selects no columns. + fn parse_projection<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + if p.at_keyword("FROM") { + return Ok(Vec::new()); + } + p.parse_comma_separated(Parser::parse_select_item) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_join(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_function_call<'a>( + p: &mut Parser<'a, Self>, + name: ObjectName<'a>, + ) -> PResult> { + parse_function_call(p, name) + } + + fn parse_function_arg<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_function_arg(p) + } + + fn parse_extract_field<'a>(p: &mut Parser<'a, Self>) -> PResult<&'a str> { + parse_extract_field(p) + } + + fn parse_grant<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_grant(p) + } + + fn parse_limit_after_locks<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + if p.eat_keyword("LIMIT") { + return Self::parse_limit(p).map(|limit| Some(Box::new(limit))); + } + Ok(None) + } +} diff --git a/sqlparser_v2/src/dialect/postgres/ddl.rs b/sqlparser_v2/src/dialect/postgres/ddl.rs new file mode 100644 index 0000000000..20a14fb6a8 --- /dev/null +++ b/sqlparser_v2/src/dialect/postgres/ddl.rs @@ -0,0 +1,3207 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Objects only PostgreSQL has: operators, aggregates, functions, types, +//! roles, text search, foreign data, triggers and rules. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + ColumnDef, ColumnOption, ConstraintAttribute, DataType, DropBehavior, Expr, ExprKind, + GenericOption, Grantee, Ident, Literal, ObjectName, OperatorName, Privileges, RoutineArg, + RoutineSignature, Statement, StatementKind, StringLiteral, +}; +use crate::dialect::postgres::{AlterPolicy, CreatePolicy, PostgresStatement}; +use crate::dialect::{Builtin, Dialect}; +use crate::display::comma; +use crate::grammar::{self, prec}; +use crate::lexer::TokenKind; +use crate::parser::Parser; + +type Exp<'a> = Expr<'a, Builtin>; +type Arg<'a> = RoutineArg<'a, Builtin>; +/// The expressions of `USING (...)` and `WITH CHECK (...)`. +type PolicyConditions<'a> = (Option>, Option>); + +/// An element of a `(name [= value], ...)` definition list. +#[derive(Debug, Clone, PartialEq)] +pub struct DefElem<'a> { + pub name: Ident<'a>, + pub value: Option>, +} + +/// The value of a definition element, which can name a type, an operator, a +/// function or a word, or be a number or string. +#[derive(Debug, Clone, PartialEq)] +pub enum DefArg<'a> { + /// A type or function name, which PostgreSQL reads identically. + Type(DataType<'a>), + /// `[schema.]operator` + Operator(OperatorName<'a>), + /// `OPERATOR([schema.]operator)` + OperatorCall(OperatorName<'a>), + Number(Cow<'a, str>), + String(StringLiteral<'a>), + /// A reserved word used as a value. + Word(Cow<'a, str>), +} + +/// `RENAME TO`, `OWNER TO` or `SET SCHEMA`. +#[derive(Debug, Clone, PartialEq)] +pub enum ObjectAction<'a> { + Rename(Ident<'a>), + Owner(Ident<'a>), + SetSchema(Ident<'a>), +} + +/// The name, method and items of `CREATE OPERATOR CLASS`. +#[derive(Debug, Clone, PartialEq)] +pub struct CreateOperatorClass<'a> { + pub name: ObjectName<'a>, + pub default: bool, + pub for_type: DataType<'a>, + pub using: Ident<'a>, + pub family: Option>, + pub items: Vec>, +} + +/// One item of an operator class or family. +#[derive(Debug, Clone, PartialEq)] +pub enum OperatorClassItem<'a> { + Operator { + strategy: Cow<'a, str>, + operator: OperatorName<'a>, + types: Option, DataType<'a>)>>, + /// `FOR SEARCH`, or `FOR ORDER BY` this family. + purpose: Option>, + }, + Function { + support: Cow<'a, str>, + /// The optional types written directly after the support number. + op_types: Vec>, + name: Option>, + args: Option>>, + }, + Storage(DataType<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum OperatorPurpose<'a> { + Search, + OrderBy(ObjectName<'a>), +} + +/// `CREATE OPERATOR CLASS` and `FAMILY`, `ALTER` and `DROP`. +#[derive(Debug, Clone, PartialEq)] +pub enum AlterFamilyOp<'a> { + Add(Vec>), + Drop(Vec>), + Action(ObjectAction<'a>), +} + +/// `(*)`, `(args)`, `(args ORDER BY args)` or `(ORDER BY args)`. +#[derive(Debug, Clone, PartialEq)] +pub enum AggregateArgs<'a> { + Star, + List { + args: Vec>, + order_by: Vec>, + }, +} + +/// `CREATE [OR REPLACE] AGGREGATE` +#[derive(Debug, Clone, PartialEq)] +pub struct CreateAggregate<'a> { + pub or_replace: bool, + pub name: ObjectName<'a>, + /// `None` for the legacy form, whose definition holds `BASETYPE`. + pub args: Option>, + pub definition: Vec>, +} + +/// `ALTER AGGREGATE name (args) ...` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterAggregate<'a> { + pub name: ObjectName<'a>, + pub args: AggregateArgs<'a>, + pub action: ObjectAction<'a>, +} + +/// `RETURNS` in `CREATE FUNCTION`. +#[derive(Debug, Clone, PartialEq)] +pub enum FunctionReturn<'a> { + Type(DataType<'a>), + SetOf(DataType<'a>), + Table(Vec>), +} + +/// `SET parameter ...`, in a function or role. +#[derive(Debug, Clone, PartialEq)] +pub struct ParameterSetting<'a> { + pub name: ObjectName<'a>, + pub value: ParameterValue<'a>, + /// True if written with `TO` rather than `=`. + pub to: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ParameterValue<'a> { + Default, + FromCurrent, + Values(Vec>), +} + +/// The body of `CREATE FUNCTION`. +#[derive(Debug, Clone, PartialEq)] +pub enum FunctionBody<'a> { + /// `AS 'text'[, 'link_symbol']` + As { + body: Literal<'a>, + link_symbol: Option>, + }, + /// `RETURN expr` + Return(Exp<'a>), + /// `BEGIN ATOMIC statement; ... END` + BeginAtomic(Vec>), +} + +/// `CREATE [OR REPLACE] FUNCTION` +#[derive(Debug, Clone, PartialEq)] +pub struct CreateFunction<'a> { + pub or_replace: bool, + pub name: ObjectName<'a>, + pub args: Vec>, + pub returns: Option>, + pub language: Option>, + pub window: bool, + /// `IMMUTABLE`, `STABLE` or `VOLATILE`. + pub volatility: Option>, + /// `CALLED ON NULL INPUT`, `RETURNS NULL ON NULL INPUT` or `STRICT`. + pub null_input: Option>, + /// `SAFE`, `UNSAFE` or `RESTRICTED`. + pub parallel: Option>, + /// `DEFINER` or `INVOKER`. + pub security: Option>, + pub leakproof: Option, + pub cost: Option>, + pub rows: Option>, + pub support: Option>, + pub set: Vec>, + pub body: Option>, +} + +/// An `ALTER FUNCTION` action, in the order written. +#[derive(Debug, Clone, PartialEq)] +pub enum FunctionAttr<'a> { + Volatility(Cow<'a, str>), + NullInput(Cow<'a, str>), + Parallel(Cow<'a, str>), + Security { + external: bool, + kind: Cow<'a, str>, + }, + Leakproof(bool), + Cost(Cow<'a, str>), + Rows(Cow<'a, str>), + Support(ObjectName<'a>), + Set(ParameterSetting<'a>), + /// `RESET name` or `RESET ALL`, the second with `None`. + Reset(Option>), + Restrict, +} + +/// What `ALTER FUNCTION` changes. +#[derive(Debug, Clone, PartialEq)] +pub enum AlterFunctionOp<'a> { + Action(ObjectAction<'a>), + /// `[NO] DEPENDS ON EXTENSION name` + DependsOn { + no: bool, + extension: Ident<'a>, + }, + Attributes(Vec>), +} + +/// `ALTER FUNCTION signature ...` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterFunction<'a> { + pub signature: RoutineSignature<'a, Builtin>, + pub op: AlterFunctionOp<'a>, +} + +/// One clause of `CREATE ROLE` or `ALTER ROLE`. +#[derive(Debug, Clone, PartialEq)] +pub enum RoleOption<'a> { + /// `SUPERUSER`, `NOLOGIN`, ... kept as written. + Flag(Cow<'a, str>), + ConnectionLimit(Cow<'a, str>), + Password(Option>), + ValidUntil(StringLiteral<'a>), + /// `IN ROLE`, `ROLE`, `ADMIN` and `USER` lists, holding their keyword. + Members { + keyword: Cow<'a, str>, + names: Vec>, + }, + Sysid(Cow<'a, str>), +} + +/// `CREATE ROLE`, `USER` or `GROUP`. +#[derive(Debug, Clone, PartialEq)] +pub struct CreateRole<'a> { + /// `ROLE`, `USER` or `GROUP`. + pub keyword: Cow<'a, str>, + pub name: Ident<'a>, + pub options: Vec>, +} + +/// What `ALTER ROLE` does. +#[derive(Debug, Clone, PartialEq)] +pub enum AlterRoleOp<'a> { + Rename(Ident<'a>), + Options { options: Vec> }, + Set(ParameterSetting<'a>), + Reset(Option>), +} + +/// `ALTER ROLE`, `USER` or `GROUP`. +#[derive(Debug, Clone, PartialEq)] +pub struct AlterRole<'a> { + pub keyword: Cow<'a, str>, + pub name: Ident<'a>, + pub in_database: Option>, + pub op: AlterRoleOp<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ExtensionVersion<'a> { + Name(Ident<'a>), + String(StringLiteral<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateExtension<'a> { + pub if_not_exists: bool, + pub name: Ident<'a>, + pub with: bool, + pub schema: Option>, + pub version: Option>, + pub cascade: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateDomain<'a> { + pub name: ObjectName<'a>, + /// True if `AS` was written. + pub as_keyword: bool, + pub data_type: DataType<'a>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CreateType<'a> { + Enum { + name: ObjectName<'a>, + labels: Vec>, + }, + Composite { + name: ObjectName<'a>, + columns: Vec>, + }, + Range { + name: ObjectName<'a>, + definition: Vec>, + }, + Base { + name: ObjectName<'a>, + definition: Vec>, + }, + Shell { + name: ObjectName<'a>, + }, +} + +/// `ALTER TYPE name ...` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterType<'a> { + pub name: ObjectName<'a>, + pub op: AlterTypeOp<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum AlterTypeOp<'a> { + Action(ObjectAction<'a>), + AddValue { + if_not_exists: bool, + value: StringLiteral<'a>, + /// `true` for `BEFORE`, `false` for `AFTER`, with the neighbour. + position: Option<(bool, StringLiteral<'a>)>, + }, + RenameValue { + old: StringLiteral<'a>, + new: StringLiteral<'a>, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateCollation<'a> { + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub source: CollationSource<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CollationSource<'a> { + Definition(Vec>), + From(ObjectName<'a>), +} + +/// `ALTER COLLATION name ...` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterCollation<'a> { + pub name: ObjectName<'a>, + pub op: AlterCollationOp<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum AlterCollationOp<'a> { + Action(ObjectAction<'a>), + RefreshVersion, +} + +/// The four text search object kinds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TextSearchKind { + Configuration, + Dictionary, + Parser, + Template, +} + +/// `ALTER TEXT SEARCH kind name ...` +#[derive(Debug, Clone, PartialEq)] +pub enum AlterTextSearchOp<'a> { + Options(Vec>), + Action(ObjectAction<'a>), +} + +/// A clause of `CREATE FOREIGN DATA WRAPPER`. +#[derive(Debug, Clone, PartialEq)] +pub enum FdwClause<'a> { + Handler(Option>), + Validator(Option>), + Options(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateServer<'a> { + pub if_not_exists: bool, + pub name: Ident<'a>, + pub server_type: Option>, + pub version: Option>, + pub wrapper: Ident<'a>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateUserMapping<'a> { + pub if_not_exists: bool, + pub user: Ident<'a>, + pub server: Ident<'a>, + pub options: Vec>, +} + +/// One action of `ALTER DEFAULT PRIVILEGES`. +#[derive(Debug, Clone, PartialEq)] +pub enum DefaultPrivilegesAction<'a> { + Grant { + privileges: Privileges<'a>, + object: Vec>, + grantees: Vec>, + with_grant_option: bool, + }, + Revoke { + grant_option: bool, + privileges: Privileges<'a>, + object: Vec>, + grantees: Vec>, + behavior: Option, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct AlterDefaultPrivileges<'a> { + /// `FOR ROLE names` and `IN SCHEMA names`, in the order written. + pub clauses: Vec>, + pub action: DefaultPrivilegesAction<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DefaultPrivilegesClause<'a> { + Roles { + keyword: Cow<'a, str>, + names: Vec>, + }, + Schemas(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TriggerEvent<'a> { + Insert, + Delete, + Truncate, + Update(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateTrigger<'a> { + pub or_replace: bool, + pub constraint: bool, + pub name: Ident<'a>, + /// `BEFORE`, `AFTER` or `INSTEAD OF`. + pub timing: Cow<'a, str>, + pub events: Vec>, + pub table: ObjectName<'a>, + pub from: Option>, + pub attributes: Vec, + /// `{OLD | NEW} [TABLE] [AS] name`, in the order written. + pub referencing: Vec>, + /// `Some((each, row))`, for `FOR [EACH] {ROW | STATEMENT}`. + pub for_each: Option<(bool, bool)>, + pub when: Option>, + /// True if written with `PROCEDURE` rather than `FUNCTION`. + pub procedure: bool, + pub function: ObjectName<'a>, + pub args: Option>>, +} + +/// One `REFERENCING` item. +#[derive(Debug, Clone, PartialEq)] +pub struct TriggerReferencing<'a> { + pub new: bool, + pub table: bool, + pub as_keyword: bool, + pub name: Ident<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateRule<'a> { + pub or_replace: bool, + pub name: Ident<'a>, + pub event: Cow<'a, str>, + pub table: ObjectName<'a>, + pub condition: Option>, + /// `Some(true)` for `INSTEAD`, `Some(false)` for `ALSO`. + pub instead: Option, + pub action: RuleAction<'a>, +} + +/// What a rule does. +#[derive(Debug, Clone, PartialEq)] +pub enum RuleAction<'a> { + Nothing, + Single(Box>), + Multiple(Vec>), +} + +pub fn statement(statement: PostgresStatement<'_>) -> Statement<'_, Builtin> { + StatementKind::Ext(crate::dialect::builtin::BuiltinStatement::Postgres( + statement, + )) + .into() +} + +// Parsing + +fn is_name_word(kind: TokenKind) -> bool { + matches!(kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +/// True at `[schema.]...operator`, where `n` tokens of the schema have been +/// checked to be a dotted prefix. +fn at_qualified_operator(p: &Parser<'_, D>) -> bool { + let mut n = 0; + loop { + let token = p.peek_nth(n); + if is_name_word(token.kind) && p.peek_nth(n + 1).is_op(".") { + n += 2; + } else { + return n > 0 && token.kind == TokenKind::Op && token.text != "("; + } + } +} + +/// Parses `[schema.]operator`. +pub fn parse_operator_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let mut schema = Vec::new(); + while is_name_word(p.peek().kind) && p.peek_nth(1).is_op(".") { + schema.push(p.parse_name_part()?); + p.advance(); + } + let token = p.peek(); + if token.kind != TokenKind::Op || token.text == "(" || token.text == ")" { + return Err(p.expected("an operator")); + } + p.advance(); + Ok(OperatorName { + schema, + operator: token.text.into(), + }) +} + +fn parse_operator_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("OPERATOR")?; + p.expect_op("(")?; + let operator = parse_operator_name(p)?; + p.expect_op(")")?; + Ok(operator) +} + +/// Parses `(name [= value], ...)`. +pub fn parse_definition<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + let elements = p.parse_comma_separated(parse_def_elem)?; + p.expect_op(")")?; + Ok(elements) +} + +fn parse_def_elem<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_name_part()?; + let value = if p.eat_op("=") { + Some(parse_def_arg(p)?) + } else { + None + }; + Ok(DefElem { name, value }) +} + +fn parse_def_arg<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::String => { + p.advance(); + return Ok(DefArg::String(D::string_literal(token))); + } + TokenKind::Number => { + p.advance(); + return Ok(DefArg::Number(token.text.into())); + } + TokenKind::Op + if (token.text == "-" || token.text == "+") + && p.peek_nth(1).kind == TokenKind::Number => + { + let start = token.span.start; + p.advance(); + let number = p.advance(); + let span = crate::ast::Span { + start, + end: number.span.end, + }; + return Ok(DefArg::Number(p.text(span).into())); + } + TokenKind::Op => return Ok(DefArg::Operator(parse_operator_name(p)?)), + TokenKind::Word if token.is_word("OPERATOR") && p.peek_nth(1).is_op("(") => { + return Ok(DefArg::OperatorCall(parse_operator_call(p)?)); + } + _ => {} + } + if at_qualified_operator(p) { + return Ok(DefArg::Operator(parse_operator_name(p)?)); + } + if token.kind == TokenKind::Word && !p.at_ident() { + p.advance(); + return Ok(DefArg::Word(token.text.into())); + } + Ok(DefArg::Type(D::parse_data_type(p)?)) +} + +/// Parses `RENAME TO` or `OWNER TO`, for `ALTER SCHEMA`. +pub fn parse_rename_or_owner<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + expect_object_action(p) +} + +/// Parses `RENAME TO`, `OWNER TO` or `SET SCHEMA`. +fn parse_object_action<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let next = p.peek_nth(1); + if p.at_keyword("RENAME") && next.is_word("TO") { + p.advance(); + p.advance(); + return p.parse_ident().map(ObjectAction::Rename).map(Some); + } + if p.at_keyword("OWNER") && next.is_word("TO") { + p.advance(); + p.advance(); + return p.parse_name_part().map(ObjectAction::Owner).map(Some); + } + if p.at_keyword("SET") && next.is_word("SCHEMA") { + p.advance(); + p.advance(); + return p.parse_ident().map(ObjectAction::SetSchema).map(Some); + } + Ok(None) +} + +fn expect_object_action<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + parse_object_action(p)?.ok_or_else(|| p.expected("RENAME TO, OWNER TO or SET SCHEMA")) +} + +/// Parses `(type, type)`, for an operator's arguments. +fn parse_operator_types<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(DataType<'a>, DataType<'a>)> { + p.expect_op("(")?; + let left = D::parse_data_type(p)?; + p.expect_op(",")?; + let right = D::parse_data_type(p)?; + p.expect_op(")")?; + Ok((left, right)) +} + +fn parse_family_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, + dropping: bool, +) -> PResult> { + if p.eat_keyword("OPERATOR") { + let strategy = parse_integer_text(p)?; + if dropping { + let types = parse_operator_types(p)?; + return Ok(OperatorClassItem::Operator { + strategy: strategy.into(), + operator: OperatorName { + schema: Vec::new(), + operator: "".into(), + }, + types: Some(Box::new(types)), + purpose: None, + }); + } + let operator = parse_operator_name(p)?; + let types = if p.at_op("(") { + Some(Box::new(parse_operator_types(p)?)) + } else { + None + }; + let purpose = if p.eat_keyword("FOR") { + if p.eat_keyword("SEARCH") { + Some(OperatorPurpose::Search) + } else { + p.expect_keyword("ORDER")?; + p.expect_keyword("BY")?; + Some(OperatorPurpose::OrderBy(grammar::parse_object_name(p)?)) + } + } else { + None + }; + return Ok(OperatorClassItem::Operator { + strategy: strategy.into(), + operator, + types, + purpose, + }); + } + if p.eat_keyword("FUNCTION") { + let support = parse_integer_text(p)?; + let op_types = if p.at_op("(") { + let types = parse_paren_types(p)?; + if types.is_empty() { + return Err(p.expected("a data type")); + } + types + } else { + Vec::new() + }; + let (name, args) = if dropping { + (None, None) + } else { + let name = grammar::parse_object_name(p)?; + let args = if p.at_op("(") { + Some(parse_paren_types(p)?) + } else { + None + }; + // `name()` means the same as `name`. + (Some(name), args.filter(|args| !args.is_empty())) + }; + return Ok(OperatorClassItem::Function { + support: support.into(), + op_types, + name, + args, + }); + } + p.expect_keyword("STORAGE")?; + Ok(OperatorClassItem::Storage(D::parse_data_type(p)?)) +} + +/// Parses a strategy or support number, which must be a small integer. +fn parse_integer_text<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.peek(); + let text = grammar::parse_number_text(p)?; + if text.parse::().is_err() { + return Err(crate::ParseError { + message: format!("expected an integer, found {text}"), + span: token.span, + }); + } + Ok(text) +} + +fn parse_paren_types<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + if p.eat_op(")") { + return Ok(Vec::new()); + } + let types = p.parse_comma_separated(D::parse_data_type)?; + p.expect_op(")")?; + Ok(types) +} + +/// Parses what follows `CREATE OPERATOR`. +fn parse_create_operator<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let family = p.at_keyword("FAMILY"); + if family || p.at_keyword("CLASS") { + p.advance(); + let name = grammar::parse_object_name(p)?; + if family { + p.expect_keyword("USING")?; + let using = p.parse_ident()?; + return Ok(PostgresStatement::CreateOperatorFamily { name, using }); + } + let default = p.eat_keyword("DEFAULT"); + p.expect_keyword("FOR")?; + p.expect_keyword("TYPE")?; + let for_type = D::parse_data_type(p)?; + p.expect_keyword("USING")?; + let using = p.parse_ident()?; + let family = if p.eat_keyword("FAMILY") { + Some(grammar::parse_object_name(p)?) + } else { + None + }; + p.expect_keyword("AS")?; + let items = p.parse_comma_separated(|p| parse_family_item(p, false))?; + return Ok(PostgresStatement::CreateOperatorClass(Box::new( + CreateOperatorClass { + name, + default, + for_type, + using, + family, + items, + }, + ))); + } + let mut name = parse_operator_name(p)?; + if name.operator == "!=" { + name.operator = "<>".into(); + } + let definition: Vec> = parse_definition(p)? + .into_iter() + .map(|element| DefElem { + name: element.name, + value: element.value.map(|value| match value { + DefArg::OperatorCall(operator) => DefArg::Operator(operator), + other => other, + }), + }) + .collect(); + const KEYS: [&str; 10] = [ + "FUNCTION", + "PROCEDURE", + "LEFTARG", + "RIGHTARG", + "COMMUTATOR", + "NEGATOR", + "RESTRICT", + "JOIN", + "HASHES", + "MERGES", + ]; + check_definition(p, &definition, &KEYS, true)?; + let has = |key: &str| { + definition + .iter() + .any(|element| element.name.text.eq_ignore_ascii_case(key)) + }; + if has("FUNCTION") == has("PROCEDURE") { + return Err(p.expected("exactly one of FUNCTION or PROCEDURE")); + } + Ok(PostgresStatement::CreateOperator { name, definition }) +} + +/// Checks that a definition sets only `keys` and, if `unique`, each of them +/// at most once. +fn check_definition<'a, D: Dialect>( + p: &Parser<'a, D>, + definition: &[DefElem<'a>], + keys: &[&str], + unique: bool, +) -> PResult<()> { + let mut seen: Vec<&str> = Vec::new(); + for element in definition { + let name = &element.name.text; + let key = keys.iter().find(|key| key.eq_ignore_ascii_case(name)); + let Some(key) = key.filter(|_| element.name.quote.is_none()) else { + return Err(p.expected(&format!("a definition option, not {name}"))); + }; + if unique && seen.contains(key) { + return Err(p.expected(&format!("{key} at most once"))); + } + seen.push(key); + } + Ok(()) +} + +/// Parses `ALTER OPERATOR ...`, with the cursor on `OPERATOR`. +fn parse_alter_operator<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let family = p.at_keyword("FAMILY"); + if family || p.at_keyword("CLASS") { + p.advance(); + let name = grammar::parse_object_name(p)?; + p.expect_keyword("USING")?; + let using = p.parse_ident()?; + if !family { + let action = expect_object_action(p)?; + return Ok(PostgresStatement::AlterOperatorClass { + family: false, + name, + using, + op: AlterFamilyOp::Action(action), + }); + } + let op = if p.eat_keyword("ADD") { + AlterFamilyOp::Add(p.parse_comma_separated(|p| parse_family_item(p, false))?) + } else if p.eat_keyword("DROP") { + AlterFamilyOp::Drop(p.parse_comma_separated(|p| parse_family_item(p, true))?) + } else { + AlterFamilyOp::Action(expect_object_action(p)?) + }; + return Ok(PostgresStatement::AlterOperatorClass { + family: true, + name, + using, + op, + }); + } + let name = parse_operator_name(p)?; + let (left, right) = parse_operator_types(p)?; + let op = if p.at_keyword("SET") && p.peek_nth(1).is_op("(") { + p.advance(); + AlterOperatorOp::Set(parse_definition(p)?) + } else { + AlterOperatorOp::Action(expect_object_action(p)?) + }; + Ok(PostgresStatement::AlterOperator { + name, + types: Box::new((left, right)), + op, + }) +} + +/// What `ALTER OPERATOR` does. +#[derive(Debug, Clone, PartialEq)] +pub enum AlterOperatorOp<'a> { + Action(ObjectAction<'a>), + Set(Vec>), +} + +/// Parses `DROP OPERATOR {CLASS|FAMILY}`, with the cursor on `CLASS`. +pub fn parse_drop_operator_group<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let family = p.at_keyword("FAMILY"); + p.advance(); + let if_exists = p.at_keyword("IF"); + if if_exists { + p.advance(); + p.expect_keyword("EXISTS")?; + } + let names = p.parse_comma_separated(grammar::parse_object_name)?; + p.expect_keyword("USING")?; + let using = p.parse_ident()?; + let behavior = if p.eat_keyword("CASCADE") { + Some(DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(DropBehavior::Restrict) + } else { + None + }; + Ok(PostgresStatement::DropOperatorGroup { + family, + if_exists, + names, + using, + behavior, + }) +} + +/// Parses one function or aggregate argument. The written `DEFAULT` is +/// normalized to `=`. +fn parse_routine_param<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mode = ["IN", "OUT", "INOUT", "VARIADIC"] + .into_iter() + .find(|mode| p.eat_keyword(mode)); + let next = p.peek_nth(1); + let continues_type = ["PRECISION", "VARYING", "WITH", "WITHOUT"] + .iter() + .any(|word| next.is_word(word)); + let has_name = p.at_ident() + && matches!(next.kind, TokenKind::Word | TokenKind::QuotedIdent) + && !continues_type + && !next.is_word("DEFAULT") + && !next.is_word("ORDER"); + let name = if has_name { + Some(p.parse_ident()?) + } else { + None + }; + let data_type = D::parse_data_type(p)?; + let default = if p.eat_op("=") || p.eat_keyword("DEFAULT") { + Some((true, p.parse_expr()?)) + } else { + None + }; + Ok(RoutineArg { + mode: mode.map(Cow::Borrowed), + name, + data_type, + default, + }) +} + +fn parse_aggregate_arg<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + let arg = parse_routine_param(p)?; + if matches!(arg.mode.as_deref(), Some("OUT" | "INOUT")) || arg.default.is_some() { + return Err(crate::ParseError { + message: "aggregate arguments cannot be output arguments or have defaults".into(), + span: token.span, + }); + } + Ok(arg) +} + +fn parse_aggregate_args<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("(")?; + if p.eat_op("*") { + p.expect_op(")")?; + return Ok(AggregateArgs::Star); + } + let args = if p.at_keyword("ORDER") { + Vec::new() + } else { + p.parse_comma_separated(parse_aggregate_arg)? + }; + let order_by = if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + p.parse_comma_separated(parse_aggregate_arg)? + } else { + Vec::new() + }; + p.expect_op(")")?; + Ok(AggregateArgs::List { args, order_by }) +} + +/// True if the list at the cursor is an aggregate's legacy definition, whose +/// first element is `name =`, or has no second list after it. +fn at_legacy_aggregate(p: &Parser<'_, D>) -> bool { + p.peek_nth(2).is_op("=") +} + +fn parse_create_aggregate<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_replace: bool, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + let args = if at_legacy_aggregate(p) { + None + } else { + Some(parse_aggregate_args(p)?) + }; + let definition = parse_definition(p)?; + const KEYS: [&str; 23] = [ + "SFUNC", + "STYPE", + "SSPACE", + "FINALFUNC", + "FINALFUNC_EXTRA", + "FINALFUNC_MODIFY", + "COMBINEFUNC", + "SERIALFUNC", + "DESERIALFUNC", + "INITCOND", + "MSFUNC", + "MINVFUNC", + "MSTYPE", + "MSSPACE", + "MFINALFUNC", + "MFINALFUNC_EXTRA", + "MFINALFUNC_MODIFY", + "MINITCOND", + "SORTOP", + "PARALLEL", + "HYPOTHETICAL", + "BASETYPE", + "COMPUTEFUNC", + ]; + check_definition(p, &definition, &KEYS, false)?; + Ok(PostgresStatement::CreateAggregate(Box::new( + CreateAggregate { + or_replace, + name, + args, + definition, + }, + ))) +} + +fn parse_set_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + if p.at_keyword("FROM") && p.peek_nth(1).is_word("CURRENT") { + p.advance(); + p.advance(); + return Ok(ParameterSetting { + name, + value: ParameterValue::FromCurrent, + to: false, + }); + } + let to = if p.eat_op("=") { + false + } else { + p.expect_keyword("TO")?; + true + }; + let value = if p.eat_keyword("DEFAULT") { + ParameterValue::Default + } else { + ParameterValue::Values(p.parse_comma_separated(|p| p.parse_expr_bp(prec::COMPARE))?) + }; + Ok(ParameterSetting { name, value, to }) +} + +fn parse_number_literal<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + grammar::parse_number_text(p) +} + +/// Parses what follows `FUNCTION`, with `or_replace` already read. +fn parse_create_function<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_replace: bool, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + p.expect_op("(")?; + let args = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(parse_routine_param)? + }; + p.expect_op(")")?; + let returns = if p.at_keyword("RETURNS") && !p.peek_nth(1).is_word("NULL") { + p.advance(); + Some(parse_function_return(p)?) + } else { + None + }; + + let mut function = CreateFunction { + or_replace, + name, + args, + returns, + language: None, + window: false, + volatility: None, + null_input: None, + parallel: None, + security: None, + leakproof: None, + cost: None, + rows: None, + support: None, + set: Vec::new(), + body: None, + }; + loop { + if p.eat_keyword("LANGUAGE") { + let language = p.parse_ident(); + set_once(p, &mut function.language, language, "LANGUAGE")?; + } else if p.eat_keyword("WINDOW") { + if function.window { + return Err(p.expected("WINDOW at most once")); + } + function.window = true; + } else if let Some(volatility) = parse_volatility(p) { + set_once( + p, + &mut function.volatility, + Ok(volatility.into()), + "IMMUTABLE, STABLE or VOLATILE", + )?; + } else if let Some(null_input) = parse_null_input(p) { + set_once( + p, + &mut function.null_input, + Ok(null_input.into()), + "null input", + )?; + } else if p.eat_keyword("PARALLEL") { + let level = parse_parallel(p)?; + set_once(p, &mut function.parallel, Ok(level.into()), "PARALLEL")?; + } else if p.at_keyword("SECURITY") { + p.advance(); + let kind = parse_security_kind(p)?; + set_once(p, &mut function.security, Ok(kind.into()), "SECURITY")?; + } else if p.eat_keyword("LEAKPROOF") { + set_once(p, &mut function.leakproof, Ok(true), "LEAKPROOF")?; + } else if p.at_keyword("NOT") && p.peek_nth(1).is_word("LEAKPROOF") { + p.advance(); + p.advance(); + set_once(p, &mut function.leakproof, Ok(false), "LEAKPROOF")?; + } else if p.eat_keyword("COST") { + let cost = parse_number_literal(p).map(Cow::from); + set_once(p, &mut function.cost, cost, "COST")?; + } else if p.eat_keyword("ROWS") { + let rows = parse_number_literal(p).map(Cow::from); + set_once(p, &mut function.rows, rows, "ROWS")?; + } else if p.eat_keyword("SUPPORT") { + let name = grammar::parse_object_name(p); + set_once(p, &mut function.support, name, "SUPPORT")?; + } else if p.eat_keyword("SET") { + let name = grammar::parse_object_name(p)?; + let setting = parse_set_value(p, name)?; + function.set.push(ParameterSetting { + to: false, + ..setting + }); + } else if p.eat_keyword("AS") { + let body = parse_body_literal(p)?; + let link_symbol = if p.eat_op(",") { + Some(parse_body_literal(p)?) + } else { + None + }; + set_once( + p, + &mut function.body, + Ok(FunctionBody::As { body, link_symbol }), + "AS", + )?; + } else if p.eat_keyword("RETURN") { + let value = p.parse_expr(); + set_once( + p, + &mut function.body, + value.map(FunctionBody::Return), + "RETURN", + )?; + } else if p.at_keyword("BEGIN") && p.peek_nth(1).is_word("ATOMIC") { + p.advance(); + p.advance(); + let statements = parse_begin_atomic(p)?; + set_once( + p, + &mut function.body, + Ok(FunctionBody::BeginAtomic(statements)), + "BEGIN ATOMIC", + )?; + } else { + break; + } + } + Ok(PostgresStatement::CreateFunction(Box::new(function))) +} + +fn set_once<'a, D: Dialect, T>( + p: &Parser<'a, D>, + slot: &mut Option, + value: PResult, + what: &str, +) -> PResult<()> { + let value = value?; + if slot.is_some() { + return Err(p.expected(&format!("{what} at most once"))); + } + *slot = Some(value); + Ok(()) +} + +fn parse_body_literal<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::String => { + p.advance(); + Ok(Literal::String(D::string_literal(token))) + } + TokenKind::DollarString => match p.parse_expr()?.kind { + ExprKind::Literal(literal) => Ok(literal), + _ => Err(p.expected("a dollar-quoted string")), + }, + _ => Err(p.expected("a string")), + } +} + +fn parse_function_return<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("SETOF") { + return D::parse_data_type(p).map(FunctionReturn::SetOf); + } + if p.at_keyword("TABLE") && p.peek_nth(1).is_op("(") { + p.advance(); + p.advance(); + let columns = p.parse_comma_separated(grammar::parse_column_def)?; + p.expect_op(")")?; + return Ok(FunctionReturn::Table(columns)); + } + D::parse_data_type(p).map(FunctionReturn::Type) +} + +fn parse_volatility(p: &mut Parser<'_, D>) -> Option<&'static str> { + ["IMMUTABLE", "STABLE", "VOLATILE"] + .into_iter() + .find(|word| p.eat_keyword(word)) +} + +fn parse_null_input(p: &mut Parser<'_, D>) -> Option<&'static str> { + let next = p.peek_nth(1); + if p.at_keyword("CALLED") && next.is_word("ON") { + for _ in 0..4 { + p.advance(); + } + return Some("CALLED ON NULL INPUT"); + } + if p.at_keyword("RETURNS") && next.is_word("NULL") { + for _ in 0..5 { + p.advance(); + } + return Some("RETURNS NULL ON NULL INPUT"); + } + if p.eat_keyword("STRICT") { + return Some("STRICT"); + } + None +} + +fn parse_parallel<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'static str> { + ["SAFE", "UNSAFE", "RESTRICTED"] + .into_iter() + .find(|word| p.eat_keyword(word)) + .ok_or_else(|| p.expected("SAFE, UNSAFE or RESTRICTED")) +} + +fn parse_security_kind<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'static str> { + ["DEFINER", "INVOKER"] + .into_iter() + .find(|word| p.eat_keyword(word)) + .ok_or_else(|| p.expected("DEFINER or INVOKER")) +} + +/// Parses `statement; ... END`. +fn parse_begin_atomic<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut statements = Vec::new(); + while !p.eat_keyword("END") { + let parsed = if p.eat_keyword("RETURN") { + statement(PostgresStatement::Return(Box::new(p.parse_expr()?))) + } else { + p.nested(Parser::parse_statement)? + }; + statements.push(parsed); + p.expect_op(";")?; + } + Ok(statements) +} + +/// Parses what follows `ALTER {FUNCTION | PROCEDURE | ROUTINE | AGGREGATE}`. +fn parse_alter_function<'a, D: Dialect>( + p: &mut Parser<'a, D>, + aggregate: bool, + keyword: &'static str, +) -> PResult> { + if aggregate { + let name = grammar::parse_object_name(p)?; + let args = parse_aggregate_args(p)?; + let action = expect_object_action(p)?; + return Ok(PostgresStatement::AlterAggregate(Box::new( + AlterAggregate { name, args, action }, + ))); + } + let name = grammar::parse_object_name(p)?; + let args = if p.eat_op("(") { + let args = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(parse_routine_param)? + }; + p.expect_op(")")?; + Some(args) + } else { + None + }; + let signature = RoutineSignature { name, args }; + let no_depends = p.at_keyword("NO") && p.peek_nth(1).is_word("DEPENDS"); + let op = if p.at_keyword("DEPENDS") || no_depends { + if no_depends { + p.advance(); + } + p.advance(); + p.expect_keyword("ON")?; + p.expect_keyword("EXTENSION")?; + AlterFunctionOp::DependsOn { + no: no_depends, + extension: p.parse_ident()?, + } + } else if let Some(action) = parse_object_action(p)? { + AlterFunctionOp::Action(action) + } else { + let mut attrs = Vec::new(); + while let Some(attr) = parse_function_attr(p)? { + attrs.push(attr); + } + if attrs.is_empty() { + return Err(p.expected("an ALTER FUNCTION action")); + } + AlterFunctionOp::Attributes(attrs) + }; + Ok(PostgresStatement::AlterFunction( + keyword.into(), + Box::new(AlterFunction { signature, op }), + )) +} + +fn parse_function_attr<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if let Some(volatility) = parse_volatility(p) { + return Ok(Some(FunctionAttr::Volatility(volatility.into()))); + } + if let Some(null_input) = parse_null_input(p) { + return Ok(Some(FunctionAttr::NullInput(null_input.into()))); + } + if p.eat_keyword("PARALLEL") { + return parse_parallel(p) + .map(|v| FunctionAttr::Parallel(v.into())) + .map(Some); + } + if p.at_keyword("SECURITY") || (p.at_keyword("EXTERNAL") && p.peek_nth(1).is_word("SECURITY")) { + let external = p.eat_keyword("EXTERNAL"); + p.advance(); + return Ok(Some(FunctionAttr::Security { + external, + kind: parse_security_kind(p)?.into(), + })); + } + if p.eat_keyword("LEAKPROOF") { + return Ok(Some(FunctionAttr::Leakproof(true))); + } + if p.at_keyword("NOT") && p.peek_nth(1).is_word("LEAKPROOF") { + p.advance(); + p.advance(); + return Ok(Some(FunctionAttr::Leakproof(false))); + } + if p.eat_keyword("COST") { + return parse_number_literal(p) + .map(|v| FunctionAttr::Cost(v.into())) + .map(Some); + } + if p.eat_keyword("ROWS") { + return parse_number_literal(p) + .map(|v| FunctionAttr::Rows(v.into())) + .map(Some); + } + if p.eat_keyword("SUPPORT") { + return grammar::parse_object_name(p) + .map(FunctionAttr::Support) + .map(Some); + } + if p.eat_keyword("RESTRICT") { + return Ok(Some(FunctionAttr::Restrict)); + } + if p.at_keyword("SET") { + p.advance(); + let name = grammar::parse_object_name(p)?; + let setting = parse_set_value(p, name)?; + return Ok(Some(FunctionAttr::Set(ParameterSetting { + to: false, + ..setting + }))); + } + if p.eat_keyword("RESET") { + return Ok(Some(FunctionAttr::Reset(if p.eat_keyword("ALL") { + None + } else { + Some(grammar::parse_object_name(p)?) + }))); + } + Ok(None) +} + +const ROLE_FLAGS: [&str; 14] = [ + "SUPERUSER", + "NOSUPERUSER", + "CREATEDB", + "NOCREATEDB", + "CREATEROLE", + "NOCREATEROLE", + "INHERIT", + "NOINHERIT", + "LOGIN", + "NOLOGIN", + "REPLICATION", + "NOREPLICATION", + "BYPASSRLS", + "NOBYPASSRLS", +]; + +fn parse_role_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let token = p.peek(); + if token.kind == TokenKind::Word && ROLE_FLAGS.iter().any(|word| token.is_word(word)) { + p.advance(); + return Ok(Some(RoleOption::Flag(token.text.into()))); + } + if p.eat_keyword("CONNECTION") { + p.expect_keyword("LIMIT")?; + let start = p.peek().span.start; + if !p.eat_op("-") { + p.eat_op("+"); + } + let number = grammar::parse_number_text(p)?; + let end = number.as_ptr() as usize + number.len() - p.source().as_ptr() as usize; + return Ok(Some(RoleOption::ConnectionLimit(Cow::Borrowed( + &p.source()[start as usize..end], + )))); + } + if p.eat_keyword("PASSWORD") { + let value = if p.eat_keyword("NULL") { + None + } else { + Some(grammar::parse_string(p)?) + }; + return Ok(Some(RoleOption::Password(value))); + } + if p.eat_keyword("VALID") { + p.expect_keyword("UNTIL")?; + return grammar::parse_string(p) + .map(RoleOption::ValidUntil) + .map(Some); + } + if p.eat_keyword("SYSID") { + return parse_number_literal(p) + .map(|v| RoleOption::Sysid(v.into())) + .map(Some); + } + let keyword = if p.at_keyword("IN") && p.peek_nth(1).is_word("ROLE") { + p.advance(); + p.advance(); + Some("IN ROLE") + } else if p.at_keyword("IN") && p.peek_nth(1).is_word("GROUP") { + p.advance(); + p.advance(); + Some("IN GROUP") + } else if p.eat_keyword("ROLE") { + Some("ROLE") + } else if p.eat_keyword("ADMIN") { + Some("ADMIN") + } else if p.eat_keyword("USER") { + Some("USER") + } else { + None + }; + let Some(keyword) = keyword else { + return Ok(None); + }; + let names = p.parse_comma_separated(Parser::parse_ident)?; + Ok(Some(RoleOption::Members { + keyword: keyword.into(), + names, + })) +} + +fn parse_role_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut options = Vec::new(); + let mut seen_flags: Vec = Vec::new(); + let start = p.peek(); + while let Some(option) = parse_role_option(p)? { + if let RoleOption::Flag(ref word) = option { + let base = word + .strip_prefix(['n', 'N']) + .filter(|rest| { + rest.strip_prefix(['o', 'O']) + .is_some_and(|flag| ROLE_FLAGS.iter().any(|f| f.eq_ignore_ascii_case(flag))) + }) + .map_or(word.as_ref(), |rest| &rest[1..]); + if seen_flags.iter().any(|f| f.eq_ignore_ascii_case(base)) { + return Err(p.expected(&format!("only one {base} option, near {}", start.text))); + } + seen_flags.push(base.to_owned()); + } + options.push(option); + } + Ok(options) +} + +/// The rank of a role option in the canonical order the options render in. +fn role_option_rank(option: &RoleOption<'_>) -> usize { + match option { + RoleOption::Flag(word) => { + let word = word.to_ascii_uppercase(); + let word = word.strip_prefix("NO").unwrap_or(&word); + ROLE_FLAGS.iter().position(|f| *f == word).unwrap_or(0) / 2 + } + RoleOption::ConnectionLimit(_) => 100, + RoleOption::Password(_) => 101, + RoleOption::ValidUntil(_) => 102, + RoleOption::Members { keyword, .. } => { + ["IN ROLE", "IN GROUP", "ROLE", "ADMIN", "USER"] + .iter() + .position(|k| k == keyword) + .unwrap_or(5) + + 103 + } + RoleOption::Sysid(_) => 110, + } +} + +fn write_role_options(f: &mut fmt::Formatter<'_>, options: &[RoleOption<'_>]) -> fmt::Result { + let mut sorted: Vec<&RoleOption<'_>> = options.iter().collect(); + sorted.sort_by_key(|option| role_option_rank(option)); + for option in sorted { + write!(f, " {option}")?; + } + Ok(()) +} + +/// Parses what follows `CREATE {ROLE | USER | GROUP}`. +fn parse_create_role<'a, D: Dialect>( + p: &mut Parser<'a, D>, + keyword: &'static str, +) -> PResult> { + let name = p.parse_ident()?; + p.eat_keyword("WITH"); + let options = parse_role_options(p)?; + Ok(PostgresStatement::CreateRole(Box::new(CreateRole { + keyword: keyword.into(), + name, + options, + }))) +} + +/// Parses what follows `ALTER {ROLE | USER | GROUP}`. +fn parse_alter_role<'a, D: Dialect>( + p: &mut Parser<'a, D>, + keyword: &'static str, +) -> PResult> { + let name = p.parse_ident()?; + let in_database = if p.at_keyword("IN") && p.peek_nth(1).is_word("DATABASE") { + p.advance(); + p.advance(); + Some(p.parse_ident()?) + } else { + None + }; + let op = if p.at_keyword("RENAME") && p.peek_nth(1).is_word("TO") { + p.advance(); + p.advance(); + AlterRoleOp::Rename(p.parse_ident()?) + } else if p.eat_keyword("SET") { + let parameter = grammar::parse_object_name(p)?; + let setting = parse_set_value(p, parameter)?; + AlterRoleOp::Set(ParameterSetting { + to: true, + ..setting + }) + } else if p.eat_keyword("RESET") { + AlterRoleOp::Reset(if p.eat_keyword("ALL") { + None + } else { + Some(grammar::parse_object_name(p)?) + }) + } else { + p.eat_keyword("WITH"); + let options = parse_role_options(p)?; + if options.is_empty() { + return Err(p.expected("an ALTER ROLE action")); + } + AlterRoleOp::Options { options } + }; + Ok(PostgresStatement::AlterRole(Box::new(AlterRole { + keyword: keyword.into(), + name, + in_database, + op, + }))) +} + +fn parse_create_extension<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = p.parse_ident()?; + let with = p.eat_keyword("WITH"); + let (mut schema, mut version, mut cascade) = (None, None, false); + loop { + if p.eat_keyword("SCHEMA") { + let value = p.parse_ident(); + set_once(p, &mut schema, value, "SCHEMA")?; + } else if p.eat_keyword("VERSION") { + let token = p.peek(); + let value = if token.kind == TokenKind::String { + p.advance(); + Ok(ExtensionVersion::String(D::string_literal(token))) + } else { + p.parse_ident().map(ExtensionVersion::Name) + }; + set_once(p, &mut version, value, "VERSION")?; + } else if p.eat_keyword("CASCADE") { + if cascade { + return Err(p.expected("CASCADE at most once")); + } + cascade = true; + } else { + break; + } + } + Ok(PostgresStatement::CreateExtension(Box::new( + CreateExtension { + if_not_exists, + name, + with, + schema, + version, + cascade, + }, + ))) +} + +fn parse_create_domain<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + let as_keyword = p.eat_keyword("AS"); + let data_type = D::parse_data_type(p)?; + let mut options = Vec::new(); + while let Some(option) = D::parse_column_option(p)? { + options.push(option); + } + Ok(PostgresStatement::CreateDomain(Box::new(CreateDomain { + name, + as_keyword, + data_type, + options, + }))) +} + +pub fn parse_create_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + if p.eat_keyword("AS") { + if p.eat_keyword("ENUM") { + p.expect_op("(")?; + let labels = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(grammar::parse_string)? + }; + p.expect_op(")")?; + return Ok(PostgresStatement::CreateType(Box::new(CreateType::Enum { + name, + labels, + }))); + } + if p.eat_keyword("RANGE") { + let definition = parse_definition(p)?; + return Ok(PostgresStatement::CreateType(Box::new(CreateType::Range { + name, + definition, + }))); + } + p.expect_op("(")?; + let columns = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(D::parse_column_def)? + }; + p.expect_op(")")?; + return Ok(PostgresStatement::CreateType(Box::new( + CreateType::Composite { name, columns }, + ))); + } + if p.at_op("(") { + let definition = parse_definition(p)?; + return Ok(PostgresStatement::CreateType(Box::new(CreateType::Base { + name, + definition, + }))); + } + Ok(PostgresStatement::CreateType(Box::new(CreateType::Shell { + name, + }))) +} + +fn parse_alter_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + let op = if p.at_keyword("ADD") && p.peek_nth(1).is_word("VALUE") { + p.advance(); + p.advance(); + let if_not_exists = grammar::parse_if_not_exists(p)?; + let value = grammar::parse_string(p)?; + let position = if p.eat_keyword("BEFORE") { + Some((true, grammar::parse_string(p)?)) + } else if p.eat_keyword("AFTER") { + Some((false, grammar::parse_string(p)?)) + } else { + None + }; + AlterTypeOp::AddValue { + if_not_exists, + value, + position, + } + } else if p.at_keyword("RENAME") && p.peek_nth(1).is_word("VALUE") { + p.advance(); + p.advance(); + let old = grammar::parse_string(p)?; + p.expect_keyword("TO")?; + AlterTypeOp::RenameValue { + old, + new: grammar::parse_string(p)?, + } + } else { + AlterTypeOp::Action(expect_object_action(p)?) + }; + Ok(PostgresStatement::AlterType(Box::new(AlterType { + name, + op, + }))) +} + +fn parse_create_collation<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let source = if p.eat_keyword("FROM") { + CollationSource::From(grammar::parse_object_name(p)?) + } else { + CollationSource::Definition(parse_definition(p)?) + }; + Ok(PostgresStatement::CreateCollation(Box::new( + CreateCollation { + if_not_exists, + name, + source, + }, + ))) +} + +fn parse_alter_collation<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + let op = if p.at_keyword("REFRESH") && p.peek_nth(1).is_word("VERSION") { + p.advance(); + p.advance(); + AlterCollationOp::RefreshVersion + } else { + AlterCollationOp::Action(expect_object_action(p)?) + }; + Ok(PostgresStatement::AlterCollation(Box::new( + AlterCollation { name, op }, + ))) +} + +fn parse_text_search_kind<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + let token = p.peek(); + let kind = if token.is_word("CONFIGURATION") { + TextSearchKind::Configuration + } else if token.is_word("DICTIONARY") { + TextSearchKind::Dictionary + } else if token.is_word("PARSER") { + TextSearchKind::Parser + } else if token.is_word("TEMPLATE") { + TextSearchKind::Template + } else { + return Err(p.expected("a text search object")); + }; + p.advance(); + Ok(kind) +} + +fn parse_create_text_search<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SEARCH")?; + let kind = parse_text_search_kind(p)?; + let name = grammar::parse_object_name(p)?; + let definition = parse_definition(p)?; + Ok(PostgresStatement::CreateTextSearch { + kind, + name, + definition, + }) +} + +fn parse_alter_text_search<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SEARCH")?; + let kind = parse_text_search_kind(p)?; + let name = grammar::parse_object_name(p)?; + let op = if p.at_op("(") { + AlterTextSearchOp::Options(parse_definition(p)?) + } else { + AlterTextSearchOp::Action(expect_object_action(p)?) + }; + Ok(PostgresStatement::AlterTextSearch { kind, name, op }) +} + +/// Parses `OPTIONS (...)` if present. +pub fn parse_generic_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.eat_keyword("OPTIONS") { + return Ok(Vec::new()); + } + p.expect_op("(")?; + let options = p.parse_comma_separated(parse_generic_option)?; + p.expect_op(")")?; + Ok(options) +} + +/// Parses `[ADD | SET | DROP] name ['value']`. +fn parse_generic_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + let keyword = if next.kind == TokenKind::String || next.is_op(",") || next.is_op(")") { + None + } else { + ["ADD", "SET", "DROP"] + .into_iter() + .find(|word| p.at_keyword(word)) + }; + if keyword.is_some() { + p.advance(); + } + let name = p.parse_name_part()?; + let value = if keyword == Some("DROP") { + None + } else { + Some(grammar::parse_string(p)?) + }; + Ok(GenericOption { + action: keyword.map(Cow::Borrowed), + name, + value, + }) +} + +fn parse_create_fdw<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DATA")?; + p.expect_keyword("WRAPPER")?; + let name = p.parse_ident()?; + let mut clauses = Vec::new(); + loop { + if p.at_keyword("NO") && p.peek_nth(1).is_word("HANDLER") { + p.advance(); + p.advance(); + clauses.push(FdwClause::Handler(None)); + } else if p.at_keyword("NO") && p.peek_nth(1).is_word("VALIDATOR") { + p.advance(); + p.advance(); + clauses.push(FdwClause::Validator(None)); + } else if p.eat_keyword("HANDLER") { + clauses.push(FdwClause::Handler(Some(p.parse_ident()?))); + } else if p.eat_keyword("VALIDATOR") { + clauses.push(FdwClause::Validator(Some(p.parse_ident()?))); + } else if p.at_keyword("OPTIONS") { + clauses.push(FdwClause::Options(parse_generic_options(p)?)); + } else { + break; + } + } + Ok(PostgresStatement::CreateForeignDataWrapper { name, clauses }) +} + +fn parse_create_server<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = p.parse_ident()?; + let server_type = if p.eat_keyword("TYPE") { + Some(grammar::parse_string(p)?) + } else { + None + }; + let version = if p.eat_keyword("VERSION") { + Some(grammar::parse_string(p)?) + } else { + None + }; + p.expect_keyword("FOREIGN")?; + p.expect_keyword("DATA")?; + p.expect_keyword("WRAPPER")?; + let wrapper = p.parse_ident()?; + let options = parse_generic_options(p)?; + Ok(PostgresStatement::CreateServer(Box::new(CreateServer { + if_not_exists, + name, + server_type, + version, + wrapper, + options, + }))) +} + +/// Parses what follows `CREATE USER`, when `MAPPING` follows it. +fn parse_create_user_mapping<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + p.expect_keyword("FOR")?; + let user = p.parse_name_part()?; + p.expect_keyword("SERVER")?; + let server = p.parse_ident()?; + let options = parse_generic_options(p)?; + Ok(PostgresStatement::CreateUserMapping(Box::new( + CreateUserMapping { + if_not_exists, + user, + server, + options, + }, + ))) +} + +fn parse_default_privileges<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("PRIVILEGES")?; + let mut clauses = Vec::new(); + loop { + if p.at_keyword("FOR") && (p.peek_nth(1).is_word("ROLE") || p.peek_nth(1).is_word("USER")) { + p.advance(); + let keyword = if p.eat_keyword("ROLE") { + "ROLE" + } else { + p.advance(); + "USER" + }; + clauses.push(DefaultPrivilegesClause::Roles { + keyword: keyword.into(), + names: p.parse_comma_separated(Parser::parse_ident)?, + }); + } else if p.at_keyword("IN") && p.peek_nth(1).is_word("SCHEMA") { + p.advance(); + p.advance(); + clauses.push(DefaultPrivilegesClause::Schemas( + p.parse_comma_separated(Parser::parse_ident)?, + )); + } else { + break; + } + } + let action = if p.eat_keyword("GRANT") { + let privileges = grammar::parse_privileges(p)?; + let object = parse_default_object(p)?; + p.expect_keyword("TO")?; + let grantees = D::parse_grantees(p)?; + let with_grant_option = p.at_keyword("WITH"); + if with_grant_option { + p.advance(); + p.expect_keyword("GRANT")?; + p.expect_keyword("OPTION")?; + } + DefaultPrivilegesAction::Grant { + privileges, + object: object.into_iter().map(Cow::Borrowed).collect(), + grantees, + with_grant_option, + } + } else { + p.expect_keyword("REVOKE")?; + let grant_option = p.at_keyword("GRANT"); + if grant_option { + p.advance(); + p.expect_keyword("OPTION")?; + p.expect_keyword("FOR")?; + } + let privileges = grammar::parse_privileges(p)?; + let object = parse_default_object(p)?; + p.expect_keyword("FROM")?; + let grantees = D::parse_grantees(p)?; + let behavior = if p.eat_keyword("CASCADE") { + Some(DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(DropBehavior::Restrict) + } else { + None + }; + DefaultPrivilegesAction::Revoke { + grant_option, + privileges, + object: object.into_iter().map(Cow::Borrowed).collect(), + grantees, + behavior, + } + }; + Ok(PostgresStatement::AlterDefaultPrivileges(Box::new( + AlterDefaultPrivileges { clauses, action }, + ))) +} + +/// Parses `ON kind` of `ALTER DEFAULT PRIVILEGES`, as written. +fn parse_default_object<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ON")?; + const KINDS: [&[&str]; 7] = [ + &["TABLES"], + &["SEQUENCES"], + &["FUNCTIONS"], + &["ROUTINES"], + &["TYPES"], + &["SCHEMAS"], + &["LARGE", "OBJECTS"], + ]; + let Some(words) = KINDS.iter().find(|words| { + words + .iter() + .enumerate() + .all(|(i, word)| p.peek_nth(i).is_word(word)) + }) else { + return Err( + p.expected("TABLES, SEQUENCES, FUNCTIONS, ROUTINES, TYPES, SCHEMAS or LARGE OBJECTS") + ); + }; + Ok(words.iter().map(|_| p.advance().text).collect()) +} + +fn parse_create_trigger<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_replace: bool, + constraint: bool, +) -> PResult> { + let name = p.parse_ident()?; + let timing = if p.eat_keyword("BEFORE") { + "BEFORE" + } else if p.eat_keyword("AFTER") { + "AFTER" + } else { + p.expect_keyword("INSTEAD")?; + p.expect_keyword("OF")?; + "INSTEAD OF" + }; + let mut events = vec![parse_trigger_event(p)?]; + while p.eat_keyword("OR") { + events.push(parse_trigger_event(p)?); + } + p.expect_keyword("ON")?; + let table = grammar::parse_object_name(p)?; + let from = if p.eat_keyword("FROM") { + Some(grammar::parse_object_name(p)?) + } else { + None + }; + let mut attributes = Vec::new(); + while let Some(attribute) = grammar::parse_constraint_attribute(p)? { + attributes.push(attribute); + } + let mut referencing = Vec::new(); + if p.eat_keyword("REFERENCING") { + while p.at_keyword("OLD") || p.at_keyword("NEW") { + let new = p.at_keyword("NEW"); + p.advance(); + let table = p.eat_keyword("TABLE"); + let as_keyword = p.eat_keyword("AS"); + let name = p.parse_ident()?; + referencing.push(TriggerReferencing { + new, + table, + as_keyword, + name, + }); + } + if referencing.is_empty() { + return Err(p.expected("OLD or NEW")); + } + } + let for_each = if p.eat_keyword("FOR") { + let each = p.eat_keyword("EACH"); + let row = p.eat_keyword("ROW"); + if !row { + p.expect_keyword("STATEMENT")?; + } + Some((each, row)) + } else { + None + }; + let when = if p.eat_keyword("WHEN") { + p.expect_op("(")?; + let condition = p.parse_expr()?; + p.expect_op(")")?; + Some(condition) + } else { + None + }; + p.expect_keyword("EXECUTE")?; + let procedure = if p.eat_keyword("PROCEDURE") { + true + } else { + p.expect_keyword("FUNCTION")?; + false + }; + let function = grammar::parse_object_name(p)?; + let args = if p.eat_op("(") { + let args = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(parse_trigger_arg)? + }; + p.expect_op(")")?; + Some(args) + } else { + None + }; + Ok(PostgresStatement::CreateTrigger(Box::new(CreateTrigger { + or_replace, + constraint, + name, + timing: timing.into(), + events, + table, + from, + attributes, + referencing, + for_each, + when, + procedure, + function, + args, + }))) +} + +/// Trigger arguments are literals: numbers and strings, or bare words. +fn parse_trigger_arg<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::Number => { + p.advance(); + Ok(Literal::Number(token.text.into())) + } + TokenKind::String => { + p.advance(); + Ok(Literal::String(D::string_literal(token))) + } + _ => Err(p.expected("a literal")), + } +} + +fn parse_trigger_event<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("INSERT") { + return Ok(TriggerEvent::Insert); + } + if p.eat_keyword("DELETE") { + return Ok(TriggerEvent::Delete); + } + if p.eat_keyword("TRUNCATE") { + return Ok(TriggerEvent::Truncate); + } + p.expect_keyword("UPDATE")?; + let columns = if p.eat_keyword("OF") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + Ok(TriggerEvent::Update(columns)) +} + +fn parse_create_rule<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_replace: bool, +) -> PResult> { + let name = p.parse_ident()?; + p.expect_keyword("AS")?; + p.expect_keyword("ON")?; + let event = ["SELECT", "INSERT", "UPDATE", "DELETE"] + .into_iter() + .find(|word| p.eat_keyword(word)) + .ok_or_else(|| p.expected("SELECT, INSERT, UPDATE or DELETE"))?; + p.expect_keyword("TO")?; + let table = grammar::parse_object_name(p)?; + let condition = grammar::parse_optional_where(p)?; + p.expect_keyword("DO")?; + let instead = if p.eat_keyword("INSTEAD") { + Some(true) + } else if p.eat_keyword("ALSO") { + Some(false) + } else { + None + }; + let action = if p.eat_keyword("NOTHING") { + RuleAction::Nothing + } else if p.eat_op("(") { + let mut statements = Vec::new(); + loop { + statements.push(p.nested(Parser::parse_statement)?); + if !p.eat_op(";") { + break; + } + if p.at_op(")") { + break; + } + } + p.expect_op(")")?; + RuleAction::Multiple(statements) + } else { + RuleAction::Single(Box::new(p.nested(Parser::parse_statement)?)) + }; + Ok(PostgresStatement::CreateRule(Box::new(CreateRule { + or_replace, + name, + event: event.into(), + table, + condition, + instead, + action, + }))) +} + +fn at_user_mapping(p: &Parser<'_, D>) -> bool { + p.at_keyword("USER") + && p.peek_nth(1).is_word("MAPPING") + && (p.peek_nth(2).is_word("FOR") || p.peek_nth(2).is_word("IF")) +} + +/// Dispatches `CREATE` for the kinds only PostgreSQL has, or returns `None` +/// to let the caller handle it, with the cursor on the object type. +fn parse_policy_roles<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("TO") { + p.parse_comma_separated(Parser::parse_ident) + } else { + Ok(Vec::new()) + } +} + +/// Parses `USING (expr)` and `WITH CHECK (expr)`, in that order. +fn parse_policy_conditions<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let parse_condition = |p: &mut Parser<'a, D>| { + p.expect_op("(")?; + let expr = p.parse_expr()?; + p.expect_op(")")?; + Ok(expr) + }; + let using = if p.eat_keyword("USING") { + Some(parse_condition(p)?) + } else { + None + }; + let with_check = if p.at_keyword("WITH") && p.peek_nth(1).is_word("CHECK") { + p.advance(); + p.advance(); + Some(parse_condition(p)?) + } else { + None + }; + Ok((using, with_check)) +} + +fn parse_create_policy<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + p.expect_keyword("ON")?; + let table = grammar::parse_object_name(p)?; + let kind = if p.eat_keyword("AS") { + let token = p.peek(); + if !(token.is_word("PERMISSIVE") || token.is_word("RESTRICTIVE")) { + return Err(p.expected("PERMISSIVE or RESTRICTIVE")); + } + p.advance(); + Some(token.text) + } else { + None + }; + let command = if p.eat_keyword("FOR") { + let token = p.peek(); + if !["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"] + .iter() + .any(|word| token.is_word(word)) + { + return Err(p.expected("ALL, SELECT, INSERT, UPDATE or DELETE")); + } + p.advance(); + Some(token.text) + } else { + None + }; + let to = parse_policy_roles(p)?; + let (using, with_check) = parse_policy_conditions(p)?; + Ok(PostgresStatement::CreatePolicy(Box::new(CreatePolicy { + name, + table, + kind: kind.map(Cow::Borrowed), + command: command.map(Cow::Borrowed), + to, + using, + with_check, + }))) +} + +fn parse_alter_policy<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + p.expect_keyword("ON")?; + let table = grammar::parse_object_name(p)?; + if p.at_keyword("RENAME") && p.peek_nth(1).is_word("TO") { + p.advance(); + p.advance(); + let rename_to = Some(p.parse_ident()?); + return Ok(PostgresStatement::AlterPolicy(Box::new(AlterPolicy { + name, + table, + rename_to, + to: Vec::new(), + using: None, + with_check: None, + }))); + } + let to = parse_policy_roles(p)?; + let (using, with_check) = parse_policy_conditions(p)?; + Ok(PostgresStatement::AlterPolicy(Box::new(AlterPolicy { + name, + table, + rename_to: None, + to, + using, + with_check, + }))) +} + +pub fn parse_create_object<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_replace: bool, +) -> PResult>> { + let token = p.peek(); + let next = p.peek_nth(1); + if !or_replace { + if p.at_keyword("POLICY") { + p.advance(); + return parse_create_policy(p).map(Some); + } + if p.at_keyword("OPERATOR") { + p.advance(); + return parse_create_operator(p).map(Some); + } + if p.at_keyword("EXTENSION") { + p.advance(); + return parse_create_extension(p).map(Some); + } + if p.at_keyword("DOMAIN") { + p.advance(); + return parse_create_domain(p).map(Some); + } + if p.at_keyword("TYPE") { + p.advance(); + return parse_create_type(p).map(Some); + } + if p.at_keyword("COLLATION") { + p.advance(); + return parse_create_collation(p).map(Some); + } + if p.at_keyword("TEXT") { + p.advance(); + return parse_create_text_search(p).map(Some); + } + if p.at_keyword("SERVER") { + p.advance(); + return parse_create_server(p).map(Some); + } + if p.at_keyword("FOREIGN") && next.is_word("DATA") { + p.advance(); + return parse_create_fdw(p).map(Some); + } + if at_user_mapping(p) { + p.advance(); + p.advance(); + return parse_create_user_mapping(p).map(Some); + } + for keyword in ["ROLE", "USER", "GROUP"] { + if token.is_word(keyword) { + p.advance(); + return parse_create_role(p, keyword).map(Some); + } + } + } + if p.eat_keyword("AGGREGATE") { + return parse_create_aggregate(p, or_replace).map(Some); + } + if p.eat_keyword("FUNCTION") { + return parse_create_function(p, or_replace).map(Some); + } + if p.eat_keyword("RULE") { + return parse_create_rule(p, or_replace).map(Some); + } + if p.at_keyword("CONSTRAINT") && next.is_word("TRIGGER") { + p.advance(); + p.advance(); + return parse_create_trigger(p, or_replace, true).map(Some); + } + if p.eat_keyword("TRIGGER") { + return parse_create_trigger(p, or_replace, false).map(Some); + } + Ok(None) +} + +/// Parses `ALTER` for objects other than tables, or returns `None`. +pub fn parse_alter_object<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.at_keyword("OPERATOR") { + return parse_alter_operator(p).map(Some); + } + if p.eat_keyword("POLICY") { + return parse_alter_policy(p).map(Some); + } + if p.eat_keyword("AGGREGATE") { + return parse_alter_function(p, true, "AGGREGATE").map(Some); + } + for keyword in ["FUNCTION", "PROCEDURE", "ROUTINE"] { + if p.eat_keyword(keyword) { + return parse_alter_function(p, false, keyword).map(Some); + } + } + for keyword in ["ROLE", "USER", "GROUP"] { + if p.eat_keyword(keyword) { + return parse_alter_role(p, keyword).map(Some); + } + } + if p.eat_keyword("TYPE") { + return parse_alter_type(p).map(Some); + } + if p.eat_keyword("COLLATION") { + return parse_alter_collation(p).map(Some); + } + if p.eat_keyword("TEXT") { + return parse_alter_text_search(p).map(Some); + } + if p.eat_keyword("DEFAULT") { + return parse_default_privileges(p).map(Some); + } + Ok(None) +} + +impl fmt::Display for DefElem<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + if let Some(value) = &self.value { + write!(f, " = {value}")?; + } + Ok(()) + } +} + +impl fmt::Display for DefArg<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DefArg::Type(ty) => ty.fmt(f), + DefArg::Operator(op) => op.fmt(f), + DefArg::OperatorCall(op) => write!(f, "OPERATOR({op})"), + DefArg::Number(n) => f.write_str(n), + DefArg::String(s) => s.fmt(f), + DefArg::Word(w) => f.write_str(w), + } + } +} + +impl fmt::Display for ObjectAction<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ObjectAction::Rename(name) => write!(f, "RENAME TO {name}"), + ObjectAction::Owner(name) => write!(f, "OWNER TO {name}"), + ObjectAction::SetSchema(name) => write!(f, "SET SCHEMA {name}"), + } + } +} + +impl fmt::Display for OperatorClassItem<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OperatorClassItem::Operator { + strategy, + operator, + types, + purpose, + } => { + write!(f, "OPERATOR {strategy}")?; + if !operator.operator.is_empty() { + write!(f, " {operator}")?; + } + if let Some((left, right)) = types.as_deref() { + write!(f, " ({left}, {right})")?; + } + match purpose { + Some(OperatorPurpose::Search) => f.write_str(" FOR SEARCH"), + Some(OperatorPurpose::OrderBy(name)) => write!(f, " FOR ORDER BY {name}"), + None => Ok(()), + } + } + OperatorClassItem::Function { + support, + op_types, + name, + args, + } => { + write!(f, "FUNCTION {support}")?; + if !op_types.is_empty() { + write!(f, " ({})", comma(op_types))?; + } + if let Some(name) = name { + write!(f, " {name}")?; + } + if let Some(args) = args { + write!(f, "({})", comma(args))?; + } + Ok(()) + } + OperatorClassItem::Storage(ty) => write!(f, "STORAGE {ty}"), + } + } +} + +impl fmt::Display for AlterFamilyOp<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AlterFamilyOp::Add(items) => write!(f, "ADD {}", comma(items)), + AlterFamilyOp::Drop(items) => write!(f, "DROP {}", comma(items)), + AlterFamilyOp::Action(action) => action.fmt(f), + } + } +} + +impl fmt::Display for AlterOperatorOp<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AlterOperatorOp::Action(action) => action.fmt(f), + AlterOperatorOp::Set(definition) => write!(f, "SET ({})", comma(definition)), + } + } +} + +impl fmt::Display for AggregateArgs<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AggregateArgs::Star => f.write_str("*"), + AggregateArgs::List { args, order_by } => { + comma(args).fmt(f)?; + if !order_by.is_empty() { + if !args.is_empty() { + f.write_str(" ")?; + } + write!(f, "ORDER BY {}", comma(order_by))?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for CreateAggregate<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + write!(f, "AGGREGATE {} ", self.name)?; + if let Some(args) = &self.args { + write!(f, "({args}) ")?; + } + write!(f, "({})", comma(&self.definition)) + } +} + +impl fmt::Display for FunctionReturn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FunctionReturn::Type(ty) => ty.fmt(f), + FunctionReturn::SetOf(ty) => write!(f, "SETOF {ty}"), + FunctionReturn::Table(columns) => write!(f, "TABLE({})", comma(columns)), + } + } +} + +impl fmt::Display for ParameterSetting<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "SET {}", self.name)?; + match &self.value { + ParameterValue::FromCurrent => f.write_str(" FROM CURRENT"), + ParameterValue::Default => { + write!(f, " {} DEFAULT", if self.to { "TO" } else { "=" }) + } + ParameterValue::Values(values) => { + write!(f, " {} {}", if self.to { "TO" } else { "=" }, comma(values)) + } + } + } +} + +impl fmt::Display for CreateFunction<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + write!(f, "FUNCTION {}({})", self.name, comma(&self.args))?; + if let Some(returns) = &self.returns { + write!(f, " RETURNS {returns}")?; + } + if let Some(language) = &self.language { + write!(f, " LANGUAGE {language}")?; + } + if self.window { + f.write_str(" WINDOW")?; + } + if let Some(ref volatility) = self.volatility { + write!(f, " {volatility}")?; + } + if let Some(ref null_input) = self.null_input { + write!(f, " {null_input}")?; + } + if let Some(ref parallel) = self.parallel { + write!(f, " PARALLEL {parallel}")?; + } + if let Some(ref security) = self.security { + write!(f, " SECURITY {security}")?; + } + match self.leakproof { + Some(true) => f.write_str(" LEAKPROOF")?, + Some(false) => f.write_str(" NOT LEAKPROOF")?, + None => {} + } + if let Some(ref cost) = self.cost { + write!(f, " COST {cost}")?; + } + if let Some(ref rows) = self.rows { + write!(f, " ROWS {rows}")?; + } + if let Some(support) = &self.support { + write!(f, " SUPPORT {support}")?; + } + for setting in &self.set { + write!(f, " {setting}")?; + } + match &self.body { + Some(FunctionBody::As { body, link_symbol }) => { + write!(f, " AS {body}")?; + if let Some(symbol) = link_symbol { + write!(f, ", {symbol}")?; + } + } + Some(FunctionBody::Return(value)) => write!(f, " RETURN {value}")?, + Some(FunctionBody::BeginAtomic(statements)) => { + f.write_str(" BEGIN ATOMIC")?; + for statement in statements { + write!(f, " {statement};")?; + } + f.write_str(" END")?; + } + None => {} + } + Ok(()) + } +} + +impl fmt::Display for FunctionAttr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FunctionAttr::Volatility(word) | FunctionAttr::NullInput(word) => f.write_str(word), + FunctionAttr::Parallel(level) => write!(f, "PARALLEL {level}"), + FunctionAttr::Security { external, kind } => { + if *external { + f.write_str("EXTERNAL ")?; + } + write!(f, "SECURITY {kind}") + } + FunctionAttr::Leakproof(true) => f.write_str("LEAKPROOF"), + FunctionAttr::Leakproof(false) => f.write_str("NOT LEAKPROOF"), + FunctionAttr::Cost(n) => write!(f, "COST {n}"), + FunctionAttr::Rows(n) => write!(f, "ROWS {n}"), + FunctionAttr::Support(name) => write!(f, "SUPPORT {name}"), + FunctionAttr::Set(setting) => setting.fmt(f), + FunctionAttr::Reset(None) => f.write_str("RESET ALL"), + FunctionAttr::Reset(Some(name)) => write!(f, "RESET {name}"), + FunctionAttr::Restrict => f.write_str("RESTRICT"), + } + } +} + +impl fmt::Display for AlterFunction<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} ", self.signature)?; + match &self.op { + AlterFunctionOp::Action(action) => action.fmt(f), + AlterFunctionOp::DependsOn { no, extension } => { + if *no { + f.write_str("NO ")?; + } + write!(f, "DEPENDS ON EXTENSION {extension}") + } + AlterFunctionOp::Attributes(attrs) => crate::display::space(attrs).fmt(f), + } + } +} + +impl fmt::Display for RoleOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RoleOption::Flag(word) => f.write_str(word), + RoleOption::ConnectionLimit(limit) => write!(f, "CONNECTION LIMIT {limit}"), + RoleOption::Password(None) => f.write_str("PASSWORD NULL"), + RoleOption::Password(Some(password)) => { + write!(f, "PASSWORD {}", password) + } + RoleOption::ValidUntil(when) => write!(f, "VALID UNTIL {}", when), + RoleOption::Members { keyword, names } => write!(f, "{keyword} {}", comma(names)), + RoleOption::Sysid(id) => write!(f, "SYSID {id}"), + } + } +} + +impl fmt::Display for CreateRole<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "CREATE {} {}", self.keyword, self.name)?; + write_role_options(f, &self.options) + } +} + +impl fmt::Display for AlterRole<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ALTER ROLE {}", self.name)?; + if let Some(database) = &self.in_database { + write!(f, " IN DATABASE {database}")?; + } + match &self.op { + AlterRoleOp::Rename(name) => write!(f, " RENAME TO {name}"), + AlterRoleOp::Set(setting) => write!(f, " {setting}"), + AlterRoleOp::Reset(None) => f.write_str(" RESET ALL"), + AlterRoleOp::Reset(Some(name)) => write!(f, " RESET {name}"), + AlterRoleOp::Options { options } => { + f.write_str(" WITH")?; + for option in options { + write!(f, " {option}")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for CreateExtension<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE EXTENSION ")?; + crate::display::write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if self.with { + f.write_str(" WITH")?; + } + if let Some(schema) = &self.schema { + write!(f, " SCHEMA {schema}")?; + } + match &self.version { + Some(ExtensionVersion::Name(version)) => write!(f, " VERSION {version}")?, + Some(ExtensionVersion::String(version)) => write!(f, " VERSION {}", version)?, + None => {} + } + if self.cascade { + f.write_str(" CASCADE")?; + } + Ok(()) + } +} + +impl fmt::Display for CreateDomain<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "CREATE DOMAIN {}", self.name)?; + if self.as_keyword { + f.write_str(" AS")?; + } + write!(f, " {}", self.data_type)?; + for option in &self.options { + write!(f, " {option}")?; + } + Ok(()) + } +} + +impl fmt::Display for CreateType<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CreateType::Enum { name, labels } => { + write!(f, "CREATE TYPE {name} AS ENUM (")?; + for (i, label) in labels.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + label.fmt(f)?; + } + f.write_str(")") + } + CreateType::Composite { name, columns } => { + write!(f, "CREATE TYPE {name} AS ({})", comma(columns)) + } + CreateType::Range { name, definition } => { + write!(f, "CREATE TYPE {name} AS RANGE ({})", comma(definition)) + } + CreateType::Base { name, definition } => { + write!(f, "CREATE TYPE {name} ({})", comma(definition)) + } + CreateType::Shell { name } => write!(f, "CREATE TYPE {name}"), + } + } +} + +impl fmt::Display for AlterType<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ALTER TYPE {} ", self.name)?; + match &self.op { + AlterTypeOp::Action(action) => action.fmt(f), + AlterTypeOp::AddValue { + if_not_exists, + value, + position, + } => { + f.write_str("ADD VALUE ")?; + crate::display::write_if_not_exists(f, *if_not_exists)?; + value.fmt(f)?; + match position { + Some((true, other)) => write!(f, " BEFORE {}", other), + Some((false, other)) => write!(f, " AFTER {}", other), + None => Ok(()), + } + } + AlterTypeOp::RenameValue { old, new } => { + write!(f, "RENAME VALUE {} TO {}", old, new) + } + } + } +} + +impl fmt::Display for CreateCollation<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE COLLATION ")?; + crate::display::write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + match &self.source { + CollationSource::Definition(definition) => write!(f, " ({})", comma(definition)), + CollationSource::From(source) => write!(f, " FROM {source}"), + } + } +} + +impl fmt::Display for AlterCollation<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ALTER COLLATION {} ", self.name)?; + match &self.op { + AlterCollationOp::Action(action) => action.fmt(f), + AlterCollationOp::RefreshVersion => f.write_str("REFRESH VERSION"), + } + } +} + +impl TextSearchKind { + pub fn keyword(self) -> &'static str { + match self { + TextSearchKind::Configuration => "CONFIGURATION", + TextSearchKind::Dictionary => "DICTIONARY", + TextSearchKind::Parser => "PARSER", + TextSearchKind::Template => "TEMPLATE", + } + } +} + +impl fmt::Display for FdwClause<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FdwClause::Handler(Some(name)) => write!(f, "HANDLER {name}"), + FdwClause::Handler(None) => f.write_str("NO HANDLER"), + FdwClause::Validator(Some(name)) => write!(f, "VALIDATOR {name}"), + FdwClause::Validator(None) => f.write_str("NO VALIDATOR"), + FdwClause::Options(options) => write_options(f, options), + } + } +} + +/// Writes `OPTIONS (...)`. +pub fn write_options(f: &mut fmt::Formatter<'_>, options: &[GenericOption<'_>]) -> fmt::Result { + write!(f, "OPTIONS ({})", comma(options)) +} + +impl fmt::Display for CreateServer<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE SERVER ")?; + crate::display::write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if let Some(ref server_type) = self.server_type { + write!(f, " TYPE {}", server_type)?; + } + if let Some(ref version) = self.version { + write!(f, " VERSION {}", version)?; + } + write!(f, " FOREIGN DATA WRAPPER {}", self.wrapper)?; + if !self.options.is_empty() { + f.write_str(" ")?; + write_options(f, &self.options)?; + } + Ok(()) + } +} + +impl fmt::Display for CreateUserMapping<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE USER MAPPING ")?; + crate::display::write_if_not_exists(f, self.if_not_exists)?; + write!(f, "FOR {} SERVER {}", self.user, self.server)?; + if !self.options.is_empty() { + f.write_str(" ")?; + write_options(f, &self.options)?; + } + Ok(()) + } +} + +fn write_object_words(f: &mut fmt::Formatter<'_>, words: &[Cow<'_, str>]) -> fmt::Result { + for (i, word) in words.iter().enumerate() { + if i > 0 { + f.write_str(" ")?; + } + f.write_str(word)?; + } + Ok(()) +} + +impl fmt::Display for AlterDefaultPrivileges<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ALTER DEFAULT PRIVILEGES")?; + for clause in &self.clauses { + match clause { + DefaultPrivilegesClause::Roles { keyword: _, names } => { + write!(f, " FOR ROLE {}", comma(names))? + } + DefaultPrivilegesClause::Schemas(names) => { + write!(f, " IN SCHEMA {}", comma(names))? + } + } + } + match &self.action { + DefaultPrivilegesAction::Grant { + privileges, + object, + grantees, + with_grant_option, + } => { + write!(f, " GRANT {privileges} ON ")?; + write_object_words(f, object)?; + write!(f, " TO {}", comma(grantees))?; + if *with_grant_option { + f.write_str(" WITH GRANT OPTION")?; + } + Ok(()) + } + DefaultPrivilegesAction::Revoke { + grant_option, + privileges, + object, + grantees, + behavior, + } => { + f.write_str(" REVOKE ")?; + if *grant_option { + f.write_str("GRANT OPTION FOR ")?; + } + write!(f, "{privileges} ON ")?; + write_object_words(f, object)?; + write!(f, " FROM {}", comma(grantees))?; + write_behavior(f, *behavior) + } + } + } +} + +/// Writes ` CASCADE` or ` RESTRICT` if present. +pub fn write_behavior(f: &mut fmt::Formatter<'_>, behavior: Option) -> fmt::Result { + f.write_str(match behavior { + Some(DropBehavior::Cascade) => " CASCADE", + Some(DropBehavior::Restrict) => " RESTRICT", + None => "", + }) +} + +impl fmt::Display for TriggerEvent<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TriggerEvent::Insert => f.write_str("INSERT"), + TriggerEvent::Delete => f.write_str("DELETE"), + TriggerEvent::Truncate => f.write_str("TRUNCATE"), + TriggerEvent::Update(columns) if columns.is_empty() => f.write_str("UPDATE"), + TriggerEvent::Update(columns) => write!(f, "UPDATE OF {}", comma(columns)), + } + } +} + +impl fmt::Display for CreateTrigger<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + if self.constraint { + f.write_str("CONSTRAINT ")?; + } + write!(f, "TRIGGER {} {} ", self.name, self.timing)?; + for (i, event) in self.events.iter().enumerate() { + if i > 0 { + f.write_str(" OR ")?; + } + event.fmt(f)?; + } + write!(f, " ON {}", self.table)?; + if let Some(from) = &self.from { + write!(f, " FROM {from}")?; + } + for attribute in &self.attributes { + write!(f, " {attribute}")?; + } + if !self.referencing.is_empty() { + f.write_str(" REFERENCING")?; + for item in &self.referencing { + f.write_str(if item.new { " NEW" } else { " OLD" })?; + if item.table { + f.write_str(" TABLE")?; + } + if item.as_keyword { + f.write_str(" AS")?; + } + write!(f, " {}", item.name)?; + } + } + if let Some((each, row)) = self.for_each { + f.write_str(" FOR ")?; + if each { + f.write_str("EACH ")?; + } + f.write_str(if row { "ROW" } else { "STATEMENT" })?; + } + if let Some(when) = &self.when { + write!(f, " WHEN ({when})")?; + } + write!( + f, + " EXECUTE {} {}", + if self.procedure { + "PROCEDURE" + } else { + "FUNCTION" + }, + self.function + )?; + if let Some(args) = &self.args { + write!(f, "({})", comma(args))?; + } + Ok(()) + } +} + +impl fmt::Display for CreateRule<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + write!( + f, + "RULE {} AS ON {} TO {}", + self.name, self.event, self.table + )?; + if let Some(condition) = &self.condition { + write!(f, " WHERE {condition}")?; + } + f.write_str(" DO ")?; + match self.instead { + Some(true) => f.write_str("INSTEAD ")?, + Some(false) => f.write_str("ALSO ")?, + None => {} + } + match &self.action { + RuleAction::Nothing => f.write_str("NOTHING"), + RuleAction::Single(statement) => statement.fmt(f), + RuleAction::Multiple(statements) => { + f.write_str("(")?; + for (i, statement) in statements.iter().enumerate() { + if i > 0 { + f.write_str("; ")?; + } + statement.fmt(f)?; + } + f.write_str(")") + } + } + } +} diff --git a/sqlparser_v2/src/dialect/postgres/table.rs b/sqlparser_v2/src/dialect/postgres/table.rs new file mode 100644 index 0000000000..b17942278b --- /dev/null +++ b/sqlparser_v2/src/dialect/postgres/table.rs @@ -0,0 +1,712 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! PostgreSQL's table clauses: `PARTITION OF`, `LIKE`, `INHERITS` and more. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + AlterColumnAction, AlterTable, AlterTableOp, ColumnOption, ConstraintAttribute, CreateFlags, + CreateTable, ExcludeConstraint, ExcludeElement, ExcludeOperator, Expr, Ident, IndexStorage, + ObjectName, PartitionBound, RangeBound, Statement, StatementKind, TableConstraint, + TableConstraintKind, +}; +use crate::dialect::postgres::ddl::{parse_generic_options, parse_operator_name, statement}; +use crate::dialect::postgres::{PostgresStatement, ddl}; +use crate::dialect::{Builtin, Dialect}; +use crate::display::{Indent, NewLine, SpaceOrNewline, comma, write_storage}; +use crate::grammar; +use crate::lexer::TokenKind; +use crate::parser::Parser; + +type Exp<'a> = Expr<'a, Builtin>; + +/// A column of `CREATE TABLE ... PARTITION OF`, which gives no type. +#[derive(Debug, Clone, PartialEq)] +pub struct PartitionColumn<'a> { + pub name: Ident<'a>, + /// True if `WITH OPTIONS` was written. + pub with_options: bool, + pub options: Vec>, +} + +/// `LIKE source [INCLUDING | EXCLUDING option]...` +#[derive(Debug, Clone, PartialEq)] +pub struct TableLike<'a> { + pub source: ObjectName<'a>, + /// `(including, option)`, in the order written. + pub options: Vec<(bool, Ident<'a>)>, + /// How many columns come before this element. + pub position: usize, +} + +/// `CREATE TABLE` with clauses the core does not have. +#[derive(Debug, Clone, PartialEq)] +pub struct PostgresCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + pub local: bool, + pub unlogged: bool, + pub foreign: bool, + pub partition_of: Option>, + /// True if the column list was written, even when empty. + pub has_elements: bool, + pub likes: Vec>, + pub partition_columns: Vec>, + pub inherits: Vec>, + pub bound: Option>, + pub partition_by: Option>>, + pub with: IndexStorage<'a, Builtin>, + /// `DROP`, `DELETE ROWS` or `PRESERVE ROWS`. + pub on_commit: Option>, + pub server: Option>, + pub options: Vec>, +} + +impl PostgresCreateTable<'_> { + /// True if this holds nothing beyond the core table. + pub fn is_plain(&self) -> bool { + (self.table.columns.len() + self.table.constraints.len() > 0 || self.table.query.is_some()) + && !self.local + && !self.unlogged + && !self.foreign + && self.partition_of.is_none() + && self.likes.is_empty() + && self.partition_columns.is_empty() + && self.inherits.is_empty() + && self.bound.is_none() + && self.partition_by.is_none() + && self.with.is_empty() + && self.on_commit.is_none() + && self.server.is_none() + && self.options.is_empty() + } +} + +/// True at `CREATE [OR REPLACE] [temporary-like] TABLE`, `n` tokens in. +pub fn at_create_table_at(p: &Parser<'_, D>, n: usize) -> bool { + let mut n = n; + if p.peek_nth(n).is_word("LOCAL") { + n += 1; + } + if ["TEMP", "TEMPORARY", "UNLOGGED"] + .iter() + .any(|word| p.peek_nth(n).is_word(word)) + { + n += 1; + } + p.peek_nth(n).is_word("TABLE") +} + +/// Parses what follows `CREATE`, with the cursor on the first modifier. +pub fn parse_create_table_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, + or_replace: bool, +) -> PResult> { + let local = p.eat_keyword("LOCAL"); + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + if local && !temporary { + return Err(p.expected("TEMPORARY after LOCAL")); + } + if or_replace && p.at_keyword("FOREIGN") { + return Err(p.expected("TABLE")); + } + let unlogged = p.eat_keyword("UNLOGGED"); + let foreign = p.eat_keyword("FOREIGN"); + p.expect_keyword("TABLE")?; + let flags = CreateFlags { + or_replace, + temporary, + }; + let create = parse_table(p, flags, local, unlogged, foreign)?; + if create.is_plain() { + return Ok(StatementKind::CreateTable(Box::new(create.table)).into()); + } + Ok(statement(PostgresStatement::CreateTable(Box::new(create)))) +} + +/// Parses what follows `CREATE ... TABLE`. +fn parse_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, + local: bool, + unlogged: bool, + foreign: bool, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let partition_of = if p.at_keyword("PARTITION") && p.peek_nth(1).is_word("OF") { + p.advance(); + p.advance(); + Some(grammar::parse_object_name(p)?) + } else { + None + }; + + let mut columns = Vec::new(); + let mut constraints = Vec::new(); + let mut likes = Vec::new(); + let mut partition_columns = Vec::new(); + let mut has_elements = false; + if p.eat_op("(") { + has_elements = true; + if !p.at_op(")") { + loop { + if let Some(constraint) = D::parse_table_constraint(p)? { + constraints.push(constraint); + } else if p.at_keyword("LIKE") { + likes.push(parse_like(p, columns.len())?); + } else if partition_of.is_some() { + partition_columns.push(parse_partition_column(p)?); + } else { + columns.push(D::parse_column_def(p)?); + } + if !p.eat_op(",") { + break; + } + } + } + p.expect_op(")")?; + } + + let inherits = if p.eat_keyword("INHERITS") { + p.expect_op("(")?; + let parents = p.parse_comma_separated(grammar::parse_object_name)?; + p.expect_op(")")?; + parents + } else { + Vec::new() + }; + if partition_of.is_some() && !inherits.is_empty() { + return Err(p.expected("FOR VALUES or DEFAULT before any INHERITS")); + } + let bound = if partition_of.is_some() { + Some(parse_partition_bound(p)?) + } else { + None + }; + let partition_by = if p.at_keyword("PARTITION") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + Some(Box::new(p.parse_expr()?)) + } else { + None + }; + let with = crate::dialect::postgres::parse_storage_parameters(p)?; + let on_commit = if p.at_keyword("ON") && p.peek_nth(1).is_word("COMMIT") { + p.advance(); + p.advance(); + Some(parse_on_commit(p)?) + } else { + None + }; + let (server, options) = if p.eat_keyword("SERVER") { + let server = p.parse_ident()?; + (Some(server), parse_generic_options(p)?) + } else { + (None, Vec::new()) + }; + if foreign && server.is_none() { + return Err(p.expected("SERVER")); + } + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_create_table_query(p)?)) + } else { + None + }; + if !has_elements && partition_of.is_none() && query.is_none() { + return Err(p.expected("column definitions or AS")); + } + + Ok(PostgresCreateTable { + table: CreateTable { + or_replace: flags.or_replace, + temporary: flags.temporary, + name, + if_not_exists, + columns, + constraints, + query, + }, + local, + unlogged, + foreign, + partition_of, + has_elements, + likes, + partition_columns, + inherits, + bound, + partition_by, + with, + on_commit: on_commit.map(Cow::Borrowed), + server, + options, + }) +} + +fn parse_like<'a, D: Dialect>( + p: &mut Parser<'a, D>, + position: usize, +) -> PResult> { + p.advance(); + let source = grammar::parse_object_name(p)?; + let mut options = Vec::new(); + while p.at_keyword("INCLUDING") || p.at_keyword("EXCLUDING") { + let including = p.at_keyword("INCLUDING"); + p.advance(); + options.push((including, p.parse_ident()?)); + } + Ok(TableLike { + source, + options, + position, + }) +} + +fn parse_partition_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let with_options = p.at_keyword("WITH") && p.peek_nth(1).is_word("OPTIONS"); + if with_options { + p.advance(); + p.advance(); + } + let mut options = Vec::new(); + while let Some(option) = D::parse_column_option(p)? { + options.push(option); + } + Ok(PartitionColumn { + name, + with_options, + options, + }) +} + +fn parse_on_commit<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'static str> { + if p.eat_keyword("DROP") { + return Ok("DROP"); + } + if p.eat_keyword("DELETE") { + p.expect_keyword("ROWS")?; + return Ok("DELETE ROWS"); + } + p.expect_keyword("PRESERVE")?; + p.expect_keyword("ROWS")?; + Ok("PRESERVE ROWS") +} + +/// Parses a partition's bound: `DEFAULT` or `FOR VALUES ...`. +pub fn parse_partition_bound<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("DEFAULT") { + return Ok(PartitionBound::Default); + } + p.expect_keyword("FOR")?; + p.expect_keyword("VALUES")?; + if p.eat_keyword("IN") { + p.expect_op("(")?; + let values = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + return Ok(PartitionBound::In(values)); + } + if p.eat_keyword("FROM") { + let from = parse_range_bounds(p)?; + p.expect_keyword("TO")?; + let to = parse_range_bounds(p)?; + return Ok(PartitionBound::Range { from, to }); + } + p.expect_keyword("WITH")?; + p.expect_op("(")?; + p.expect_keyword("MODULUS")?; + let modulus = grammar::parse_number_text(p)?; + p.expect_op(",")?; + p.expect_keyword("REMAINDER")?; + let remainder = grammar::parse_number_text(p)?; + p.expect_op(")")?; + Ok(PartitionBound::Hash { + modulus: modulus.into(), + remainder: remainder.into(), + }) +} + +fn parse_range_bounds<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + let bounds = p.parse_comma_separated(|p| { + Ok(if p.eat_keyword("MINVALUE") { + RangeBound::MinValue + } else if p.eat_keyword("MAXVALUE") { + RangeBound::MaxValue + } else { + RangeBound::Value(p.parse_expr()?) + }) + })?; + p.expect_op(")")?; + Ok(bounds) +} + +/// Parses a table constraint, adding `EXCLUDE` and `[CONSTRAINT n] NOT NULL`. +pub fn parse_table_constraint<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let named = p.at_keyword("CONSTRAINT"); + let offset = if named { 2 } else { 0 }; + let word = p.peek_nth(offset); + let exclude = word.is_word("EXCLUDE") + && (p.peek_nth(offset + 1).is_op("(") || p.peek_nth(offset + 1).is_word("USING")); + let not_null = word.is_word("NOT") && p.peek_nth(offset + 1).is_word("NULL"); + if !exclude && !not_null { + return grammar::parse_table_constraint(p); + } + let name = if named { + p.advance(); + Some(p.parse_ident()?) + } else { + None + }; + let kind = if exclude { + p.advance(); + let using = if p.eat_keyword("USING") { + Some(p.parse_ident()?) + } else { + None + }; + p.expect_op("(")?; + let elements = p.parse_comma_separated(parse_exclude_element)?; + p.expect_op(")")?; + TableConstraintKind::Exclude(Box::new(ExcludeConstraint { + using, + elements, + predicate: None, + })) + } else { + p.advance(); + p.advance(); + TableConstraintKind::NotNull(p.parse_ident()?) + }; + let include = if p.eat_keyword("INCLUDE") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let kind = match kind { + TableConstraintKind::Exclude(mut exclude) => { + if p.eat_keyword("WHERE") { + p.expect_op("(")?; + exclude.predicate = Some(p.parse_expr()?); + p.expect_op(")")?; + } + TableConstraintKind::Exclude(exclude) + } + other => other, + }; + let mut attributes: Vec = Vec::new(); + while let Some(attribute) = grammar::parse_constraint_attribute(p)? { + attributes.push(attribute); + } + grammar::check_constraint_attributes(p, attributes.iter().copied())?; + if matches!(kind, TableConstraintKind::NotNull(_)) + && attributes.iter().any(|attribute| { + !matches!( + attribute, + ConstraintAttribute::NoInherit | ConstraintAttribute::NotValid + ) + }) + { + return Err(p.expected("NO INHERIT or NOT VALID after NOT NULL")); + } + Ok(Some(TableConstraint { + name, + kind, + include, + nulls_distinct: None, + attributes, + })) +} + +fn parse_exclude_element<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let column = D::parse_index_column(p)?; + p.expect_keyword("WITH")?; + let operator = if p.at_keyword("OPERATOR") && p.peek_nth(1).is_op("(") { + p.advance(); + p.advance(); + let operator = parse_operator_name(p)?; + p.expect_op(")")?; + ExcludeOperator::Qualified(operator) + } else { + let token = p.expect_kind(TokenKind::Op, "an operator")?; + ExcludeOperator::Plain(token.text.into()) + }; + Ok(ExcludeElement { column, operator }) +} + +/// Parses `ALTER {MATERIALIZED VIEW | FOREIGN TABLE} ...`, with the cursor on +/// the first keyword of the kind. +pub fn parse_alter_relation<'a, D: Dialect>( + p: &mut Parser<'a, D>, + keyword: &'static str, +) -> PResult> { + for _ in keyword.split(' ') { + p.advance(); + } + let if_exists = p.at_keyword("IF") && p.peek_nth(1).is_word("EXISTS"); + if if_exists { + p.advance(); + p.advance(); + } + let only = D::parse_alter_table_only(p); + let name = grammar::parse_object_name(p)?; + let operations = p.parse_comma_separated(D::parse_alter_table_op)?; + Ok(PostgresStatement::AlterRelation { + keyword: keyword.into(), + alter: Box::new(AlterTable { + if_exists, + only, + name, + operations, + }), + }) +} + +/// Parses `ALTER` table operations only PostgreSQL has, or returns `None`. +pub fn parse_alter_table_op_extra<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let next = p.peek_nth(1); + if p.at_keyword("ATTACH") && next.is_word("PARTITION") { + p.advance(); + p.advance(); + let name = grammar::parse_object_name(p)?; + let bound = parse_partition_bound(p)?; + return Ok(Some(AlterTableOp::AttachPartition { name, bound })); + } + if p.at_keyword("DETACH") && next.is_word("PARTITION") { + p.advance(); + p.advance(); + let name = grammar::parse_object_name(p)?; + let mode = ["CONCURRENTLY", "FINALIZE"] + .into_iter() + .find(|word| p.eat_keyword(word)); + return Ok(Some(AlterTableOp::DetachPartition { + name, + mode: mode.map(Cow::Borrowed), + })); + } + if p.at_keyword("INHERIT") { + p.advance(); + let name = grammar::parse_object_name(p)?; + return Ok(Some(AlterTableOp::PhraseObject { + phrase: "INHERIT".into(), + name, + })); + } + if p.at_keyword("NO") && next.is_word("INHERIT") { + p.advance(); + p.advance(); + let name = grammar::parse_object_name(p)?; + return Ok(Some(AlterTableOp::PhraseObject { + phrase: "NO INHERIT".into(), + name, + })); + } + if p.at_keyword("OPTIONS") && next.is_op("(") { + return Ok(Some(AlterTableOp::GenericOptions(parse_generic_options( + p, + )?))); + } + if p.at_keyword("RESET") && next.is_op("(") { + p.advance(); + p.advance(); + let names = p.parse_comma_separated(|p| { + let mut parts = vec![p.parse_name_part()?]; + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + Ok(ObjectName { parts }) + })?; + p.expect_op(")")?; + return Ok(Some(AlterTableOp::ResetOptions(names))); + } + if p.at_keyword("SET") && next.is_word("SCHEMA") { + p.advance(); + p.advance(); + let name = p.parse_ident()?; + return Ok(Some(AlterTableOp::PhraseName { + phrase: "SET SCHEMA".into(), + name, + })); + } + if p.at_keyword("ALTER") { + let column_keyword = next.is_word("COLUMN"); + let name_at = if column_keyword { 2 } else { 1 }; + if p.peek_nth(name_at + 1).is_word("OPTIONS") { + p.advance(); + if column_keyword { + p.advance(); + } + let name = p.parse_ident()?; + return Ok(Some(AlterTableOp::AlterColumn { + column_keyword, + name, + action: AlterColumnAction::GenericOptions(parse_generic_options(p)?), + })); + } + } + Ok(None) +} + +impl fmt::Display for TableLike<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "LIKE {}", self.source)?; + for (including, option) in &self.options { + write!( + f, + " {} {option}", + if *including { "INCLUDING" } else { "EXCLUDING" } + )?; + } + Ok(()) + } +} + +impl fmt::Display for PartitionColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + for option in &self.options { + write!(f, " {option}")?; + } + Ok(()) + } +} + +/// The comma-separated contents of `CREATE TABLE ( ... )`. +struct TableElements<'s, 'a>(&'s PostgresCreateTable<'a>); + +impl fmt::Display for TableElements<'_, '_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let this = self.0; + let mut first = true; + let mut separate = |f: &mut fmt::Formatter<'_>| -> fmt::Result { + if !std::mem::take(&mut first) { + f.write_str(",")?; + SpaceOrNewline.fmt(f)?; + } + Ok(()) + }; + let mut likes = this.likes.iter().peekable(); + for (i, column) in this.table.columns.iter().enumerate() { + while let Some(like) = likes.next_if(|like| like.position == i) { + separate(f)?; + write!(f, "{like}")?; + } + separate(f)?; + write!(f, "{column}")?; + } + for like in likes { + separate(f)?; + write!(f, "{like}")?; + } + for column in &this.partition_columns { + separate(f)?; + write!(f, "{column}")?; + } + for constraint in &this.table.constraints { + separate(f)?; + write!(f, "{constraint}")?; + } + Ok(()) + } +} + +impl fmt::Display for PostgresCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + f.write_str("CREATE ")?; + if table.or_replace { + f.write_str("OR REPLACE ")?; + } + if self.local { + f.write_str("LOCAL ")?; + } + if table.temporary { + f.write_str("TEMPORARY ")?; + } + if self.unlogged { + f.write_str("UNLOGGED ")?; + } + if self.foreign { + f.write_str("FOREIGN ")?; + } + f.write_str("TABLE ")?; + if table.if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + table.name.fmt(f)?; + if let Some(parent) = &self.partition_of { + write!(f, " PARTITION OF {parent}")?; + } + if self.has_elements { + f.write_str(" (")?; + // A list of only `LIKE` stays on one line, as in the original. + if table.columns.is_empty() + && self.partition_columns.is_empty() + && table.constraints.is_empty() + { + write!(f, "{}", TableElements(self))?; + } else { + NewLine.fmt(f)?; + Indent(TableElements(self)).fmt(f)?; + NewLine.fmt(f)?; + } + f.write_str(")")?; + } + if !self.inherits.is_empty() { + write!(f, " INHERITS ({})", comma(&self.inherits))?; + } + if let Some(bound) = &self.bound { + write!(f, " {bound}")?; + } + if let Some(partition_by) = &self.partition_by { + write!(f, " PARTITION BY {partition_by}")?; + } + if !self.with.is_empty() { + f.write_str(" WITH ")?; + write_storage(f, &self.with)?; + } + if let Some(ref on_commit) = self.on_commit { + write!(f, " ON COMMIT {on_commit}")?; + } + if let Some(server) = &self.server { + write!(f, " SERVER {server}")?; + } + if !self.options.is_empty() { + f.write_str(" ")?; + ddl::write_options(f, &self.options)?; + } + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} diff --git a/sqlparser_v2/src/dialect/postgres/utility.rs b/sqlparser_v2/src/dialect/postgres/utility.rs new file mode 100644 index 0000000000..c38ee86488 --- /dev/null +++ b/sqlparser_v2/src/dialect/postgres/utility.rs @@ -0,0 +1,1130 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `COPY`, cursors, `LOCK`, prepared statements and other utility statements. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + DataType, Expr, ExprKind, Ident, Literal, ObjectName, Query, Statement, StatementKind, + StringLiteral, +}; +use crate::dialect::postgres::PostgresStatement; +use crate::dialect::postgres::ddl::{statement, write_behavior}; +use crate::dialect::{Builtin, Dialect}; +use crate::display::comma; +use crate::grammar; +use crate::lexer::{Token, TokenKind}; +use crate::parser::Parser; + +/// The source of `COPY`: a table with optional columns, or a query. +#[derive(Debug, Clone, PartialEq)] +pub enum CopySource<'a> { + Table { + name: ObjectName<'a>, + columns: Vec>, + }, + Query(Box>), +} + +/// Where `COPY` reads or writes. +#[derive(Debug, Clone, PartialEq)] +pub enum CopyTarget<'a> { + Stdin, + Stdout, + Program(StringLiteral<'a>), + File(StringLiteral<'a>), +} + +/// One `(option value)` of the modern `COPY` option list. +#[derive(Debug, Clone, PartialEq)] +pub enum CopyOption<'a> { + Format(Ident<'a>), + Freeze(Option), + Delimiter(StringLiteral<'a>), + Null(StringLiteral<'a>), + Header(Option), + Quote(StringLiteral<'a>), + Escape(StringLiteral<'a>), + ForceQuote(Vec>), + ForceNotNull(Vec>), + ForceNull(Vec>), + Encoding(StringLiteral<'a>), +} + +/// A keyword option of the legacy `COPY` syntax. Redshift's are of this form too. +#[derive(Debug, Clone, PartialEq)] +pub struct CopyLegacyOption<'a> { + pub keyword: Cow<'a, str>, + pub value: CopyLegacyValue<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CopyLegacyValue<'a> { + None, + /// The word `DEFAULT` in place of a string. + Default, + String(StringLiteral<'a>), + Number(Cow<'a, str>), + /// `FORCE NOT NULL a, b` or `FORCE QUOTE a`. + Force { + not_null: bool, + columns: Vec>, + }, + /// An optional `PRESET` and a boolean word such as `ON`. + Toggle { + preset: bool, + word: Option>, + }, +} + +/// What a legacy option takes after its keyword. +#[derive(Clone, Copy)] +pub enum CopyLegacyKind { + Flag, + /// `[AS] 'text'` + String, + /// `[AS] 'text'` or `DEFAULT`. + StringOrDefault, + /// `[AS] 'text'`, or nothing. + OptionalString, + /// `[AS] n` + Number, + /// `[PRESET] [TRUE | FALSE | ON | OFF]` + Toggle, + /// `[NOT NULL | QUOTE] a, b`, after `FORCE`. + Force, +} + +/// The legacy options PostgreSQL has, shared with Redshift. +pub const LEGACY_OPTIONS: &[(&str, CopyLegacyKind)] = &[ + ("BINARY", CopyLegacyKind::Flag), + ("DELIMITER", CopyLegacyKind::String), + ("NULL", CopyLegacyKind::String), + ("CSV", CopyLegacyKind::Flag), + ("HEADER", CopyLegacyKind::Flag), + ("QUOTE", CopyLegacyKind::String), + ("ESCAPE", CopyLegacyKind::String), + ("FORCE", CopyLegacyKind::Force), + ("CREDENTIALS", CopyLegacyKind::String), + ("IAM_ROLE", CopyLegacyKind::String), +]; + +/// `COPY ... FROM STDIN` data that follows the statement. +#[derive(Debug, Clone, PartialEq)] +pub struct CopyPayload<'a> { + pub data: Cow<'a, str>, + /// True if the `\.` terminator was present. + pub terminated: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Copy<'a> { + pub source: CopySource<'a>, + /// True for `TO`, false for `FROM`. + pub to: bool, + pub target: CopyTarget<'a>, + /// True if `WITH` was written before the option list. + pub with: bool, + pub options: Vec>, + pub legacy_options: Vec>, + pub payload: Option>, +} + +/// A table named by `TRUNCATE` or `LOCK`. +#[derive(Debug, Clone, PartialEq)] +pub struct TableItem<'a> { + pub only: bool, + pub name: ObjectName<'a>, + /// True if `*` followed the name. + pub star: bool, +} + +/// `TRUNCATE` with clauses the core does not have. +#[derive(Debug, Clone, PartialEq)] +pub struct PostgresTruncate<'a> { + pub table_keyword: bool, + pub tables: Vec>, + /// `Some(true)` for `RESTART IDENTITY`, `Some(false)` for `CONTINUE IDENTITY`. + pub identity: Option, + pub behavior: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DeclareCursor<'a> { + pub name: Ident<'a>, + pub binary: bool, + /// `ASENSITIVE` or `INSENSITIVE`. + pub sensitivity: Option>, + /// `Some(true)` for `SCROLL`, `Some(false)` for `NO SCROLL`. + pub scroll: Option, + /// `Some(true)` for `WITH HOLD`, `Some(false)` for `WITHOUT HOLD`. + pub hold: Option, + pub query: Box>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FetchDirection<'a> { + Next, + Prior, + First, + Last, + All, + Count(Cow<'a, str>), + Absolute(Cow<'a, str>), + Relative(Cow<'a, str>), + Forward(Option>), + ForwardAll, + Backward(Option>), + BackwardAll, +} + +/// `FETCH direction {IN | FROM} cursor [INTO target]` +#[derive(Debug, Clone, PartialEq)] +pub struct FetchStatement<'a> { + pub direction: FetchDirection<'a>, + pub position: Cow<'a, str>, + pub cursor: Ident<'a>, + pub into: Option>, +} + +/// `LOCK [TABLE] tables [IN mode MODE] [NOWAIT]` +#[derive(Debug, Clone, PartialEq)] +pub struct LockStatement<'a> { + pub table_keyword: bool, + pub tables: Vec>, + pub mode: Option>, + pub nowait: bool, +} + +/// `PREPARE name [(types)] AS statement` +#[derive(Debug, Clone, PartialEq)] +pub struct PrepareStatement<'a> { + pub name: Ident<'a>, + pub types: Vec>, + pub statement: Box>, +} + +/// `EXECUTE name [(args)] [USING values]` +#[derive(Debug, Clone, PartialEq)] +pub struct ExecuteStatement<'a> { + pub name: Ident<'a>, + pub args: Option>>, + pub using: Vec>, +} + +/// An item of a `DO` statement. +#[derive(Debug, Clone, PartialEq)] +pub enum DoItem<'a> { + Language(Ident<'a>), + Body(Literal<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct AnalyzeTable<'a> { + pub name: ObjectName<'a>, + pub columns: Vec>, +} + +// Parsing + +fn is_name_word(p: &Parser<'_, D>, token: Token<'_>) -> bool { + p.at_ident() && matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +fn parse_paren_idents<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + grammar::parse_ident_list(p) +} + +fn parse_copy_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("FORMAT") { + return p.parse_name_part().map(CopyOption::Format); + } + if p.eat_keyword("FREEZE") { + return Ok(CopyOption::Freeze(parse_optional_bool(p))); + } + if p.eat_keyword("DELIMITER") { + return grammar::parse_string(p).map(CopyOption::Delimiter); + } + if p.eat_keyword("NULL") { + return grammar::parse_string(p).map(CopyOption::Null); + } + if p.eat_keyword("HEADER") { + return Ok(CopyOption::Header(parse_optional_bool(p))); + } + if p.eat_keyword("QUOTE") { + return grammar::parse_string(p).map(CopyOption::Quote); + } + if p.eat_keyword("ESCAPE") { + return grammar::parse_string(p).map(CopyOption::Escape); + } + if p.eat_keyword("FORCE_QUOTE") { + return parse_paren_idents(p).map(CopyOption::ForceQuote); + } + if p.eat_keyword("FORCE_NOT_NULL") { + return parse_paren_idents(p).map(CopyOption::ForceNotNull); + } + if p.eat_keyword("FORCE_NULL") { + return parse_paren_idents(p).map(CopyOption::ForceNull); + } + if p.eat_keyword("ENCODING") { + return grammar::parse_string(p).map(CopyOption::Encoding); + } + Err(p.expected("a COPY option")) +} + +fn parse_optional_bool(p: &mut Parser<'_, D>) -> Option { + if p.eat_keyword("TRUE") { + Some(true) + } else if p.eat_keyword("FALSE") { + Some(false) + } else { + None + } +} + +fn parse_legacy_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, + kind: CopyLegacyKind, +) -> PResult> { + match kind { + CopyLegacyKind::Flag => Ok(CopyLegacyValue::None), + CopyLegacyKind::String => { + p.eat_keyword("AS"); + grammar::parse_string(p).map(CopyLegacyValue::String) + } + CopyLegacyKind::StringOrDefault => { + p.eat_keyword("AS"); + if p.eat_keyword("DEFAULT") { + return Ok(CopyLegacyValue::Default); + } + grammar::parse_string(p).map(CopyLegacyValue::String) + } + CopyLegacyKind::OptionalString => { + p.eat_keyword("AS"); + if p.peek().kind == TokenKind::String { + grammar::parse_string(p).map(CopyLegacyValue::String) + } else { + Ok(CopyLegacyValue::None) + } + } + CopyLegacyKind::Number => { + p.eat_keyword("AS"); + grammar::parse_number_text(p).map(|v| CopyLegacyValue::Number(v.into())) + } + CopyLegacyKind::Toggle => { + let preset = p.eat_keyword("PRESET"); + let word = ["TRUE", "FALSE", "ON", "OFF"] + .into_iter() + .find(|word| p.eat_keyword(word)); + Ok(CopyLegacyValue::Toggle { + preset, + word: word.map(Cow::Borrowed), + }) + } + CopyLegacyKind::Force => { + let not_null = p.eat_keyword("NOT"); + if not_null { + p.expect_keyword("NULL")?; + } else { + p.expect_keyword("QUOTE")?; + } + let columns = p.parse_comma_separated(Parser::parse_ident)?; + Ok(CopyLegacyValue::Force { not_null, columns }) + } + } +} + +/// Parses legacy options drawn from `table`, until something else. +pub fn parse_legacy_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, + table: &[(&'static str, CopyLegacyKind)], +) -> PResult>> { + let mut options = Vec::new(); + loop { + // `FORMAT [AS]` before an option carries no meaning of its own. + if p.at_keyword("FORMAT") && table.iter().any(|(word, _)| *word == "PARQUET") { + p.advance(); + p.eat_keyword("AS"); + } + let token = p.peek(); + let Some((keyword, kind)) = table + .iter() + .find(|(word, _)| token.kind == TokenKind::Word && token.is_word(word)) + else { + break; + }; + p.advance(); + let value = parse_legacy_value(p, *kind)?; + options.push(CopyLegacyOption { + keyword: (*keyword).into(), + value, + }); + } + Ok(options) +} + +/// Parses `COPY ...`, with the cursor on the source, and any `COPY` data. +pub fn parse_copy<'a, D: Dialect>( + p: &mut Parser<'a, D>, + legacy: &[(&'static str, CopyLegacyKind)], +) -> PResult> { + p.expect_keyword("COPY")?; + let source = if p.eat_op("(") { + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + CopySource::Query(Box::new(query)) + } else { + let name = grammar::parse_object_name(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + CopySource::Table { name, columns } + }; + let to = if p.eat_keyword("TO") { + true + } else { + p.expect_keyword("FROM")?; + false + }; + if !to && matches!(source, CopySource::Query(_)) { + return Err(p.expected("TO after a query")); + } + let target = if p.eat_keyword("STDIN") { + CopyTarget::Stdin + } else if p.eat_keyword("STDOUT") { + CopyTarget::Stdout + } else if p.eat_keyword("PROGRAM") { + CopyTarget::Program(grammar::parse_string(p)?) + } else { + CopyTarget::File(grammar::parse_string(p)?) + }; + let with = p.eat_keyword("WITH"); + let options = if p.eat_op("(") { + let options = p.parse_comma_separated(parse_copy_option)?; + p.expect_op(")")?; + options + } else { + Vec::new() + }; + let legacy_options = parse_legacy_options(p, legacy)?; + let payload = parse_copy_payload(p); + Ok(statement(PostgresStatement::Copy(Box::new(Copy { + source, + to, + target, + with, + options, + legacy_options, + payload, + })))) +} + +/// Consumes the payload token, if the lexer made one, leaving the `;` for +/// the statement separator. +fn parse_copy_payload<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option> { + if p.peek().kind != TokenKind::DialectLiteral { + return None; + } + let text = p.advance().text; + Some(match text.strip_suffix("\\.") { + Some(data) => CopyPayload { + data: data.into(), + terminated: true, + }, + None => match text + .strip_suffix("\\.\n") + .or_else(|| text.strip_suffix("\\.\r\n")) + { + Some(data) => CopyPayload { + data: data.into(), + terminated: true, + }, + None => CopyPayload { + data: text.into(), + terminated: false, + }, + }, + }) +} + +fn parse_table_items<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.parse_comma_separated(|p| { + let only = p.eat_keyword("ONLY"); + let name = grammar::parse_object_name(p)?; + let star = !only && p.eat_op("*"); + Ok(TableItem { only, name, star }) + }) +} + +/// Parses `TRUNCATE` and its clauses. +pub fn parse_truncate<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("TRUNCATE")?; + let table_keyword = p.eat_keyword("TABLE"); + let tables = parse_table_items(p)?; + let identity = if p.eat_keyword("RESTART") { + p.expect_keyword("IDENTITY")?; + Some(true) + } else if p.eat_keyword("CONTINUE") { + p.expect_keyword("IDENTITY")?; + Some(false) + } else { + None + }; + let behavior = if p.eat_keyword("CASCADE") { + Some(crate::ast::DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(crate::ast::DropBehavior::Restrict) + } else { + None + }; + if identity.is_none() && behavior.is_none() && tables.iter().all(|t| !t.only && !t.star) { + return Ok(StatementKind::Truncate(Box::new(crate::ast::Truncate { + table_keyword, + if_exists: false, + names: tables.into_iter().map(|t| t.name).collect(), + })) + .into()); + } + Ok(statement(PostgresStatement::Truncate(Box::new( + PostgresTruncate { + table_keyword, + tables, + identity, + behavior, + }, + )))) +} + +fn parse_declare<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let name = p.parse_ident()?; + let binary = p.eat_keyword("BINARY"); + let sensitivity = ["ASENSITIVE", "INSENSITIVE"] + .into_iter() + .find(|word| p.eat_keyword(word)); + let scroll = if p.eat_keyword("SCROLL") { + Some(true) + } else if p.at_keyword("NO") && p.peek_nth(1).is_word("SCROLL") { + p.advance(); + p.advance(); + Some(false) + } else { + None + }; + p.expect_keyword("CURSOR")?; + let hold = if p.eat_keyword("WITH") { + p.expect_keyword("HOLD")?; + Some(true) + } else if p.eat_keyword("WITHOUT") { + p.expect_keyword("HOLD")?; + Some(false) + } else { + None + }; + p.expect_keyword("FOR")?; + let query = D::parse_query(p)?; + Ok(PostgresStatement::Declare(Box::new(DeclareCursor { + name, + binary, + sensitivity: sensitivity.map(Cow::Borrowed), + scroll, + hold, + query: Box::new(query), + }))) +} + +fn parse_fetch<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let direction = if p.eat_keyword("NEXT") { + FetchDirection::Next + } else if p.eat_keyword("PRIOR") { + FetchDirection::Prior + } else if p.eat_keyword("FIRST") { + FetchDirection::First + } else if p.eat_keyword("LAST") { + FetchDirection::Last + } else if p.eat_keyword("ALL") { + FetchDirection::All + } else if p.eat_keyword("ABSOLUTE") { + FetchDirection::Absolute(grammar::parse_number_text(p)?.into()) + } else if p.eat_keyword("RELATIVE") { + FetchDirection::Relative(grammar::parse_number_text(p)?.into()) + } else if p.at_keyword("FORWARD") || p.at_keyword("BACKWARD") { + let forward = p.at_keyword("FORWARD"); + p.advance(); + if p.eat_keyword("ALL") { + if forward { + FetchDirection::ForwardAll + } else { + FetchDirection::BackwardAll + } + } else { + let count = if p.peek().kind == TokenKind::Number { + Some(grammar::parse_number_text(p)?) + } else { + None + }; + if forward { + FetchDirection::Forward(count.map(Cow::Borrowed)) + } else { + FetchDirection::Backward(count.map(Cow::Borrowed)) + } + } + } else { + FetchDirection::Count(grammar::parse_number_text(p)?.into()) + }; + let position = if p.eat_keyword("IN") { + "IN" + } else { + p.expect_keyword("FROM")?; + "FROM" + }; + let cursor = p.parse_ident()?; + let into = if p.eat_keyword("INTO") { + Some(grammar::parse_object_name(p)?) + } else { + None + }; + Ok(PostgresStatement::Fetch(Box::new(FetchStatement { + direction, + position: position.into(), + cursor, + into, + }))) +} + +fn parse_lock<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let table_keyword = p.eat_keyword("TABLE"); + let tables = parse_table_items(p)?; + let mode = if p.eat_keyword("IN") { + const MODES: [(&str, &[&str]); 8] = [ + ("ACCESS SHARE", &["ACCESS", "SHARE"]), + ("ROW SHARE", &["ROW", "SHARE"]), + ("ROW EXCLUSIVE", &["ROW", "EXCLUSIVE"]), + ("SHARE UPDATE EXCLUSIVE", &["SHARE", "UPDATE", "EXCLUSIVE"]), + ("SHARE ROW EXCLUSIVE", &["SHARE", "ROW", "EXCLUSIVE"]), + ("SHARE", &["SHARE"]), + ("EXCLUSIVE", &["EXCLUSIVE"]), + ("ACCESS EXCLUSIVE", &["ACCESS", "EXCLUSIVE"]), + ]; + let found = MODES.into_iter().find(|(_, words)| { + words + .iter() + .enumerate() + .all(|(i, word)| p.peek_nth(i).is_word(word)) + }); + let Some((mode, words)) = found else { + return Err(p.expected("a lock mode")); + }; + for _ in words { + p.advance(); + } + p.expect_keyword("MODE")?; + Some(mode) + } else { + None + }; + let nowait = p.eat_keyword("NOWAIT"); + Ok(PostgresStatement::Lock(Box::new(LockStatement { + table_keyword, + tables, + mode: mode.map(Cow::Borrowed), + nowait, + }))) +} + +/// Parses `PREPARE`, `EXECUTE` or `DEALLOCATE`, or returns `None` at anything +/// else. DuckDB shares these with PostgreSQL. +pub fn parse_prepared_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let token = p.peek(); + let parsed = if token.is_word("PREPARE") { + parse_prepare(p)? + } else if token.is_word("EXECUTE") { + parse_execute(p)? + } else if token.is_word("DEALLOCATE") { + parse_deallocate(p)? + } else { + return Ok(None); + }; + Ok(Some(parsed)) +} + +fn parse_prepare<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let name = p.parse_ident()?; + let types = if p.eat_op("(") { + let types = p.parse_comma_separated(D::parse_data_type)?; + p.expect_op(")")?; + types + } else { + Vec::new() + }; + p.expect_keyword("AS")?; + let inner = p.nested(Parser::parse_statement)?; + Ok(PostgresStatement::Prepare(Box::new(PrepareStatement { + name, + types, + statement: Box::new(inner), + }))) +} + +fn parse_execute<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let name = p.parse_ident()?; + let args = if p.eat_op("(") { + let args = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op(")")?; + Some(args) + } else { + None + }; + let using = if p.eat_keyword("USING") { + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + Ok(PostgresStatement::Execute(Box::new(ExecuteStatement { + name, + args, + using, + }))) +} + +fn parse_deallocate<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let prepare = p.eat_keyword("PREPARE"); + let name = if p.eat_keyword("ALL") { + None + } else { + Some(p.parse_ident()?) + }; + Ok(PostgresStatement::Deallocate { prepare, name }) +} + +fn parse_do<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let mut items = Vec::new(); + loop { + if p.at_keyword("LANGUAGE") { + p.advance(); + items.push(DoItem::Language(p.parse_ident()?)); + } else if matches!(p.peek().kind, TokenKind::String | TokenKind::DollarString) { + items.push(DoItem::Body(match p.parse_expr()?.kind { + ExprKind::Literal(literal) => literal, + _ => return Err(p.expected("a string")), + })); + } else { + break; + } + } + if items.is_empty() { + return Err(p.expected("LANGUAGE or a string")); + } + Ok(PostgresStatement::Do(items)) +} + +fn parse_analyze<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let verbose = p.eat_keyword("VERBOSE"); + let tables = if is_name_word(p, p.peek()) { + p.parse_comma_separated(|p| { + let name = grammar::parse_object_name(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + Ok(AnalyzeTable { name, columns }) + })? + } else { + Vec::new() + }; + Ok(PostgresStatement::Analyze { verbose, tables }) +} + +fn parse_notify<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let channel = p.parse_ident()?; + let payload = if p.eat_op(",") { + Some(grammar::parse_string(p)?) + } else { + None + }; + Ok(PostgresStatement::Notify { channel, payload }) +} + +/// Parses `RESET name`, `RESET ALL` or `RESET SESSION AUTHORIZATION`. +pub fn parse_reset<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + use crate::dialect::postgres::ResetTarget; + p.expect_keyword("RESET")?; + let target = if p.eat_keyword("ALL") { + ResetTarget::All + } else if p.at_keyword("SESSION") && p.peek_nth(1).is_word("AUTHORIZATION") { + p.advance(); + p.advance(); + ResetTarget::SessionAuthorization + } else { + ResetTarget::Name(grammar::parse_object_name(p)?) + }; + Ok(PostgresStatement::Reset(target)) +} + +/// Parses `CLOSE name` or `CLOSE ALL`. +pub fn parse_close<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CLOSE")?; + if p.eat_keyword("ALL") { + return Ok(PostgresStatement::Close(None)); + } + Ok(PostgresStatement::Close(Some(p.parse_ident()?))) +} + +/// Parses the statements in this module, or returns `None` at something else. +pub fn parse_utility<'a, D: Dialect>( + p: &mut Parser<'a, D>, + legacy: &[(&'static str, CopyLegacyKind)], +) -> PResult>> { + let token = p.peek(); + if token.kind != TokenKind::Word { + return Ok(None); + } + let statement_of = |parsed: PostgresStatement<'a>| statement(parsed); + if token.is_word("COPY") { + return parse_copy(p, legacy).map(Some); + } + if token.is_word("TRUNCATE") { + return parse_truncate(p).map(Some); + } + let parsed = if token.is_word("DECLARE") { + parse_declare(p)? + } else if token.is_word("FETCH") { + parse_fetch(p)? + } else if token.is_word("LOCK") { + parse_lock(p)? + } else if let Some(prepared) = parse_prepared_statement(p)? { + prepared + } else if token.is_word("DO") { + parse_do(p)? + } else if token.is_word("ANALYZE") { + parse_analyze(p)? + } else if token.is_word("NOTIFY") { + parse_notify(p)? + } else if token.is_word("LISTEN") { + p.advance(); + PostgresStatement::Listen(p.parse_ident()?) + } else if token.is_word("DISCARD") { + p.advance(); + let target = p.peek(); + if !["ALL", "PLANS", "SEQUENCES", "TEMP", "TEMPORARY"] + .iter() + .any(|word| target.is_word(word)) + { + return Err(p.expected("ALL, PLANS, SEQUENCES, TEMP or TEMPORARY")); + } + p.advance(); + PostgresStatement::Discard(target.text.into()) + } else if token.is_word("RESET") { + parse_reset(p)? + } else if token.is_word("CLOSE") { + parse_close(p)? + } else if token.is_word("LOAD") && p.peek_nth(1).kind == TokenKind::String { + p.advance(); + PostgresStatement::Load(grammar::parse_string(p)?) + } else if token.is_word("UNLISTEN") { + p.advance(); + PostgresStatement::Unlisten(if p.eat_op("*") { + None + } else { + Some(p.parse_ident()?) + }) + } else { + return Ok(None); + }; + Ok(Some(statement_of(parsed))) +} + +impl fmt::Display for CopyOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let flag = |f: &mut fmt::Formatter<'_>, word: &str, value: &Option| match value { + Some(false) => write!(f, "{word} FALSE"), + _ => f.write_str(word), + }; + let literal = |s: StringLiteral<'_>| Literal::String(s).to_string(); + match self { + CopyOption::Format(name) => write!(f, "FORMAT {name}"), + CopyOption::Freeze(value) => flag(f, "FREEZE", value), + CopyOption::Delimiter(s) => write!(f, "DELIMITER {}", literal(s.clone())), + CopyOption::Null(s) => write!(f, "NULL {}", literal(s.clone())), + CopyOption::Header(value) => flag(f, "HEADER", value), + CopyOption::Quote(s) => write!(f, "QUOTE {}", literal(s.clone())), + CopyOption::Escape(s) => write!(f, "ESCAPE {}", literal(s.clone())), + CopyOption::ForceQuote(columns) => write!(f, "FORCE_QUOTE ({})", comma(columns)), + CopyOption::ForceNotNull(columns) => write!(f, "FORCE_NOT_NULL ({})", comma(columns)), + CopyOption::ForceNull(columns) => write!(f, "FORCE_NULL ({})", comma(columns)), + CopyOption::Encoding(s) => write!(f, "ENCODING {}", literal(s.clone())), + } + } +} + +impl fmt::Display for CopyLegacyOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.keyword)?; + match &self.value { + CopyLegacyValue::None => Ok(()), + CopyLegacyValue::Default => f.write_str(" DEFAULT"), + CopyLegacyValue::String(s) => write!(f, " {}", s), + CopyLegacyValue::Number(n) => write!(f, " {n}"), + CopyLegacyValue::Force { not_null, columns } => { + write!( + f, + " {} {}", + if *not_null { "NOT NULL" } else { "QUOTE" }, + comma(columns) + ) + } + CopyLegacyValue::Toggle { preset, word } => { + if *preset { + f.write_str(" PRESET")?; + } + if let Some(word) = word { + write!(f, " {word}")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for Copy<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("COPY ")?; + match &self.source { + CopySource::Table { name, columns } => { + name.fmt(f)?; + if !columns.is_empty() { + write!(f, " ({})", comma(columns))?; + } + } + CopySource::Query(query) => write!(f, "({query})")?, + } + write!(f, " {} ", if self.to { "TO" } else { "FROM" })?; + match &self.target { + CopyTarget::Stdin => f.write_str("STDIN")?, + CopyTarget::Stdout => f.write_str("STDOUT")?, + CopyTarget::Program(command) => write!(f, "PROGRAM {}", command)?, + CopyTarget::File(file) => file.fmt(f)?, + } + if !self.options.is_empty() { + write!(f, " ({})", comma(&self.options))?; + } + for option in &self.legacy_options { + write!(f, " {option}")?; + } + if let Some(payload) = &self.payload { + f.write_str(";\n")?; + f.write_str(&payload.data)?; + if payload.terminated { + f.write_str("\\.")?; + } + } + Ok(()) + } +} + +impl fmt::Display for TableItem<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.only { + f.write_str("ONLY ")?; + } + self.name.fmt(f)?; + if self.star { + f.write_str(" *")?; + } + Ok(()) + } +} + +impl fmt::Display for PostgresTruncate<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("TRUNCATE ")?; + if self.table_keyword { + f.write_str("TABLE ")?; + } + comma(&self.tables).fmt(f)?; + match self.identity { + Some(true) => f.write_str(" RESTART IDENTITY")?, + Some(false) => f.write_str(" CONTINUE IDENTITY")?, + None => {} + } + write_behavior(f, self.behavior) + } +} + +impl fmt::Display for DeclareCursor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "DECLARE {}", self.name)?; + if self.binary { + f.write_str(" BINARY")?; + } + if let Some(ref sensitivity) = self.sensitivity { + write!(f, " {sensitivity}")?; + } + match self.scroll { + Some(true) => f.write_str(" SCROLL")?, + Some(false) => f.write_str(" NO SCROLL")?, + None => {} + } + f.write_str(" CURSOR")?; + match self.hold { + Some(true) => f.write_str(" WITH HOLD")?, + Some(false) => f.write_str(" WITHOUT HOLD")?, + None => {} + } + write!(f, " FOR {}", self.query) + } +} + +impl fmt::Display for FetchDirection<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FetchDirection::Next => f.write_str("NEXT"), + FetchDirection::Prior => f.write_str("PRIOR"), + FetchDirection::First => f.write_str("FIRST"), + FetchDirection::Last => f.write_str("LAST"), + FetchDirection::All => f.write_str("ALL"), + FetchDirection::Count(n) => f.write_str(n), + FetchDirection::Absolute(n) => write!(f, "ABSOLUTE {n}"), + FetchDirection::Relative(n) => write!(f, "RELATIVE {n}"), + FetchDirection::Forward(None) => f.write_str("FORWARD"), + FetchDirection::Forward(Some(n)) => write!(f, "FORWARD {n}"), + FetchDirection::ForwardAll => f.write_str("FORWARD ALL"), + FetchDirection::Backward(None) => f.write_str("BACKWARD"), + FetchDirection::Backward(Some(n)) => write!(f, "BACKWARD {n}"), + FetchDirection::BackwardAll => f.write_str("BACKWARD ALL"), + } + } +} + +impl fmt::Display for FetchStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "FETCH {} {} {}", + self.direction, self.position, self.cursor + )?; + if let Some(into) = &self.into { + write!(f, " INTO {into}")?; + } + Ok(()) + } +} + +impl fmt::Display for LockStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "LOCK TABLE {}", comma(&self.tables))?; + if let Some(ref mode) = self.mode { + write!(f, " IN {mode} MODE")?; + } + if self.nowait { + f.write_str(" NOWAIT")?; + } + Ok(()) + } +} + +impl fmt::Display for PrepareStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "PREPARE {}", self.name)?; + if !self.types.is_empty() { + write!(f, " ({})", comma(&self.types))?; + } + write!(f, " AS {}", self.statement) + } +} + +impl fmt::Display for ExecuteStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "EXECUTE {}", self.name)?; + if let Some(args) = &self.args { + write!(f, "({})", comma(args))?; + } + if !self.using.is_empty() { + write!(f, " USING {}", comma(&self.using))?; + } + Ok(()) + } +} + +impl fmt::Display for DoItem<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DoItem::Language(name) => write!(f, "LANGUAGE {name}"), + DoItem::Body(body) => body.fmt(f), + } + } +} + +impl fmt::Display for AnalyzeTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + Ok(()) + } +} diff --git a/sqlparser_v2/src/dialect/redshift.rs b/sqlparser_v2/src/dialect/redshift.rs new file mode 100644 index 0000000000..f81f693ea1 --- /dev/null +++ b/sqlparser_v2/src/dialect/redshift.rs @@ -0,0 +1,753 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Amazon Redshift, built on the PostgreSQL rules. + +use crate::ast::Span; +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + AlterTableOp, BinaryOp, CreateFlags, CreateSchema, CreateTable, CreateView, Expr, ExprKind, + Ident, InsertSource, NullTreatment, ObjectName, SelectInto, SelectItem, Statement, + StatementKind, StringLiteral, TableFactor, TableRef, TableWithJoins, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinSelect, BuiltinStatement, BuiltinTableFactor}; +use crate::dialect::postgres::{self, CopyLegacyKind}; +use crate::dialect::{Builtin, Dialect}; +use crate::display::{comma, write_create_flags}; +use crate::grammar::{self, prec}; +use crate::lexer::{ + LexResult, Lexeme, Token, TokenKind, block_comment, lex_core_comment, quoted_with_backslash, +}; +use crate::parser::{InfixRule, Parser, SetOperatorRule}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Redshift; + +/// Statements only Redshift has. +#[derive(Debug, Clone, PartialEq)] +pub enum RedshiftStatement<'a> { + CreateTable(Box>), + Vacuum(Box>), +} + +/// A `CREATE TABLE` with Redshift's table attributes. Without them, the +/// statement is the core [`CreateTable`]. +#[derive(Debug, Clone, PartialEq)] +pub struct RedshiftCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + /// `Some(true)` for `BACKUP YES`, `Some(false)` for `BACKUP NO`. + pub backup: Option, + /// `AUTO`, `EVEN`, `KEY` or `ALL`. + pub diststyle: Option>, + pub distkey: Option>, + pub sortkey: Vec>, +} + +/// `VACUUM [options] [table [TO n PERCENT] [BOOST]]` +#[derive(Debug, Clone, PartialEq)] +pub struct Vacuum<'a> { + pub full: bool, + pub sort_only: bool, + pub delete_only: bool, + pub reindex: bool, + pub recluster: bool, + pub table: Option>, + /// The number in `TO n PERCENT`. + pub threshold: Option>, + pub boost: bool, +} + +/// Expressions only Redshift has. +#[derive(Debug, Clone, PartialEq)] +pub enum RedshiftExpr<'a> { + /// `APPROXIMATE PERCENTILE_DISC(...) ...` + Approximate(Box>), +} + +/// PartiQL table references. +#[derive(Debug, Clone, PartialEq)] +pub enum RedshiftTableFactor<'a> { + /// A path into a `SUPER` value: `src[0].a`. + Path(Box>), + /// A table reference with the index alias after `AT`. + At { + table: Box>, + at: Ident<'a>, + }, + /// `UNPIVOT expr [AS alias] [AT name]` + Unpivot { + expr: Box>, + alias: Option>, + at: Option>, + }, +} + +fn statement<'a>(s: RedshiftStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::Redshift(s)).into() +} + +/// The legacy `COPY` options Redshift has. +const REDSHIFT_COPY_OPTIONS: &[(&str, CopyLegacyKind)] = &[ + ("ACCEPTANYDATE", CopyLegacyKind::Flag), + ("ACCEPTINVCHARS", CopyLegacyKind::OptionalString), + ("ADDQUOTES", CopyLegacyKind::Flag), + ("ALLOWOVERWRITE", CopyLegacyKind::Flag), + ("BINARY", CopyLegacyKind::Flag), + ("BLANKSASNULL", CopyLegacyKind::Flag), + ("BZIP2", CopyLegacyKind::Flag), + ("CLEANPATH", CopyLegacyKind::Flag), + ("COMPUPDATE", CopyLegacyKind::Toggle), + ("CREDENTIALS", CopyLegacyKind::String), + ("CSV", CopyLegacyKind::Flag), + ("DATEFORMAT", CopyLegacyKind::OptionalString), + ("DELIMITER", CopyLegacyKind::String), + ("EMPTYASNULL", CopyLegacyKind::Flag), + ("ENCRYPTED", CopyLegacyKind::Flag), + ("ESCAPE", CopyLegacyKind::Flag), + ("EXTENSION", CopyLegacyKind::String), + ("FIXEDWIDTH", CopyLegacyKind::String), + ("GZIP", CopyLegacyKind::Flag), + ("HEADER", CopyLegacyKind::Flag), + ("IAM_ROLE", CopyLegacyKind::StringOrDefault), + ("IGNOREHEADER", CopyLegacyKind::Number), + ("JSON", CopyLegacyKind::OptionalString), + ("MANIFEST", CopyLegacyKind::Flag), + ("MAXFILESIZE", CopyLegacyKind::Number), + ("NULL", CopyLegacyKind::String), + ("PARALLEL", CopyLegacyKind::Toggle), + ("PARQUET", CopyLegacyKind::Flag), + ("REGION", CopyLegacyKind::String), + ("REMOVEQUOTES", CopyLegacyKind::Flag), + ("ROWGROUPSIZE", CopyLegacyKind::Number), + ("STATUPDATE", CopyLegacyKind::Toggle), + ("TIMEFORMAT", CopyLegacyKind::OptionalString), + ("TRUNCATECOLUMNS", CopyLegacyKind::Flag), + ("ZSTD", CopyLegacyKind::Flag), +]; + +/// Parses Redshift's table attributes, fixed in this order as in the original. +struct Attributes<'a> { + backup: Option, + diststyle: Option<&'static str>, + distkey: Option>, + sortkey: Vec>, +} + +impl Attributes<'_> { + fn is_empty(&self) -> bool { + self.backup.is_none() + && self.diststyle.is_none() + && self.distkey.is_none() + && self.sortkey.is_empty() + } +} + +fn parse_table_attributes<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let backup = if p.eat_keyword("BACKUP") { + if p.eat_keyword("YES") { + Some(true) + } else { + p.expect_keyword("NO")?; + Some(false) + } + } else { + None + }; + let diststyle = if p.eat_keyword("DISTSTYLE") { + let style = ["AUTO", "EVEN", "KEY", "ALL"] + .into_iter() + .find(|word| p.eat_keyword(word)); + Some(style.ok_or_else(|| p.expected("AUTO, EVEN, KEY or ALL"))?) + } else { + None + }; + let distkey = if p.eat_keyword("DISTKEY") { + p.expect_op("(")?; + let expr = p.parse_expr()?; + p.expect_op(")")?; + Some(expr) + } else { + None + }; + let sortkey = if p.eat_keyword("SORTKEY") { + p.expect_op("(")?; + let exprs = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + exprs + } else { + Vec::new() + }; + Ok(Attributes { + backup, + diststyle, + distkey, + sortkey, + }) +} + +/// Parses `CREATE [OR REPLACE] [TEMP] TABLE` with table attributes. +fn parse_create_table_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let attributes = parse_table_attributes(p)?; + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() { + return Err(p.expected("column definitions or AS")); + } + let table = CreateTable { + or_replace: flags.or_replace, + temporary: flags.temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + if attributes.is_empty() { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + let Attributes { + backup, + diststyle, + distkey, + sortkey, + } = attributes; + Ok(statement(RedshiftStatement::CreateTable(Box::new( + RedshiftCreateTable { + table, + backup, + diststyle: diststyle.map(Cow::Borrowed), + distkey, + sortkey, + }, + )))) +} + +fn parse_vacuum<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let full = p.eat_keyword("FULL"); + let sort_only = p.at_keyword("SORT") && p.peek_nth(1).is_word("ONLY"); + if sort_only { + p.advance(); + p.advance(); + } + let delete_only = p.at_keyword("DELETE") && p.peek_nth(1).is_word("ONLY"); + if delete_only { + p.advance(); + p.advance(); + } + let reindex = p.eat_keyword("REINDEX"); + let recluster = p.eat_keyword("RECLUSTER"); + let (table, threshold, boost) = if p.at_ident() { + let table = grammar::parse_object_name(p)?; + let threshold = if p.eat_keyword("TO") { + let number = grammar::parse_number_text(p)?; + p.expect_keyword("PERCENT")?; + Some(number) + } else { + None + }; + let boost = p.eat_keyword("BOOST"); + (Some(table), threshold, boost) + } else { + (None, None, false) + }; + Ok(statement(RedshiftStatement::Vacuum(Box::new(Vacuum { + full, + sort_only, + delete_only, + reindex, + recluster, + table, + threshold: threshold.map(Cow::Borrowed), + boost, + })))) +} + +/// Lexes a word starting with `#`, or a bracketed identifier. In Redshift +/// `[a]` delimits a name; only directly after a value, as `a[0]`, is it a +/// subscript, which [`Redshift::lex_after`] arranges. +fn lex_bracketed_name(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let first = bytes.iter().skip(1).find(|b| !b.is_ascii_whitespace())?; + if *first != b'"' && !(first.is_ascii_alphabetic() || *first == b'_') { + return None; + } + let mut i = 1; + loop { + match bytes.get(i)? { + b'"' => { + i += 1 + bytes[i + 1..].iter().position(|&b| b == b'"')? + 1; + } + b']' => { + return Some(Ok(Lexeme { + kind: TokenKind::QuotedIdent, + len: i + 1, + })); + } + _ => i += 1, + } + } +} + +/// True if `word` can start a `SUPER` path in `FROM`, after which `[` follows. +fn at_super_path(p: &Parser<'_, D>) -> bool { + let mut n = 0; + while matches!(p.peek_nth(n).kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(n + 1).is_op(".") + { + n += 2; + } + matches!(p.peek_nth(n).kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(n + 1).is_op("[") +} + +/// Parses a table reference, adding PartiQL paths, `AT` and `UNPIVOT`. +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("UNPIVOT") && !p.peek_nth(1).is_op("(") { + p.advance(); + let expr = Box::new(p.parse_expr_bp(prec::COMPARE)?); + let alias = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + let at = if p.eat_keyword("AT") { + Some(p.parse_ident()?) + } else { + None + }; + return Ok(TableRef { + factor: TableFactor::Ext(BuiltinTableFactor::Redshift(Box::new( + RedshiftTableFactor::Unpivot { expr, alias, at }, + ))), + alias: None, + span: Span::default(), + }); + } + let factor = if at_super_path(p) { + let expr = Box::new(p.parse_expr_bp(prec::COMPARE)?); + TableFactor::Ext(BuiltinTableFactor::Redshift(Box::new( + RedshiftTableFactor::Path(expr), + ))) + } else { + D::parse_table_factor(p)? + }; + let alias = grammar::parse_optional_table_alias(p)?; + let table = TableRef { + factor, + alias, + span: Span::default(), + }; + if p.at_keyword("AT") && p.peek_nth(1).kind != TokenKind::Eof { + p.advance(); + let at = p.parse_ident()?; + return Ok(TableRef { + factor: TableFactor::Ext(BuiltinTableFactor::Redshift(Box::new( + RedshiftTableFactor::At { + table: Box::new(table), + at, + }, + ))), + alias: None, + span: Span::default(), + }); + } + Ok(table) +} + +/// `APPROXIMATE` before an aggregate's name, as in `APPROXIMATE +/// PERCENTILE_DISC(...)`. +fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if p.at_keyword("APPROXIMATE") + && matches!(next.kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(2).is_op("(") + { + p.advance(); + let call = p.parse_expr_bp(prec::POSTFIX)?; + return Ok( + ExprKind::Ext(BuiltinExpr::Redshift(RedshiftExpr::Approximate(Box::new( + call, + )))) + .into(), + ); + } + grammar::parse_prefix(p) +} + +impl fmt::Display for RedshiftStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CreateTable(create) => { + let table = &create.table; + write_create_flags(f, table.or_replace, table.temporary)?; + f.write_str("TABLE ")?; + crate::display::write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + if !(table.columns.is_empty() && table.constraints.is_empty()) { + crate::display::write_columns(f, &table.columns, &table.constraints)?; + } + match create.backup { + Some(true) => f.write_str(" BACKUP YES")?, + Some(false) => f.write_str(" BACKUP NO")?, + None => {} + } + if let Some(ref style) = create.diststyle { + write!(f, " DISTSTYLE {style}")?; + } + if let Some(key) = &create.distkey { + write!(f, " DISTKEY({key})")?; + } + if !create.sortkey.is_empty() { + write!(f, " SORTKEY({})", comma(&create.sortkey))?; + } + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } + Self::Vacuum(vacuum) => { + f.write_str("VACUUM")?; + let flags = [ + (vacuum.full, " FULL"), + (vacuum.sort_only, " SORT ONLY"), + (vacuum.delete_only, " DELETE ONLY"), + (vacuum.reindex, " REINDEX"), + (vacuum.recluster, " RECLUSTER"), + ]; + for (set, keyword) in flags { + if set { + f.write_str(keyword)?; + } + } + if let Some(table) = &vacuum.table { + write!(f, " {table}")?; + } + if let Some(ref threshold) = vacuum.threshold { + write!(f, " TO {threshold} PERCENT")?; + } + if vacuum.boost { + f.write_str(" BOOST")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for RedshiftExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Approximate(call) => write!(f, "APPROXIMATE {call}"), + } + } +} + +impl fmt::Display for RedshiftTableFactor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Path(expr) => expr.fmt(f), + Self::At { table, at } => write!(f, "{table} AT {at}"), + Self::Unpivot { expr, alias, at } => { + write!(f, "UNPIVOT {expr}")?; + if let Some(alias) = alias { + write!(f, " AS {alias}")?; + } + if let Some(at) = at { + write!(f, " AT {at}")?; + } + Ok(()) + } + } + } +} + +impl Dialect for Redshift { + type Ext = Builtin; + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + grammar::parse_select_item_alias_any_word(p, expr) + } + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, false) + } + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_delete_using<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_delete_using(p) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_table(p) + } + + fn eat_limit_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, false, true) + } + + fn parse_insert_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_insert_source_with_default(p) + } + + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + if flags != CreateFlags::default() { + return Err(p.expected("TABLE or VIEW")); + } + grammar::parse_create_schema_authorization(p, true) + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + grammar::set_operator_rule_with_minus(p) + } + + /// Unlike PostgreSQL, block comments do not nest. + #[inline] + fn lex_comment(rest: &str) -> Option> { + if rest.starts_with("/*") { + return Some(block_comment(rest, false)); + } + lex_core_comment(rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + postgres::is_reserved(word) + } + + /// `AT` introduces a PartiQL index alias after a table's alias. + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + word.eq_ignore_ascii_case("AT") + || word.eq_ignore_ascii_case("MINUS") + || grammar::is_reserved_for_alias(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if p.at_keyword("ABORT") { + return grammar::parse_abort(p); + } + if p.at_keyword("ANALYZE") { + return grammar::parse_analyze(p); + } + if p.at_keyword("RESET") { + return postgres::utility::parse_reset(p) + .map(|s| StatementKind::Ext(BuiltinStatement::Postgres(s)).into()); + } + if p.at_keyword("CLOSE") { + return postgres::utility::parse_close(p) + .map(|s| StatementKind::Ext(BuiltinStatement::Postgres(s)).into()); + } + if p.at_keyword("COPY") { + return postgres::parse_copy(p, REDSHIFT_COPY_OPTIONS); + } + if p.at_keyword("VACUUM") { + return parse_vacuum(p); + } + grammar::parse_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let or_replace = p.peek_nth(1).is_word("OR") && p.peek_nth(2).is_word("REPLACE"); + let n = if or_replace { 3 } else { 1 }; + let temporary = p.peek_nth(n).is_word("TEMPORARY") || p.peek_nth(n).is_word("TEMP"); + let at_table = p.peek_nth(n + usize::from(temporary)).is_word("TABLE"); + if !at_table { + return grammar::parse_create(p); + } + for _ in 0..n + usize::from(temporary) + 1 { + p.advance(); + } + parse_create_table_statement( + p, + CreateFlags { + or_replace, + temporary, + }, + ) + } + + fn parse_create_view<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + let mut view = grammar::parse_create_view(p, flags)?; + if p.at_keyword("WITH") && p.peek_nth(1).is_word("NO") && p.peek_nth(2).is_word("SCHEMA") { + p.advance(); + p.advance(); + p.advance(); + p.expect_keyword("BINDING")?; + view.no_schema_binding = true; + } + Ok(view) + } + + fn parse_extract_field<'a>(p: &mut Parser<'a, Self>) -> PResult<&'a str> { + let token = p.peek(); + if token.kind == TokenKind::String { + p.advance(); + return Ok(token.text); + } + grammar::parse_date_time_field(p) + } + + fn parse_function_arg_null_treatment<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult> { + Ok(grammar::parse_null_treatment(p)) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + #[inline] + fn lex_after(prev: Option>, rest: &str) -> Option { + if rest.starts_with('[') && prev.is_none_or(|token| token.is_op(".")) { + return lex_bracketed_name(rest); + } + None + } + + fn parse_interval<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_interval(p, false) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + if rest.as_bytes()[0] == b'#' + && rest + .as_bytes() + .get(1) + .is_some_and(|&b| b.is_ascii_alphabetic() || b == b'_') + { + let len = rest + .as_bytes() + .iter() + .skip(1) + .position(|&b| !(b.is_ascii_alphanumeric() || b == b'_' || !b.is_ascii())) + .map_or(rest.len(), |at| at + 1); + return Some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })); + } + if rest.as_bytes()[0] == b'#' && !rest[1..].starts_with(['>', '-']) { + return Some(Ok(Lexeme { + kind: TokenKind::Op, + len: 1, + })); + } + if rest.starts_with('\'') { + return Some(quoted_with_backslash(rest, TokenKind::String)); + } + if let Some(result) = postgres::lex_prefixed_string(rest, false) { + return Some(result); + } + postgres::lex_token(rest) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + postgres::string_literal(token, true) + } + + /// Redshift has no `FILTER` clause. + fn parse_function_filter<'a>(_p: &mut Parser<'a, Self>) -> PResult>> { + Ok(None) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + if p.at_op("#") { + return Some(InfixRule::binary(prec::OTHER, BinaryOp::Named("#".into()))); + } + postgres::infix_rule_without_null_tests(p) + } + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let next = p.peek_nth(1); + if p.at_keyword("ALTER") && next.is_word("SORTKEY") && p.peek_nth(2).is_op("(") { + p.advance(); + p.advance(); + return grammar::parse_ident_list(p).map(AlterTableOp::AlterSortKey); + } + grammar::parse_alter_table_op(p) + } + + fn parse_select_modifiers<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if !p.eat_keyword("TOP") { + return Ok(BuiltinSelect::default()); + } + let token = p.expect_kind(TokenKind::Number, "a number after TOP")?; + Ok(BuiltinSelect { + top: Some(token.text.into()), + ..BuiltinSelect::default() + }) + } +} diff --git a/sqlparser_v2/src/dialect/snowflake.rs b/sqlparser_v2/src/dialect/snowflake.rs new file mode 100644 index 0000000000..e7f48b5b00 --- /dev/null +++ b/sqlparser_v2/src/dialect/snowflake.rs @@ -0,0 +1,2585 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Snowflake. + +use std::borrow::Cow; +use std::fmt::{self, Display as _}; + +use crate::PResult; +use crate::ast::{ + AlterTable, AlterTableOp, ColumnOption, ConnectBy, CreateFlags, CreateSchema, DataType, + DropBehavior, ExplainTarget, Expr, ExprKind, FunctionArg, Ident, Join, JoinConstraint, + JoinKind, Literal, NullTreatment, ObjectName, ObjectType, OrderByItem, Pivot, PivotSource, + Quantifier, Query, SampleClause, SelectInto, SelectItem, SelectItemKind, SetQuantifier, + SetStatement, Span, SpecialExpr, Statement, StatementKind, StringLiteral, TableAlias, + TableFactor, TableRef, TableSample, TableWithJoins, Unpivot, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinInsert, BuiltinSelect, BuiltinStatement}; +use crate::dialect::mssql::MsSqlTop; +use crate::dialect::{Builtin, Dialect, clickhouse, duckdb, mysql, oracle, postgres, spark}; +use crate::display::{SpaceOrNewline, comma, write_if_not_exists}; +use crate::grammar::{self, prec}; +use crate::lexer::{ + LexResult, Lexeme, Token, TokenKind, block_comment, lex_core_comment, line_comment, + quoted_with_backslash, +}; +use crate::parser::{InfixRule, Parser, SetOperatorRule}; + +pub mod ddl; + +pub use ddl::{ + Assignment, Block, DatabaseClause, Declaration, DeclarationKind, ExceptionWhen, RaiseValue, + SemanticView, SnowflakeCreateDatabase, SnowflakeCreateTable, SnowflakeCreateView, TableClause, + ViewColumn, +}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Snowflake; + +/// Expressions only Snowflake has. +#[derive(Debug, Clone, PartialEq)] +pub enum SnowflakeExpr<'a> { + /// A path into a semi-structured value: `a:b.c[0]`. + Path { + value: Box>, + path: Vec>, + }, + /// A call's only argument, written without parentheses: `f(SELECT 1)`. + BareSubquery(Box>), + /// The arguments of `SEMANTIC_VIEW(...)`. + SemanticView(Box>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum PathElement<'a> { + /// `:key` + Colon(Ident<'a>), + /// `.key` + Dot(Ident<'a>), + /// `[index]` + Index(Expr<'a, Builtin>), +} + +/// Statements only Snowflake has. +#[derive(Debug, Clone, PartialEq)] +pub enum SnowflakeStatement<'a> { + CreateUser(Box>), + AlterUser(Box>), + /// `USE [kind] name` + Use { + kind: Option>, + name: ObjectName<'a>, + }, + UseSecondaryRoles(SecondaryRoles<'a>), + /// `ALTER SESSION SET a=1 b=2` + AlterSessionSet(Vec<(Ident<'a>, Literal<'a>)>), + /// `ALTER SESSION UNSET a, b` + AlterSessionUnset(Vec>), + /// `INSERT ALL ...` or `INSERT FIRST ...` + MultiTableInsert(Box>), + /// `LIST @stage` or `REMOVE @stage`, with any options. + StageCommand { + remove: bool, + stage: Ident<'a>, + options: Vec<(Ident<'a>, Expr<'a, Builtin>)>, + }, + CopyInto(Box>), + /// `CREATE STAGE` or `CREATE FILE FORMAT`. + CreateObject(Box>), + CreateTable(Box>), + CreateDatabase(Box>), + CreateView(Box>), + AlterIcebergTable(Box>), + /// `ALTER {DYNAMIC | EXTERNAL} TABLE name action` + AlterTableKind { + dynamic: bool, + if_exists: bool, + name: ObjectName<'a>, + action: Cow<'a, str>, + subpath: Option>, + }, + Block(Box>), + /// `RAISE [value]` + Raise(Option>), + Declare(Vec>), + /// `SET (a, b) = (1, 2)` + SetTuple { + names: Vec>, + values: Vec>, + }, + /// `PUT 'file' @stage`, with any options. + Put { + file: StringLiteral<'a>, + stage: Ident<'a>, + options: Vec<(Ident<'a>, Expr<'a, Builtin>)>, + }, +} + +/// A `KEY=value` option. +#[derive(Debug, Clone, PartialEq)] +pub struct KeyValue<'a> { + pub key: Ident<'a>, + pub value: OptionValue<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum OptionValue<'a> { + /// An unquoted word such as `CSV` or `true`, as written. + Word(Cow<'a, str>), + Literal(Literal<'a>), + /// `('a', 'b')` + List(Vec>), + /// `(A=1 B=2)` + Nested(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CopyLocation<'a> { + Name(ObjectName<'a>), + Stage(Ident<'a>), + Url(StringLiteral<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CopySource<'a> { + Query(Box>), + Location(CopyLocation<'a>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CopyClause<'a> { + Option(KeyValue<'a>), + PartitionBy(Expr<'a, Builtin>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CopyInto<'a> { + pub into: CopyLocation<'a>, + pub into_params: Vec>, + pub columns: Vec>, + pub from: CopySource<'a>, + pub from_params: Vec>, + pub alias: Option>, + /// In the order written. + pub clauses: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CreateObject<'a> { + pub or_replace: bool, + /// `TEMPORARY` or `VOLATILE`. + pub lifetime: Option>, + /// `STAGE` or `FILE FORMAT`. + pub kind: Cow<'a, str>, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub options: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct MultiTableInsert<'a> { + pub overwrite: bool, + /// True for `INSERT FIRST`, false for `INSERT ALL`. + pub first: bool, + /// The targets of an unconditional insert. + pub into: Vec>, + pub when: Vec>, + pub otherwise: Vec>, + pub source: Query<'a, Builtin>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct InsertWhen<'a> { + pub condition: Expr<'a, Builtin>, + pub into: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct InsertTarget<'a> { + pub table: ObjectName<'a>, + pub columns: Vec>, + pub values: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SecondaryRoles<'a> { + All, + None, + List(Vec>), +} + +#[inline] +fn is_word_char(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'$' +} + +fn op(len: usize) -> Option { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) +} + +/// Lexes `@name/path` as one word. Quoted parts may contain anything. +#[inline] +fn stage(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let mut quoted = false; + let mut len = 1; + while let Some(&b) = bytes.get(len) { + let ends = b.is_ascii_whitespace() || matches!(b, b'(' | b')' | b',' | b';'); + if ends && !quoted { + break; + } + quoted ^= b == b'"'; + len += 1; + } + (len > 1).then_some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })) +} + +/// Identifiers are ASCII and can contain `$`. `@` starts a stage name. +#[inline] +pub fn lex_token(rest: &str) -> Option { + let bytes = rest.as_bytes(); + match bytes[0] { + b'\'' => Some(quoted_with_backslash(rest, TokenKind::String)), + b'$' => postgres::dollar_string(rest).or_else(|| { + // A lone `$` is the end anchor of a `MATCH_RECOGNIZE` pattern. + let continues = bytes.get(1).is_some_and(|&b| is_word_char(b) && b != b'$'); + if continues { None } else { op(1) } + }), + b'{' | b'}' => op(1), + b':' => match bytes.get(1) { + Some(b':' | b'=') => op(2), + Some(b) if b.is_ascii_digit() => { + let digits = bytes[1..].iter().take_while(|b| b.is_ascii_digit()).count(); + Some(Ok(Lexeme { + kind: TokenKind::Placeholder, + len: 1 + digits, + })) + } + Some(b) if b.is_ascii_alphabetic() || *b == b'_' => None, + _ => op(1), + }, + b'@' => stage(rest), + b'-' if bytes.get(1) == Some(&b'>') => op(2), + b'x' | b'X' if bytes.get(1) == Some(&b'\'') => None, + b if b.is_ascii_alphabetic() || b == b'_' => Some(Ok(Lexeme { + kind: TokenKind::Word, + len: bytes.iter().take_while(|&&b| is_word_char(b)).count(), + })), + b if !b.is_ascii() => Some(Err("unexpected character")), + _ => None, + } +} + +/// A colon directly after a string is a key's separator, as in `{'a':1}`. +#[inline] +pub fn lex_after(prev: Option>, rest: &str) -> Option { + let bytes = rest.as_bytes(); + let separator = bytes[0] == b':' + && !matches!(bytes.get(1), Some(b':' | b'=')) + && prev.is_some_and(|token| token.kind == TokenKind::String); + if separator { op(1) } else { None } +} + +/// `#` and `//` start line comments, and block comments do not nest. +#[inline] +pub fn lex_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'#', ..] | [b'/', b'/', ..] => Some(Ok(line_comment(rest))), + [b'/', b'*', ..] => Some(block_comment(rest, false)), + _ => lex_core_comment(rest), + } +} + +#[inline] +pub fn is_reserved_for_alias(word: &str) -> bool { + word.starts_with('@') + || [ + "MINUS", + "ASOF", + "MATCH_CONDITION", + "QUALIFY", + "SAMPLE", + "TABLESAMPLE", + "START", + "CONNECT", + "ILIKE", + "REGEXP", + "RLIKE", + "LIMIT", + "OFFSET", + "EXCEPT", + "OUTER", + ] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) + || grammar::is_reserved_for_alias(word) +} + +/// True for what can follow `LIMIT` or `OFFSET` when it starts a clause. +fn is_limit_value(token: Token<'_>) -> bool { + matches!(token.kind, TokenKind::Number | TokenKind::Placeholder) + || token.is_word("NULL") + || token.text == "''" + || token.text == "$$$$" +} + +/// True at a word that normally starts a clause but is a name here, because +/// what follows it cannot be that clause. `table` selects the rules for a +/// table alias rather than those for a select item. +fn clause_word_is_name(p: &Parser<'_, D>, table: bool) -> bool { + let next = p.peek_nth(1); + if p.at_keyword("LIMIT") || p.at_keyword("OFFSET") { + return !is_limit_value(next); + } + if p.at_keyword("FETCH") { + return !(next.is_word("FIRST") || next.is_word("NEXT") || is_limit_value(next)); + } + if p.at_keyword("EXCEPT") { + return next.kind == TokenKind::Eof || next.is_op(";") || (!table && next.is_op(",")); + } + table && (p.at_keyword("OUTER") || p.at_keyword("WINDOW") || p.at_keyword("PARTITION")) +} + +/// Parses a list that allows a trailing comma, where a clause word can still +/// be the next item. +fn parse_list_with_trailing_comma<'a, D, T>( + p: &mut Parser<'a, D>, + mut item: impl FnMut(&mut Parser<'a, D>) -> PResult, +) -> PResult> +where + D: Dialect, +{ + let mut items = vec![item(p)?]; + while p.eat_op(",") { + if grammar::at_list_end(p) && !clause_word_is_name(p, false) { + break; + } + items.push(item(p)?); + } + Ok(items) +} + +/// Adds the select aliases that the clause words can be. +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, Builtin>, +) -> PResult> { + if clause_word_is_name(p, false) { + let alias = Some(p.parse_name_part()?); + return Ok(SelectItemKind::Expr { expr, alias }.into()); + } + grammar::parse_select_item_alias(p, expr) +} + +/// True at `IDENTIFIER(...)` taking one string or bind variable. +fn at_identifier_call(p: &Parser<'_, D>) -> bool { + let argument = p.peek_nth(2).kind; + p.at_keyword("IDENTIFIER") + && p.peek_nth(1).is_op("(") + && matches!(argument, TokenKind::String | TokenKind::Placeholder) + && p.peek_nth(3).is_op(")") +} + +/// Parses an `IDENTIFIER(...)` call as a name part holding its source text, +/// since the argument is resolved only when the statement runs. +fn parse_identifier_call<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let start = p.advance().span.start; + p.advance(); + p.advance(); + let end = p.advance().span.end; + let span = Span { start, end }; + Ok(Ident { + text: p.text(span).into(), + quote: None, + span, + }) +} + +fn is_identifier_call(part: &Ident<'_>) -> bool { + part.quote.is_none() && part.text.ends_with(')') +} + +/// A part of an object's name can be an `IDENTIFIER` call, and `a..b` leaves +/// out the middle one. +pub fn parse_object_name_part<'a, D: Dialect>( + p: &mut Parser<'a, D>, + before: &[Ident<'a>], +) -> PResult> { + if before.len() == 1 && p.at_op(".") { + return Ok(Ident { + text: "".into(), + quote: None, + span: Span::default(), + }); + } + if at_identifier_call(p) && !before.iter().any(is_identifier_call) { + return parse_identifier_call(p); + } + grammar::parse_object_name_part(p, before) +} + +/// The key in a `:key` token, in which the lexer saw a named placeholder. It +/// is only a placeholder at the start of an expression. +fn colon_key(token: Token<'_>) -> Option> { + let key = token.text.strip_prefix(':')?; + let is_name = + token.kind == TokenKind::Placeholder && !key.starts_with(|c: char| c.is_ascii_digit()); + is_name.then_some(Ident { + text: key.into(), + quote: None, + span: Span { + start: token.span.start + 1, + end: token.span.end, + }, + }) +} + +pub fn at_path>(p: &Parser<'_, D>) -> bool { + !p.has_context(grammar::CONTEXT_COLON_SEPARATES) + && (p.at_op(":") || colon_key(p.peek()).is_some()) +} + +fn parse_colon_key<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if let Some(key) = colon_key(p.peek()) { + p.advance(); + return Ok(key); + } + p.expect_op(":")?; + p.parse_name_part() +} + +pub fn parse_path<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + let mut path = vec![PathElement::Colon(parse_colon_key(p)?)]; + loop { + if at_path(p) { + path.push(PathElement::Colon(parse_colon_key(p)?)); + } else if p.eat_op(".") { + path.push(PathElement::Dot(p.parse_name_part()?)); + } else if p.eat_op("[") { + path.push(PathElement::Index(p.parse_expr()?)); + p.expect_op("]")?; + } else { + break; + } + } + Ok(ExprKind::Ext(BuiltinExpr::Snowflake(SnowflakeExpr::Path { + value: Box::new(left), + path, + })) + .into()) +} + +/// True at `(+)`, which marks the outer side of a join. +pub fn at_outer_join_mark>(p: &Parser<'_, D>) -> bool { + p.at_op("(") && p.peek_nth(1).is_op("+") && p.peek_nth(2).is_op(")") +} + +pub fn parse_outer_join_mark<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + if !matches!(left.kind, ExprKind::Ident(_) | ExprKind::Compound(_)) { + return Err(p.expected("a column before (+)")); + } + p.advance(); + p.advance(); + p.advance(); + Ok(ExprKind::Special(Box::new(SpecialExpr::OuterJoinMark(left))).into()) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + if at_outer_join_mark(p) { + Some(InfixRule::custom(prec::POSTFIX, parse_outer_join_mark)) + } else if at_path(p) { + Some(InfixRule::custom(prec::POSTFIX, parse_path)) + } else if p.at_op("::") { + Some(InfixRule::custom( + prec::POSTFIX, + postgres::parse_double_colon, + )) + } else if p.at_keyword("ILIKE") { + Some(InfixRule::custom(prec::COMPARE, postgres::parse_ilike)) + } else if p.at_keyword("NOT") && postgres::next_is_ilike(p) { + Some(InfixRule::custom(prec::COMPARE, postgres::parse_not_ilike)) + } else if mysql::at_regexp(p, 0) || (p.at_keyword("NOT") && mysql::at_regexp(p, 1)) { + Some(InfixRule::custom(prec::COMPARE, mysql::parse_regexp)) + } else { + grammar::infix_rule(p) + } +} + +/// A part of a `USE` name, which can be a string. +fn parse_use_part<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::String { + p.advance(); + return Ok(Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some('\''), + span: token.span, + }); + } + p.parse_ident() +} + +fn parse_use_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if at_identifier_call(p) { + return Ok(ObjectName { + parts: vec![parse_identifier_call(p)?], + }); + } + let mut parts = vec![parse_use_part(p)?]; + while p.eat_op(".") { + parts.push(parse_use_part(p)?); + } + Ok(ObjectName { parts }) +} + +fn parse_use<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("USE")?; + if p.eat_keyword("SECONDARY") { + if !p.eat_keyword("ROLES") { + p.expect_keyword("ROLE")?; + } + return Ok(SnowflakeStatement::UseSecondaryRoles( + if p.eat_keyword("ALL") { + SecondaryRoles::All + } else if p.eat_keyword("NONE") { + SecondaryRoles::None + } else { + SecondaryRoles::List(p.parse_comma_separated(Parser::parse_ident)?) + }, + )); + } + let kind = ["DATABASE", "SCHEMA", "ROLE", "WAREHOUSE"] + .into_iter() + .find(|kind| p.eat_keyword(kind)); + let name = parse_use_name(p)?; + Ok(SnowflakeStatement::Use { + kind: kind.map(Cow::Borrowed), + name, + }) +} + +fn parse_session_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(Ident<'a>, Literal<'a>)> { + let key = p.parse_ident()?; + p.expect_op("=")?; + match p.parse_prefix()?.kind { + ExprKind::Literal(value) => Ok((key, value)), + _ => Err(p.expected("a literal session parameter value")), + } +} + +fn parse_alter_session<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + if p.eat_keyword("UNSET") { + let mut names = vec![p.parse_ident()?]; + while p.eat_op(",") || p.at_ident() { + names.push(p.parse_ident()?); + } + return Ok(SnowflakeStatement::AlterSessionUnset(names)); + } + p.expect_keyword("SET")?; + let mut options = vec![parse_session_option(p)?]; + loop { + p.eat_op(","); + if !p.at_ident() { + return Ok(SnowflakeStatement::AlterSessionSet(options)); + } + options.push(parse_session_option(p)?); + } +} + +fn at_multi_table_insert>(p: &Parser<'_, D>) -> bool { + let at_kind = |n| p.peek_nth(n).is_word("ALL") || p.peek_nth(n).is_word("FIRST"); + p.at_keyword("INSERT") && (at_kind(1) || (p.peek_nth(1).is_word("OVERWRITE") && at_kind(2))) +} + +fn parse_insert_target<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INTO")?; + let table = grammar::parse_object_name(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let values = if p.eat_keyword("VALUES") { + p.expect_op("(")?; + let values = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Some(values) + } else { + None + }; + Ok(InsertTarget { + table, + columns, + values, + }) +} + +fn parse_insert_targets<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut targets = vec![parse_insert_target(p)?]; + while p.at_keyword("INTO") { + targets.push(parse_insert_target(p)?); + } + Ok(targets) +} + +fn parse_multi_table_insert<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INSERT")?; + let overwrite = p.eat_keyword("OVERWRITE"); + let first = p.eat_keyword("FIRST"); + if !first { + p.expect_keyword("ALL")?; + } + let mut into = Vec::new(); + let mut when = Vec::new(); + let mut otherwise = Vec::new(); + if p.at_keyword("WHEN") { + while p.eat_keyword("WHEN") { + let condition = p.parse_expr()?; + p.expect_keyword("THEN")?; + let into = parse_insert_targets(p)?; + when.push(InsertWhen { condition, into }); + } + if p.eat_keyword("ELSE") { + otherwise = parse_insert_targets(p)?; + } + } else { + into = parse_insert_targets(p)?; + } + let source = D::parse_query(p)?; + Ok(SnowflakeStatement::MultiTableInsert(Box::new( + MultiTableInsert { + overwrite, + first, + into, + when, + otherwise, + source, + }, + ))) +} + +/// Parses a stage name, which the lexer read as a word starting with `@`. +fn parse_stage<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !(p.peek().kind == TokenKind::Word && p.peek().text.starts_with('@')) { + return Err(p.expected("a stage name")); + } + p.parse_ident() +} + +/// Parses `key=value` pairs up to the end of the statement. +fn parse_stage_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult, Expr<'a, Builtin>)>> { + let mut options = Vec::new(); + while p.at_ident() { + let key = p.parse_ident()?; + p.expect_op("=")?; + options.push((key, p.parse_prefix()?)); + } + Ok(options) +} + +fn at_stage_command>(p: &Parser<'_, D>) -> bool { + ["LIST", "LS", "REMOVE", "RM"] + .iter() + .any(|word| p.at_keyword(word)) +} + +fn parse_stage_command<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let remove = p.at_keyword("REMOVE") || p.at_keyword("RM"); + p.advance(); + let stage = parse_stage(p)?; + let options = parse_stage_options(p)?; + Ok(SnowflakeStatement::StageCommand { + remove, + stage, + options, + }) +} + +fn parse_put<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let token = p.expect_kind(TokenKind::String, "a file URL")?; + let file = D::string_literal(token); + let stage = parse_stage(p)?; + let options = parse_stage_options(p)?; + Ok(SnowflakeStatement::Put { + file, + stage, + options, + }) +} + +fn parse_option_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::String => { + p.advance(); + Ok(OptionValue::Literal(Literal::String(D::string_literal( + token, + )))) + } + TokenKind::Number => { + p.advance(); + Ok(OptionValue::Literal(Literal::Number(token.text.into()))) + } + TokenKind::Word => { + p.advance(); + Ok(OptionValue::Word(token.text.into())) + } + TokenKind::Op if token.text == "(" => { + p.advance(); + if p.peek().kind == TokenKind::String { + let strings = p.parse_comma_separated(grammar::parse_string)?; + p.expect_op(")")?; + return Ok(OptionValue::List(strings)); + } + let mut options = Vec::new(); + while !p.eat_op(")") { + options.push(parse_key_value(p)?); + p.eat_op(","); + } + Ok(OptionValue::Nested(options)) + } + _ => Err(p.expected("an option value")), + } +} + +fn parse_key_value<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let key = p.parse_name_part()?; + p.expect_op("=")?; + let value = p.nested(parse_option_value)?; + Ok(KeyValue { key, value }) +} + +/// Parses options up to something that is not a word. +fn parse_key_values<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut options = Vec::new(); + while p.peek().kind == TokenKind::Word { + options.push(parse_key_value(p)?); + p.eat_op(","); + } + Ok(options) +} + +fn parse_copy_location<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::String { + return grammar::parse_string(p).map(CopyLocation::Url); + } + if token.kind == TokenKind::Word && token.text.starts_with('@') { + return parse_stage(p).map(CopyLocation::Stage); + } + grammar::parse_object_name(p).map(CopyLocation::Name) +} + +/// Parses the storage options that can follow a location. +fn parse_stage_params<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut params = Vec::new(); + while [ + "STORAGE_INTEGRATION", + "ENDPOINT", + "CREDENTIALS", + "ENCRYPTION", + ] + .iter() + .any(|word| p.at_keyword(word)) + { + params.push(parse_key_value(p)?); + } + Ok(params) +} + +fn parse_copy_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("PARTITION") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + return p.parse_expr().map(CopyClause::PartitionBy); + } + let option = parse_key_value(p)?; + if option.key.text.eq_ignore_ascii_case("FILES") + && !matches!(option.value, OptionValue::List(_)) + { + return Err(p.expected("a list of files")); + } + Ok(CopyClause::Option(option)) +} + +fn parse_copy_into<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + let into = parse_copy_location(p)?; + let into_params = parse_stage_params(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + p.expect_keyword("FROM")?; + let from = if p.eat_op("(") { + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + CopySource::Query(Box::new(query)) + } else { + CopySource::Location(parse_copy_location(p)?) + }; + let from_params = parse_stage_params(p)?; + let alias = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + let mut clauses = Vec::new(); + while p.peek().kind == TokenKind::Word { + clauses.push(parse_copy_clause(p)?); + p.eat_op(","); + } + Ok(SnowflakeStatement::CopyInto(Box::new(CopyInto { + into, + into_params, + columns, + from, + from_params, + alias, + clauses, + }))) +} + +/// The offset of the word after `CREATE [OR REPLACE] [TEMPORARY]`. +fn create_kind_offset>(p: &Parser<'_, D>) -> usize { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + if ["TEMP", "TEMPORARY", "VOLATILE"] + .iter() + .any(|word| p.peek_nth(n).is_word(word)) + { + n += 1; + } + n +} + +fn at_create_object>(p: &Parser<'_, D>) -> bool { + if !p.at_keyword("CREATE") { + return false; + } + let n = create_kind_offset(p); + p.peek_nth(n).is_word("STAGE") + || p.peek_nth(n).is_word("WAREHOUSE") + || (p.peek_nth(n).is_word("FILE") && p.peek_nth(n + 1).is_word("FORMAT")) +} + +fn parse_create_object<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let lifetime = if p.eat_keyword("TEMP") || p.eat_keyword("TEMPORARY") { + Some("TEMPORARY") + } else if p.eat_keyword("VOLATILE") { + Some("VOLATILE") + } else { + None + }; + let kind = if p.eat_keyword("STAGE") { + "STAGE" + } else if p.eat_keyword("WAREHOUSE") { + if lifetime.is_some() { + return Err(p.expected("a warehouse without TEMPORARY or VOLATILE")); + } + "WAREHOUSE" + } else { + p.expect_keyword("FILE")?; + p.expect_keyword("FORMAT")?; + "FILE FORMAT" + }; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + if kind == "WAREHOUSE" { + p.eat_keyword("WITH"); + } + let options = parse_key_values(p)?; + Ok(SnowflakeStatement::CreateObject(Box::new(CreateObject { + or_replace, + lifetime: lifetime.map(Cow::Borrowed), + kind: kind.into(), + if_not_exists, + name, + options, + }))) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("COMMENT") { + return grammar::parse_comment_on(p).map(|c| StatementKind::Comment(Box::new(c)).into()); + } + if ddl::at_create_table(p) { + return ddl::parse_create_table(p); + } + if ddl::at_create_database(p) { + return ddl::parse_create_database(p); + } + if ddl::at_create_view(p) { + return ddl::parse_create_view(p); + } + if p.at_keyword("EXECUTE") && p.peek_nth(1).is_word("IMMEDIATE") { + let execute = oracle::parse_execute_immediate(p)?; + return Ok(StatementKind::Ext(BuiltinStatement::Oracle(execute)).into()); + } + let statement = if at_create_user(p) { + parse_create_user(p)? + } else if at_alter_user(p) { + parse_alter_user(p)? + } else if p.at_keyword("USE") { + parse_use(p)? + } else if ddl::at_alter_iceberg_table(p) { + ddl::parse_alter_iceberg_table(p)? + } else if ddl::at_alter_table_kind(p) { + ddl::parse_alter_table_kind(p)? + } else if ddl::at_block(p) { + ddl::parse_block(p)? + } else if p.at_keyword("RAISE") { + ddl::parse_raise(p)? + } else if p.at_keyword("DECLARE") { + ddl::parse_declare(p)? + } else if ddl::at_set_tuple(p) { + ddl::parse_set_tuple(p)? + } else if at_multi_table_insert(p) { + parse_multi_table_insert(p)? + } else if at_stage_command(p) { + parse_stage_command(p)? + } else if p.at_keyword("PUT") { + parse_put(p)? + } else if p.at_keyword("COPY") && p.peek_nth(1).is_word("INTO") { + parse_copy_into(p)? + } else if at_create_object(p) { + parse_create_object(p)? + } else if p.at_keyword("ALTER") && { + let next = p.peek_nth(1); + next.kind == TokenKind::Word && next.text.eq_ignore_ascii_case("SESSION") + } { + parse_alter_session(p)? + } else { + return grammar::parse_statement(p); + }; + Ok(StatementKind::Ext(BuiltinStatement::Snowflake(statement)).into()) +} + +/// Adds any options that follow a wildcard. +pub fn parse_select_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let identifier_wildcard = + at_identifier_call(p) && p.peek_nth(4).is_op(".") && p.peek_nth(5).is_op("*"); + let item = if identifier_wildcard { + let name = ObjectName { + parts: vec![parse_identifier_call(p)?], + }; + p.advance(); + p.advance(); + SelectItemKind::QualifiedWildcard(name).into() + } else { + grammar::parse_select_item(p)? + }; + let qualifier = match item.kind { + SelectItemKind::Wildcard => None, + SelectItemKind::QualifiedWildcard(ref name) => Some(name.clone()), + other => return Ok(other.into()), + }; + Ok(match grammar::parse_wildcard_options(p)? { + Some(options) => SelectItemKind::WildcardWithOptions { + qualifier, + options: Box::new(options), + } + .into(), + None => item, + }) +} + +/// True at a word followed by `(`, as in `AT(...)`. +fn at_call>(p: &Parser<'_, D>, word: &str) -> bool { + p.at_keyword(word) && p.peek_nth(1).is_op("(") +} + +fn parse_named_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = ObjectName { + parts: vec![p.parse_ident()?], + }; + p.parse_function_call(name) +} + +/// Parses `AT(...)`, `BEFORE(...)` or `CHANGES(...) AT(...) [END(...)]` if one +/// follows the table's name. +fn parse_table_version<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut calls = Vec::new(); + if at_call(p, "CHANGES") { + calls.push(parse_named_call(p)?); + if !(at_call(p, "AT") || at_call(p, "BEFORE")) { + return Err(p.expected("AT or BEFORE")); + } + calls.push(parse_named_call(p)?); + if at_call(p, "END") { + calls.push(parse_named_call(p)?); + } + } else if at_call(p, "AT") || at_call(p, "BEFORE") { + calls.push(parse_named_call(p)?); + } + Ok(calls) +} + +fn parse_semantic_view_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, + list: &mut Vec>, +) -> PResult<()> { + if !list.is_empty() { + return Err(p.expected("each clause of SEMANTIC_VIEW only once")); + } + *list = p.parse_comma_separated(D::parse_function_arg)?; + Ok(()) +} + +/// Parses `SEMANTIC_VIEW(...)`, whose clauses can be in any order. +fn parse_semantic_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let start = p.peek().span.start; + let name = ObjectName { + parts: vec![p.parse_ident()?], + }; + p.advance(); + let args_start = p.peek().span.start; + let mut view = SemanticView { + name: grammar::parse_object_name(p)?, + dimensions: Vec::new(), + metrics: Vec::new(), + facts: Vec::new(), + selection: None, + }; + while !p.at_op(")") { + if p.eat_keyword("DIMENSIONS") { + parse_semantic_view_list(p, &mut view.dimensions)?; + } else if p.eat_keyword("METRICS") { + parse_semantic_view_list(p, &mut view.metrics)?; + } else if p.eat_keyword("FACTS") { + parse_semantic_view_list(p, &mut view.facts)?; + } else if p.at_keyword("WHERE") && view.selection.is_none() { + p.advance(); + view.selection = Some(p.parse_expr()?); + } else { + return Err(p.expected("DIMENSIONS, METRICS, FACTS or WHERE")); + } + } + let arg = Expr::new( + ExprKind::Ext(BuiltinExpr::Snowflake(SnowflakeExpr::SemanticView( + Box::new(view), + ))), + p.span_since(args_start), + ); + p.expect_op(")")?; + Ok(TableFactor::Function { + call: Box::new(Expr::new( + ExprKind::Function { + name, + args: vec![FunctionArg::Expr(arg)], + options: None, + }, + p.span_since(start), + )), + with_ordinality: false, + }) +} + +/// Parses a call's arguments, which can be one unparenthesized query. +pub fn parse_function_args<'a, D: Dialect>( + p: &mut Parser<'a, D>, + quantifier: SetQuantifier, +) -> PResult>> { + if quantifier == SetQuantifier::None && (p.at_keyword("SELECT") || p.at_keyword("WITH")) { + let start = p.peek().span.start; + let query = p.nested(D::parse_query)?; + return Ok(vec![FunctionArg::Expr(Expr::new( + ExprKind::Ext(BuiltinExpr::Snowflake(SnowflakeExpr::BareSubquery( + Box::new(query), + ))), + p.span_since(start), + ))]); + } + grammar::parse_function_args(p, quantifier) +} + +/// True at a join that follows a table without a condition between them, so +/// that the join nests inside the outer one. +fn at_nested_join(p: &Parser<'_, D>) -> bool { + ["JOIN", "INNER", "LEFT", "RIGHT", "FULL"] + .iter() + .any(|word| p.at_keyword(word)) +} + +/// Parses what follows `JOIN`, where a further `JOIN` nests without parentheses. +pub fn parse_join_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + has_constraint: bool, +) -> PResult> { + let relation = p.parse_table_ref()?; + if !has_constraint || !at_nested_join(p) { + return Ok(relation); + } + let joins = p.nested(|p| { + let mut joins = Vec::new(); + while let Some(join) = D::parse_join(p)? { + joins.push(join); + } + Ok(joins) + })?; + Ok(TableRef { + factor: TableFactor::NestedJoin(Box::new(TableWithJoins { relation, joins })), + alias: None, + span: Span::default(), + }) +} + +/// Parses `TOP n`, which here comes after any `DISTINCT` and only takes a number. +pub fn parse_select_head<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + let quantifier = grammar::parse_quantifier(p); + let number = p.peek_nth(1); + let mssql_top = if p.at_keyword("TOP") && number.kind == TokenKind::Number { + p.advance(); + p.advance(); + Some(Box::new(MsSqlTop { + quantity: Expr::new( + ExprKind::Literal(Literal::Number(number.text.into())), + number.span, + ), + parenthesized: false, + percent: false, + with_ties: false, + })) + } else { + None + }; + let modifiers = BuiltinSelect { + mssql_top, + ..Default::default() + }; + Ok((modifiers, quantifier)) +} + +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if at_call(p, "SEMANTIC_VIEW") { + return parse_semantic_view(p); + } + let factor = spark::parse_table_factor(p)?; + let TableFactor::Named(name) = factor else { + return Ok(factor); + }; + let calls = parse_table_version(p)?; + Ok(if calls.is_empty() { + TableFactor::Named(name) + } else { + TableFactor::Versioned { name, calls } + }) +} + +/// Parses what follows `SAMPLE` or `TABLESAMPLE`, which here can name a method +/// and end in a seed. +pub fn parse_sample_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, + long_form: bool, +) -> PResult> { + let method = ["BERNOULLI", "ROW", "SYSTEM", "BLOCK"] + .into_iter() + .find(|method| p.eat_keyword(method)); + let mut clause = grammar::parse_sample_clause(p, long_form)?; + clause.method = method.map(Cow::Borrowed); + clause.seed = grammar::parse_sample_seed(p)?; + Ok(clause) +} + +/// Parses the values after `IN`, which here can be `ANY` or a query. +pub fn parse_pivot_source<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("ANY") { + let order_by = if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + p.parse_comma_separated(D::parse_order_by_item)? + } else { + Vec::new() + }; + return Ok(PivotSource::Any(order_by)); + } + if p.at_keyword("SELECT") || p.at_keyword("WITH") { + return Ok(PivotSource::Query(Box::new(p.nested(D::parse_query)?))); + } + grammar::parse_pivot_source(p) +} + +/// Parses what follows `PIVOT`, which here can end in `DEFAULT ON NULL`. +fn parse_pivot<'a, D: Dialect>( + p: &mut Parser<'a, D>, + table: TableRef<'a, Builtin>, +) -> PResult> { + let mut clause = grammar::parse_pivot_head(p)?; + if p.eat_keyword("DEFAULT") { + p.expect_keyword("ON")?; + p.expect_keyword("NULL")?; + p.expect_op("(")?; + clause.default_on_null = Some(p.parse_expr()?); + p.expect_op(")")?; + } + p.expect_op(")")?; + Ok(TableFactor::Pivot(Box::new(Pivot { table, clause }))) +} + +/// Levels of tree height added for a clause that wraps the table before it, +/// whose nodes take twice the stack of an ordinary level to clone or render. +const TABLE_CLAUSE_LEVELS: usize = 2; + +/// Applies any `PIVOT`, `UNPIVOT` and `SAMPLE` clauses, which can be stacked. +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + parse_table_ref_with(p, parse_alias_before_pivot) +} + +/// Parses a table and its clauses, reading aliases with `parse_alias`. +fn parse_table_ref_with<'a, D, F>( + p: &mut Parser<'a, D>, + parse_alias: F, +) -> PResult> +where + D: Dialect, + F: Fn(&mut Parser<'a, D>) -> PResult>>, +{ + let factor = D::parse_table_factor(p)?; + let alias = parse_alias(p)?; + let mut table = strip_parentheses( + p, + TableRef { + factor, + alias, + span: Span::default(), + }, + )?; + loop { + if p.at_keyword("SAMPLE") || p.at_keyword("TABLESAMPLE") { + let long_form = p.at_keyword("TABLESAMPLE"); + p.advance(); + let sample = D::parse_sample_clause(p, long_form)?; + let factor = TableFactor::Sampled(Box::new(TableSample { table, sample })); + p.deepen_by(TABLE_CLAUSE_LEVELS)?; + table = TableRef { + factor, + alias: None, + span: Span::default(), + }; + continue; + } + let factor = if at_call(p, "PIVOT") { + p.advance(); + parse_pivot(p, table)? + } else if at_call(p, "MATCH_RECOGNIZE") { + p.advance(); + // Rendering this clause takes more stack than the others. + p.deepen()?; + grammar::parse_match_recognize(p, table)? + } else if at_unpivot(p) { + p.advance(); + let clause = grammar::parse_unpivot_clause(p)?; + TableFactor::Unpivot(Box::new(Unpivot { table, clause })) + } else { + return Ok(table); + }; + p.deepen_by(TABLE_CLAUSE_LEVELS)?; + let alias = parse_alias(p)?; + table = TableRef { + factor, + alias, + span: Span::default(), + }; + } +} + +/// Removes parentheses that hold a table and no join. +fn strip_parentheses<'a, D: Dialect>( + p: &Parser<'a, D>, + table: TableRef<'a, Builtin>, +) -> PResult> { + match table.factor { + // Inner parentheses have already been stripped, so one that is left + // around a nested join is what groups it. + TableFactor::NestedJoin(inner) + if inner.joins.is_empty() + && !matches!(inner.relation.factor, TableFactor::NestedJoin(_)) + // An alias cannot be written after a sample's own clause. + && !(table.alias.is_some() + && matches!(inner.relation.factor, TableFactor::Sampled(_))) => + { + if inner.relation.alias.is_some() && table.alias.is_some() { + return Err(p.expected("only one alias for the table")); + } + Ok(TableRef { + alias: inner.relation.alias.or(table.alias), + factor: inner.relation.factor, + span: Span::default(), + }) + } + factor => Ok(TableRef { + factor, + alias: table.alias, + span: Span::default(), + }), + } +} + +fn at_unpivot>(p: &Parser<'_, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("UNPIVOT") + && (next.is_op("(") || next.is_word("INCLUDE") || next.is_word("EXCLUDE")) +} + +/// A table alias that can also be a clause keyword. +fn parse_table_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if clause_word_is_name(p, true) { + return Ok(Some(TableAlias { + name: p.parse_name_part()?, + explicit: false, + columns: Vec::new(), + column_types: Vec::new(), + })); + } + parse_alias_before_pivot(p) +} + +/// `PIVOT` is an ordinary alias unless the rest of the clause follows it. +fn parse_alias_before_pivot<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if at_call(p, "PIVOT") || at_unpivot(p) || at_call(p, "MATCH_RECOGNIZE") { + return Ok(None); + } + grammar::parse_optional_table_alias(p) +} + +pub fn parse_join<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !(p.at_keyword("ASOF") && p.peek_nth(1).is_word("JOIN")) { + return grammar::parse_join(p); + } + p.advance(); + p.advance(); + let table = p.parse_table_ref()?; + p.expect_keyword("MATCH_CONDITION")?; + p.expect_op("(")?; + let condition = p.parse_expr()?; + p.expect_op(")")?; + let constraint = if p.eat_keyword("ON") { + JoinConstraint::On(p.parse_expr()?) + } else if p.eat_keyword("USING") { + JoinConstraint::Using(grammar::parse_ident_list(p)?) + } else { + JoinConstraint::None + }; + Ok(Some(Join { + kind: JoinKind::AsOf, + spelled_out: false, + table, + constraint: JoinConstraint::AsOf { + condition, + constraint: Box::new(constraint), + }, + })) +} + +pub fn parse_set<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + // `@name` is a stage, not a variable. + if p.peek_nth(1).text.starts_with('@') { + p.advance(); + return Err(p.expected("a variable name")); + } + grammar::parse_set(p) +} + +pub fn parse_alter_table_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if p.at_keyword("SWAP") && next.is_word("WITH") { + p.advance(); + p.advance(); + return grammar::parse_object_name(p).map(AlterTableOp::SwapWith); + } + if p.at_keyword("CLUSTER") && next.is_word("BY") { + p.advance(); + p.advance(); + p.expect_op("(")?; + let exprs = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + return Ok(AlterTableOp::ClusterBy(exprs)); + } + if p.at_keyword("DROP") && next.is_word("CLUSTERING") && p.peek_nth(2).is_word("KEY") { + p.advance(); + p.advance(); + p.expect_keyword("KEY")?; + return Ok(AlterTableOp::Phrase("DROP CLUSTERING KEY".into())); + } + if p.at_keyword("SUSPEND") && next.is_word("RECLUSTER") { + p.advance(); + p.advance(); + return Ok(AlterTableOp::Phrase("SUSPEND RECLUSTER".into())); + } + if p.at_keyword("RESUME") && next.is_word("RECLUSTER") { + p.advance(); + p.advance(); + return Ok(AlterTableOp::Phrase("RESUME RECLUSTER".into())); + } + if p.at_keyword("DROP") && next.is_word("PRIMARY") && p.peek_nth(2).is_word("KEY") { + p.advance(); + p.advance(); + p.advance(); + return Ok(AlterTableOp::Phrase( + match grammar::parse_drop_behavior(p) { + Some(DropBehavior::Cascade) => "DROP PRIMARY KEY CASCADE".into(), + Some(DropBehavior::Restrict) => "DROP PRIMARY KEY RESTRICT".into(), + None => "DROP PRIMARY KEY".into(), + }, + )); + } + if p.at_keyword("DROP") && next.is_word("FOREIGN") && p.peek_nth(2).is_word("KEY") { + p.advance(); + p.advance(); + p.advance(); + let name = p.parse_ident()?; + let behavior = grammar::parse_drop_behavior(p); + return Ok(AlterTableOp::DropForeignKey { name, behavior }); + } + match grammar::parse_alter_table_op(p)? { + AlterTableOp::DropColumn { + column_keyword, + if_exists, + name, + behavior: None, + } if at_another_dropped_column(p) => { + let mut names = vec![name]; + while at_another_dropped_column(p) { + p.advance(); + names.push(p.parse_ident()?); + } + Ok(AlterTableOp::DropColumns { + column_keyword, + if_exists, + names, + behavior: grammar::parse_drop_behavior(p), + }) + } + operation => Ok(operation), + } +} + +/// True at a comma before another column of `DROP COLUMN`, not another operation. +fn at_another_dropped_column>(p: &Parser<'_, D>) -> bool { + const OPERATIONS: [&str; 10] = [ + "ADD", "ALTER", "CLUSTER", "DROP", "MODIFY", "RENAME", "RESUME", "SET", "SUSPEND", "SWAP", + ]; + let next = p.peek_nth(1); + p.at_op(",") + && matches!(next.kind, TokenKind::Word | TokenKind::QuotedIdent) + && !OPERATIONS.iter().any(|word| next.is_word(word)) +} + +pub fn parse_explain_target<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("TABLE") { + return Ok(ExplainTarget::Table { + table_keyword: true, + name: grammar::parse_object_name(p)?, + }); + } + grammar::parse_explain_target(p) +} + +pub fn parse_name_part<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::Placeholder && token.text.starts_with('$') { + p.advance(); + return Ok(Ident { + text: token.text.into(), + quote: None, + span: token.span, + }); + } + grammar::parse_name_part(p) +} + +fn at_typed_lambda(p: &Parser<'_, D>) -> bool { + let typed_parameter = if p.at_op("(") { + p.peek_nth(2).kind == TokenKind::Word + } else { + p.peek_nth(1).kind == TokenKind::Word + }; + typed_parameter && clickhouse::at_typed_lambda(p) +} + +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if spark::at_lambda(p) { + return spark::parse_lambda(p); + } + if at_typed_lambda(p) { + return clickhouse::parse_typed_lambda(p); + } + if p.at_op("{") { + return clickhouse::parse_dictionary(p); + } + let token = p.peek(); + if token.kind != TokenKind::Word { + return grammar::parse_prefix(p); + } + // Stage names are only valid where a table is. + if token.text.starts_with('@') { + return Err(p.expected("an expression")); + } + if p.has_context(grammar::CONTEXT_CONNECT_BY) && p.eat_keyword("PRIOR") { + let expr = p.parse_expr_bp(prec::ADD)?; + return Ok(ExprKind::Special(Box::new(SpecialExpr::Prior(expr))).into()); + } + if p.eat_keyword("CONNECT_BY_ROOT") { + let expr = p.parse_expr_bp(prec::UNARY)?; + return Ok(ExprKind::Special(Box::new(SpecialExpr::ConnectByRoot(expr))).into()); + } + grammar::parse_prefix(p) +} + +pub fn parse_qualify<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("QUALIFY") { + p.parse_expr().map(Some) + } else { + Ok(None) + } +} + +pub fn set_operator_rule<'a, D: Dialect>( + p: &Parser<'a, D>, +) -> Option { + grammar::set_operator_rule_with_minus(p) +} + +impl Dialect for Snowflake { + type Ext = Builtin; + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, false) + } + + fn parse_like_quantifier<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Ok(grammar::parse_like_any(p)) + } + + fn parse_update_from_after_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_delete_using<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_delete_using(p) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_variables(p) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn parse_create_schema<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult> { + if flags.temporary { + return Err(p.expected("TABLE or VIEW")); + } + let mut schema = grammar::parse_create_schema_body(p, flags)?; + if p.eat_keyword("CLONE") { + schema.clone = Some(grammar::parse_object_name(p)?); + } + Ok(schema) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref_with(p, parse_table_alias) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_join(p) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_after(prev: Option>, rest: &str) -> Option { + lex_after(prev, rest) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + lex_comment(rest) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + StringLiteral { + backslash_escapes: true, + ..grammar::string_literal(token) + } + } + + #[inline] + fn is_reserved(word: &str) -> bool { + // These start clauses, but only when what follows says so. + if ["LIMIT", "OFFSET", "EXCEPT", "OUTER"] + .iter() + .any(|name| name.eq_ignore_ascii_case(word)) + { + return false; + } + // A prefix operator rather than a name. + word.eq_ignore_ascii_case("CONNECT_BY_ROOT") || grammar::is_reserved(word) + } + + fn parse_interval<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_interval(p, false) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + is_reserved_for_alias(word) + } + + fn check_nested_join<'a>( + _p: &Parser<'a, Self>, + _table: &TableWithJoins<'a, Builtin>, + ) -> PResult<()> { + Ok(()) + } + + fn at_function_call<'a>(p: &Parser<'a, Self>) -> bool { + p.at_op("(") && !at_outer_join_mark(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + ddl::parse_column_option(p) + } + + fn parse_set<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_set(p) + } + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_alter_table_op(p) + } + + fn parse_explain_target<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_explain_target(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + grammar::eat_drop_object_type(p, &["STAGE", "STREAM", "WAREHOUSE"]) + } + + fn parse_name_part<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_name_part(p) + } + + fn parse_connect_by<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + grammar::parse_connect_by_clauses(p) + } + + fn parse_sample_clause<'a>( + p: &mut Parser<'a, Self>, + long_form: bool, + ) -> PResult> { + parse_sample_clause(p, long_form) + } + + fn parse_pivot_source<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_pivot_source(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_projection<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_list_with_trailing_comma(p, Parser::parse_select_item) + } + + fn parse_from_list<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_list_with_trailing_comma(p, Self::parse_table_with_joins) + } + + fn parse_qualify<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_qualify(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_object_name_part<'a>( + p: &mut Parser<'a, Self>, + before: &[Ident<'a>], + ) -> PResult> { + parse_object_name_part(p, before) + } + + fn parse_join_table<'a>( + p: &mut Parser<'a, Self>, + has_constraint: bool, + ) -> PResult> { + parse_join_table(p, has_constraint) + } + + fn parse_function_args<'a>( + p: &mut Parser<'a, Self>, + quantifier: SetQuantifier, + ) -> PResult>> { + parse_function_args(p, quantifier) + } + + fn parse_function_arg_null_treatment<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult> { + Ok(grammar::parse_null_treatment(p)) + } + + fn parse_select_head<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult<(BuiltinSelect<'a>, SetQuantifier)> { + parse_select_head(p) + } + + fn parse_extract_field<'a>(p: &mut Parser<'a, Self>) -> PResult<&'a str> { + let token = p.peek(); + if matches!(token.kind, TokenKind::Word | TokenKind::String) { + p.advance(); + return Ok(token.text); + } + Err(p.expected("a date or time field")) + } + + fn parse_insert_modifiers<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Ok(BuiltinInsert { + overwrite: p.eat_keyword("OVERWRITE"), + ..Default::default() + }) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + ddl::parse_data_type(p) + } + + fn parse_query_order_by<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + duckdb::parse_query_order_by(p) + } + + fn eat_group_by_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_add_column_if_not_exists<'a>(p: &mut Parser<'a, Self>) -> PResult { + grammar::parse_if_not_exists(p) + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + set_operator_rule(p) + } +} + +impl fmt::Display for SnowflakeExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SnowflakeExpr::Path { value, path } => { + fmt::Display::fmt(&**value, f)?; + // A path always starts with `:`, even before an index. + if !matches!(path.first(), Some(PathElement::Colon(_))) { + f.write_str(":")?; + } + for element in path { + match element { + PathElement::Colon(key) => write!(f, ":{key}")?, + PathElement::Dot(key) => write!(f, ".{key}")?, + PathElement::Index(index) => write!(f, "[{index}]")?, + } + } + Ok(()) + } + SnowflakeExpr::BareSubquery(query) => query.fmt(f), + SnowflakeExpr::SemanticView(view) => view.fmt(f), + } + } +} + +impl fmt::Display for KeyValue<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let spaced = ["FILES", "PATTERN", "VALIDATION_MODE"] + .iter() + .any(|key| self.key.text.eq_ignore_ascii_case(key)); + write!(f, "{}{}", self.key, if spaced { " = " } else { "=" })?; + write_value(f, &self.value) + } +} + +fn write_value(f: &mut fmt::Formatter<'_>, value: &OptionValue<'_>) -> fmt::Result { + match value { + OptionValue::Word(word) => f.write_str(word), + OptionValue::Literal(literal) => write!(f, "{literal}"), + OptionValue::List(strings) => { + f.write_str("(")?; + for (i, string) in strings.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{}", string)?; + } + f.write_str(")") + } + OptionValue::Nested(options) => { + f.write_str("(")?; + for (i, option) in options.iter().enumerate() { + if i > 0 { + f.write_str(" ")?; + } + write!(f, "{option}")?; + } + f.write_str(")") + } + } +} + +impl fmt::Display for CopyLocation<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CopyLocation::Name(name) => write!(f, "{name}"), + CopyLocation::Stage(stage) => write!(f, "{stage}"), + CopyLocation::Url(url) => write!(f, "{}", url), + } + } +} + +fn write_key_values(f: &mut fmt::Formatter<'_>, options: &[KeyValue<'_>]) -> fmt::Result { + for option in options { + write!(f, " {option}")?; + } + Ok(()) +} + +impl fmt::Display for CopyInto<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "COPY INTO {}", self.into)?; + write_key_values(f, &self.into_params)?; + if !self.columns.is_empty() { + f.write_str(" (")?; + write!(f, "{}", comma(&self.columns))?; + f.write_str(")")?; + } + match &self.from { + CopySource::Query(query) => write!(f, " FROM ({query})")?, + CopySource::Location(location) => write!(f, " FROM {location}")?, + } + write_key_values(f, &self.from_params)?; + if let Some(alias) = &self.alias { + write!(f, " AS {alias}")?; + } + for clause in &self.clauses { + match clause { + CopyClause::Option(option) => write!(f, " {option}")?, + CopyClause::PartitionBy(expr) => write!(f, " PARTITION BY {expr}")?, + } + } + Ok(()) + } +} + +impl fmt::Display for CreateObject<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + if let Some(ref lifetime) = self.lifetime { + write!(f, "{lifetime} ")?; + } + write!(f, "{} ", self.kind)?; + if self.if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + write!(f, "{}", self.name)?; + write_key_values(f, &self.options) + } +} + +fn write_options( + f: &mut fmt::Formatter<'_>, + options: &[(Ident<'_>, Expr<'_, Builtin>)], +) -> fmt::Result { + for (key, value) in options { + write!(f, " {key}={value}")?; + } + Ok(()) +} + +impl fmt::Display for InsertTarget<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "INTO {}", self.table)?; + if !self.columns.is_empty() { + f.write_str(" (")?; + write!(f, "{}", comma(&self.columns))?; + f.write_str(")")?; + } + if let Some(values) = &self.values { + f.write_str(" VALUES (")?; + for (i, value) in values.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{value}")?; + } + f.write_str(")")?; + } + Ok(()) + } +} + +fn write_targets(f: &mut fmt::Formatter<'_>, targets: &[InsertTarget<'_>]) -> fmt::Result { + for target in targets { + SpaceOrNewline.fmt(f)?; + target.fmt(f)?; + } + Ok(()) +} + +impl fmt::Display for MultiTableInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("INSERT")?; + if self.overwrite { + f.write_str(" OVERWRITE")?; + } + f.write_str(if self.first { " FIRST" } else { " ALL" })?; + write_targets(f, &self.into)?; + for when in &self.when { + SpaceOrNewline.fmt(f)?; + write!(f, "WHEN {} THEN", when.condition)?; + for target in &when.into { + write!(f, " {target}")?; + } + } + if !self.otherwise.is_empty() { + SpaceOrNewline.fmt(f)?; + f.write_str("ELSE")?; + write_targets(f, &self.otherwise)?; + } + SpaceOrNewline.fmt(f)?; + self.source.fmt(f) + } +} + +impl fmt::Display for SnowflakeStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SnowflakeStatement::CreateUser(create) => create.fmt(f), + SnowflakeStatement::AlterUser(alter) => alter.fmt(f), + SnowflakeStatement::Use { kind, name } => { + f.write_str("USE ")?; + if let Some(kind) = kind { + write!(f, "{kind} ")?; + } + write!(f, "{name}") + } + SnowflakeStatement::UseSecondaryRoles(roles) => { + f.write_str("USE SECONDARY ROLES ")?; + match roles { + SecondaryRoles::All => f.write_str("ALL"), + SecondaryRoles::None => f.write_str("NONE"), + SecondaryRoles::List(names) => write!(f, "{}", comma(names)), + } + } + SnowflakeStatement::AlterSessionSet(options) => { + f.write_str("ALTER SESSION SET")?; + for (key, value) in options { + write!(f, " {key}={value}")?; + } + Ok(()) + } + SnowflakeStatement::AlterSessionUnset(names) => { + f.write_str("ALTER SESSION UNSET ")?; + write!(f, "{}", comma(names)) + } + SnowflakeStatement::MultiTableInsert(insert) => insert.fmt(f), + SnowflakeStatement::CreateTable(create) => create.fmt(f), + SnowflakeStatement::CreateDatabase(create) => create.fmt(f), + SnowflakeStatement::CreateView(create) => create.fmt(f), + SnowflakeStatement::AlterIcebergTable(alter) => { + ddl::write_alter_iceberg_table(f, alter) + } + SnowflakeStatement::AlterTableKind { + dynamic, + if_exists, + name, + action, + subpath, + } => { + let kind = if *dynamic { "DYNAMIC" } else { "EXTERNAL" }; + let if_exists = if *if_exists { "IF EXISTS " } else { "" }; + write!(f, "ALTER {kind} TABLE {if_exists}{name} {action}")?; + match subpath { + Some(path) => write!(f, " {}", path), + None => Ok(()), + } + } + SnowflakeStatement::Block(block) => block.fmt(f), + SnowflakeStatement::Raise(None) => f.write_str("RAISE"), + SnowflakeStatement::Raise(Some(value)) => write!(f, "RAISE {value}"), + SnowflakeStatement::Declare(declarations) => ddl::write_declare(f, declarations), + SnowflakeStatement::SetTuple { names, values } => { + ddl::write_set_tuple(f, names, values) + } + SnowflakeStatement::CopyInto(copy) => copy.fmt(f), + SnowflakeStatement::CreateObject(create) => create.fmt(f), + SnowflakeStatement::StageCommand { + remove, + stage, + options, + } => { + let command = if *remove { "REMOVE" } else { "LIST" }; + write!(f, "{command} {stage}")?; + write_options(f, options) + } + SnowflakeStatement::Put { + file, + stage, + options, + } => { + write!(f, "PUT {} {stage}", file)?; + write_options(f, options) + } + } + } +} + +/// `key = value` in a user's properties. +#[derive(Debug, Clone, PartialEq)] +pub struct UserProperty<'a> { + pub key: Ident<'a>, + pub value: UserValue<'a>, +} + +/// The value of a user property. +#[derive(Debug, Clone, PartialEq)] +pub enum UserValue<'a> { + Expr(Expr<'a, Builtin>), + /// `('a', 'b')` + List(Vec>), + /// `(KEY=value, ...)` + Properties(Vec>), +} + +/// `CREATE [OR REPLACE] USER [IF NOT EXISTS] name [properties] [[WITH] TAG (...)]` +#[derive(Debug, Clone, PartialEq)] +pub struct CreateUser<'a> { + pub or_replace: bool, + pub if_not_exists: bool, + pub name: Ident<'a>, + pub properties: Vec>, + pub with_tag: bool, + pub tags: Vec>, +} + +/// What `ALTER USER` does. +#[derive(Debug, Clone, PartialEq)] +pub enum AlterUserAction<'a> { + Rename(Ident<'a>), + ResetPassword, + AbortAllQueries, + AddDelegatedAuthorization { + role: Ident<'a>, + integration: Ident<'a>, + }, + /// With no role, `AUTHORIZATIONS` removes every one. + RemoveDelegatedAuthorization { + role: Option>, + integration: Ident<'a>, + }, + EnrollMfa, + AddMfaMethodOtp { + count: Option>, + }, + ModifyMfaMethod { + method: Cow<'a, str>, + comment: StringLiteral<'a>, + }, + RemoveMfaMethod(Cow<'a, str>), + SetDefaultMfaMethod(Cow<'a, str>), + /// `AUTHENTICATION`, `PASSWORD` or `SESSION`. + SetPolicy { + kind: Cow<'a, str>, + policy: Ident<'a>, + }, + UnsetPolicy(Cow<'a, str>), + SetTag(Vec>), + UnsetTag(Vec>), + SetProperties(Vec>), + UnsetProperties(Vec>), +} + +/// `ALTER USER [IF EXISTS] name action` +#[derive(Debug, Clone, PartialEq)] +pub struct AlterUser<'a> { + pub if_exists: bool, + pub name: Ident<'a>, + pub action: AlterUserAction<'a>, +} + +const USER_POLICY_KINDS: [&str; 3] = ["AUTHENTICATION", "PASSWORD", "SESSION"]; +const MFA_METHODS: [&str; 3] = ["PASSKEY", "TOTP", "DUO"]; + +fn parse_mfa_method<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.peek(); + if !MFA_METHODS.iter().any(|method| token.is_word(method)) { + return Err(p.expected("PASSKEY, TOTP or DUO")); + } + p.advance(); + Ok(token.text) +} + +fn parse_user_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.eat_op("(") { + return p.parse_expr().map(UserValue::Expr); + } + if p.eat_op(")") { + return Ok(UserValue::List(Vec::new())); + } + if p.at_ident() && p.peek_nth(1).is_op("=") { + let properties = p.parse_comma_separated(|p| p.nested(parse_user_property))?; + p.expect_op(")")?; + return Ok(UserValue::Properties(properties)); + } + let items = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(UserValue::List(items)) +} + +fn parse_user_property<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let key = p.parse_ident()?; + p.expect_op("=")?; + Ok(UserProperty { + key, + value: parse_user_value(p)?, + }) +} + +fn at_user_property>(p: &Parser<'_, D>) -> bool { + p.at_ident() && p.peek_nth(1).is_op("=") +} + +/// True at `CREATE [OR REPLACE] USER`. +pub fn at_create_user>(p: &Parser<'_, D>) -> bool { + let n = if p.peek_nth(1).is_word("OR") { 3 } else { 1 }; + p.at_keyword("CREATE") && p.peek_nth(n).is_word("USER") +} + +pub fn parse_create_user<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + p.expect_keyword("USER")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = p.parse_ident()?; + let mut properties = Vec::new(); + while at_user_property(p) { + properties.push(parse_user_property(p)?); + } + let with_tag = p.at_keyword("WITH") && p.peek_nth(1).is_word("TAG"); + if with_tag { + p.advance(); + } + let tags = if p.at_keyword("TAG") && p.peek_nth(1).is_op("(") { + p.advance(); + p.advance(); + let tags = p.parse_comma_separated(parse_user_property)?; + p.expect_op(")")?; + tags + } else { + Vec::new() + }; + Ok(SnowflakeStatement::CreateUser(Box::new(CreateUser { + or_replace, + if_not_exists, + name, + properties, + with_tag, + tags, + }))) +} + +/// Parses what follows `ALTER USER name`, or returns `None` if nothing follows. +fn parse_alter_user_action<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + if p.eat_keyword("RENAME") { + p.expect_keyword("TO")?; + return p.parse_ident().map(AlterUserAction::Rename); + } + if p.at_keyword("RESET") && next.is_word("PASSWORD") { + p.advance(); + p.advance(); + return Ok(AlterUserAction::ResetPassword); + } + if p.eat_keyword("ABORT") { + p.expect_keyword("ALL")?; + p.expect_keyword("QUERIES")?; + return Ok(AlterUserAction::AbortAllQueries); + } + if p.at_keyword("ADD") && next.is_word("DELEGATED") { + p.advance(); + p.advance(); + p.expect_keyword("AUTHORIZATION")?; + p.expect_keyword("OF")?; + p.expect_keyword("ROLE")?; + let role = p.parse_ident()?; + p.expect_keyword("TO")?; + p.expect_keyword("SECURITY")?; + p.expect_keyword("INTEGRATION")?; + let integration = p.parse_ident()?; + return Ok(AlterUserAction::AddDelegatedAuthorization { role, integration }); + } + if p.at_keyword("REMOVE") && next.is_word("DELEGATED") { + p.advance(); + p.advance(); + let role = if p.eat_keyword("AUTHORIZATIONS") { + None + } else { + p.expect_keyword("AUTHORIZATION")?; + p.expect_keyword("OF")?; + p.expect_keyword("ROLE")?; + Some(p.parse_ident()?) + }; + p.expect_keyword("FROM")?; + p.expect_keyword("SECURITY")?; + p.expect_keyword("INTEGRATION")?; + let integration = p.parse_ident()?; + return Ok(AlterUserAction::RemoveDelegatedAuthorization { role, integration }); + } + if p.at_keyword("ENROLL") && next.is_word("MFA") { + p.advance(); + p.advance(); + return Ok(AlterUserAction::EnrollMfa); + } + if p.at_keyword("ADD") && next.is_word("MFA") { + p.advance(); + p.advance(); + p.expect_keyword("METHOD")?; + p.expect_keyword("OTP")?; + let count = if p.eat_keyword("COUNT") { + p.expect_op("=")?; + Some(grammar::parse_number_text(p)?) + } else { + None + }; + return Ok(AlterUserAction::AddMfaMethodOtp { + count: count.map(Cow::Borrowed), + }); + } + if p.at_keyword("MODIFY") && next.is_word("MFA") { + p.advance(); + p.advance(); + p.expect_keyword("METHOD")?; + let method = parse_mfa_method(p)?; + p.expect_keyword("SET")?; + p.expect_keyword("COMMENT")?; + let comment = grammar::parse_string(p)?; + return Ok(AlterUserAction::ModifyMfaMethod { + method: method.into(), + comment, + }); + } + if p.at_keyword("REMOVE") && next.is_word("MFA") { + p.advance(); + p.advance(); + p.expect_keyword("METHOD")?; + return parse_mfa_method(p).map(|v| AlterUserAction::RemoveMfaMethod(v.into())); + } + let unset = p.at_keyword("UNSET"); + if !unset && !p.at_keyword("SET") { + return Err(p.expected("an ALTER USER action")); + } + p.advance(); + if let Some(kind) = USER_POLICY_KINDS + .into_iter() + .find(|kind| p.at_keyword(kind) && p.peek_nth(1).is_word("POLICY")) + { + p.advance(); + p.advance(); + return Ok(if unset { + AlterUserAction::UnsetPolicy(kind.into()) + } else { + AlterUserAction::SetPolicy { + kind: kind.into(), + policy: p.parse_ident()?, + } + }); + } + if !unset && p.eat_keyword("DEFAULT_MFA_METHOD") { + return parse_mfa_method(p).map(|v| AlterUserAction::SetDefaultMfaMethod(v.into())); + } + if p.eat_keyword("TAG") { + return Ok(if unset { + AlterUserAction::UnsetTag(p.parse_comma_separated(Parser::parse_ident)?) + } else { + AlterUserAction::SetTag(p.parse_comma_separated(parse_user_property)?) + }); + } + if unset { + return p + .parse_comma_separated(Parser::parse_ident) + .map(AlterUserAction::UnsetProperties); + } + p.parse_comma_separated(parse_user_property) + .map(AlterUserAction::SetProperties) +} + +pub fn at_alter_user>(p: &Parser<'_, D>) -> bool { + p.at_keyword("ALTER") && p.peek_nth(1).is_word("USER") +} + +pub fn parse_alter_user<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + let if_exists = p.at_keyword("IF") && p.peek_nth(1).is_word("EXISTS"); + if if_exists { + p.advance(); + p.advance(); + } + let name = p.parse_ident()?; + let action = parse_alter_user_action(p)?; + Ok(SnowflakeStatement::AlterUser(Box::new(AlterUser { + if_exists, + name, + action, + }))) +} + +impl fmt::Display for UserValue<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Expr(expr) => expr.fmt(f), + Self::List(items) => write!(f, "({})", comma(items)), + Self::Properties(properties) => write!(f, "({})", comma(properties)), + } + } +} + +impl fmt::Display for UserProperty<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}={}", self.key, self.value) + } +} + +impl fmt::Display for CreateUser<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + f.write_str("USER ")?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + for property in &self.properties { + write!(f, " {property}")?; + } + if !self.tags.is_empty() { + let with = if self.with_tag { "WITH " } else { "" }; + write!(f, " {with}TAG ({})", comma(&self.tags))?; + } + Ok(()) + } +} + +impl fmt::Display for AlterUser<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ALTER USER ")?; + if self.if_exists { + f.write_str("IF EXISTS ")?; + } + write!(f, "{} ", self.name)?; + match &self.action { + AlterUserAction::Rename(name) => write!(f, "RENAME TO {name}"), + AlterUserAction::ResetPassword => f.write_str("RESET PASSWORD"), + AlterUserAction::AbortAllQueries => f.write_str("ABORT ALL QUERIES"), + AlterUserAction::AddDelegatedAuthorization { role, integration } => write!( + f, + "ADD DELEGATED AUTHORIZATION OF ROLE {role} TO SECURITY INTEGRATION {integration}" + ), + AlterUserAction::RemoveDelegatedAuthorization { + role: Some(role), + integration, + } => write!( + f, + "REMOVE DELEGATED AUTHORIZATION OF ROLE {role} FROM SECURITY INTEGRATION {integration}" + ), + AlterUserAction::RemoveDelegatedAuthorization { + role: None, + integration, + } => write!( + f, + "REMOVE DELEGATED AUTHORIZATIONS FROM SECURITY INTEGRATION {integration}" + ), + AlterUserAction::EnrollMfa => f.write_str("ENROLL MFA"), + AlterUserAction::AddMfaMethodOtp { count } => { + f.write_str("ADD MFA METHOD OTP")?; + match count { + Some(count) => write!(f, " COUNT = {count}"), + None => Ok(()), + } + } + AlterUserAction::ModifyMfaMethod { method, comment } => { + write!(f, "MODIFY MFA METHOD {method} SET COMMENT {}", comment) + } + AlterUserAction::RemoveMfaMethod(method) => write!(f, "REMOVE MFA METHOD {method}"), + AlterUserAction::SetDefaultMfaMethod(method) => { + write!(f, "SET DEFAULT_MFA_METHOD {method}") + } + AlterUserAction::SetPolicy { kind, policy } => { + write!(f, "SET {kind} POLICY {policy}") + } + AlterUserAction::UnsetPolicy(kind) => write!(f, "UNSET {kind} POLICY"), + AlterUserAction::SetTag(tags) => write!(f, "SET TAG {}", comma(tags)), + AlterUserAction::UnsetTag(tags) => write!(f, "UNSET TAG {}", comma(tags)), + AlterUserAction::SetProperties(properties) => { + write!(f, "SET {}", comma(properties)) + } + AlterUserAction::UnsetProperties(names) => write!(f, "UNSET {}", comma(names)), + } + } +} diff --git a/sqlparser_v2/src/dialect/snowflake/ddl.rs b/sqlparser_v2/src/dialect/snowflake/ddl.rs new file mode 100644 index 0000000000..4781891da2 --- /dev/null +++ b/sqlparser_v2/src/dialect/snowflake/ddl.rs @@ -0,0 +1,1405 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Snowflake's table and database options, scripting and `DECLARE`. + +use std::borrow::Cow; +use std::fmt::{self, Display}; + +use super::{KeyValue, SnowflakeStatement, parse_key_value, parse_named_call, write_value}; +use crate::PResult; +use crate::ast::{ + AlterTable, AngleArguments, ColumnDef, ColumnOption, CreateDatabase, CreateTable, CreateView, + DataType, Expr, ExprKind, FunctionArg, Ident, IdentityParams, Literal, ObjectName, Query, + Statement, StatementKind, StringLiteral, StructField, TableConstraint, Tag, +}; +use crate::dialect::builtin::BuiltinStatement; +use crate::dialect::{Builtin, Dialect}; +use crate::display::write_columns; +use crate::grammar; +use crate::lexer::TokenKind; +use crate::parser::Parser; + +/// A `CREATE TABLE` using syntax the core statement cannot hold. +#[derive(Debug, Clone, PartialEq)] +pub struct SnowflakeCreateTable<'a> { + pub or_replace: bool, + /// `LOCAL` or `GLOBAL`. + pub scope: Option>, + pub dynamic: bool, + /// `TEMPORARY`, `VOLATILE`, `TRANSIENT` or `ICEBERG`. + pub lifetime: Option>, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub columns: Vec>, + pub constraints: Vec>, + /// In the order written, apart from the ones that render first. + pub clauses: Vec>, + pub query: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TableClause<'a> { + CopyGrants, + /// `COMMENT [=] 'text'` + Comment { + equals: bool, + text: StringLiteral<'a>, + }, + Clone(ObjectName<'a>), + Like(ObjectName<'a>), + /// `AT(...)` or `BEFORE(...)` after `CLONE`. + Version(Expr<'a, Builtin>), + ClusterBy(Vec>), + Option(KeyValue<'a>), + /// `WITH kind name [ON (columns)]` + Policy { + kind: Cow<'a, str>, + name: ObjectName<'a>, + on: Vec>, + }, + Tags(Vec>), + OnCommit(Cow<'a, str>), + RequireUser, +} + +impl TableClause<'_> { + fn renders_first(&self) -> bool { + matches!( + self, + TableClause::Clone(_) | TableClause::Like(_) | TableClause::Version(_) + ) + } + + fn names_a_source(&self) -> bool { + matches!(self, TableClause::Clone(_) | TableClause::Like(_)) + } +} + +/// A `CREATE DATABASE` using syntax the core statement cannot hold. +#[derive(Debug, Clone, PartialEq)] +pub struct SnowflakeCreateDatabase<'a> { + pub or_replace: bool, + pub transient: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub clauses: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DatabaseClause<'a> { + Clone(ObjectName<'a>), + Option(KeyValue<'a>), + Tags(Vec>), + /// `WITH CONTACT (purpose = contact, ...)` + Contacts(Vec<(Ident<'a>, Ident<'a>)>), +} + +/// A `CREATE VIEW` using syntax the core statement cannot hold. +#[derive(Debug, Clone, PartialEq)] +pub struct SnowflakeCreateView<'a> { + pub or_replace: bool, + pub secure: bool, + pub materialized: bool, + pub temporary: bool, + pub if_not_exists: bool, + /// True if `IF NOT EXISTS` was written after the name. + pub if_not_exists_after_name: bool, + pub name: ObjectName<'a>, + pub copy_grants: bool, + pub columns: Vec>, + pub cluster_by: Vec>, + pub comment: Option>, + pub query: Box>, +} + +/// A column of a view, with its options. +#[derive(Debug, Clone, PartialEq)] +pub struct ViewColumn<'a> { + pub name: Ident<'a>, + pub options: Vec>, +} + +/// The arguments of `SEMANTIC_VIEW(...)`. +#[derive(Debug, Clone, PartialEq)] +pub struct SemanticView<'a> { + pub name: ObjectName<'a>, + pub dimensions: Vec>, + pub metrics: Vec>, + pub facts: Vec>, + pub selection: Option>, +} + +/// `BEGIN ... [EXCEPTION ...] END` +#[derive(Debug, Clone, PartialEq)] +pub struct Block<'a> { + pub statements: Vec>, + pub exception: Option>>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ExceptionWhen<'a> { + pub names: Vec>, + pub statements: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum RaiseValue<'a> { + Expr(Expr<'a, Builtin>), + Message(Expr<'a, Builtin>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Declaration<'a> { + pub name: Ident<'a>, + pub kind: DeclarationKind<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DeclarationKind<'a> { + Variable { + data_type: Option>, + value: Option>, + }, + ResultSet(Option>), + /// `CURSOR FOR query` + CursorQuery(Box>), + /// `CURSOR FOR expr` + CursorExpr(Expr<'a, Builtin>), + Exception(Option>), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Assignment<'a> { + /// `DEFAULT expr` + Default(Expr<'a, Builtin>), + /// `:= expr` + Walrus(Expr<'a, Builtin>), +} + +/// The offset of the word after `CREATE` and its modifiers. +fn create_object_offset>(p: &Parser<'_, D>) -> usize { + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + for words in [ + &["LOCAL", "GLOBAL"][..], + &["DYNAMIC"], + &["TEMP", "TEMPORARY", "VOLATILE", "TRANSIENT", "ICEBERG"], + ] { + if words.iter().any(|word| p.peek_nth(n).is_word(word)) { + n += 1; + } + } + n +} + +pub fn at_create_table>(p: &Parser<'_, D>) -> bool { + p.at_keyword("CREATE") && (p.peek_nth(create_object_offset(p))).is_word("TABLE") +} + +pub fn at_create_database>(p: &Parser<'_, D>) -> bool { + p.at_keyword("CREATE") && (p.peek_nth(create_object_offset(p))).is_word("DATABASE") +} + +pub fn at_create_view>(p: &Parser<'_, D>) -> bool { + if !p.at_keyword("CREATE") { + return false; + } + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + for words in [ + &["SECURE"][..], + &["TEMP", "TEMPORARY"], + &["SECURE"], + &["MATERIALIZED"], + ] { + if words.iter().any(|word| p.peek_nth(n).is_word(word)) { + n += 1; + } + } + p.peek_nth(n).is_word("VIEW") +} + +fn first_of>( + p: &mut Parser<'_, D>, + words: &[&'static str], +) -> Option<&'static str> { + words.iter().copied().find(|word| p.eat_keyword(word)) +} + +/// Parses a comment's text, which can be dollar-quoted. +pub fn parse_comment<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + match p.parse_prefix()?.kind { + ExprKind::Literal(Literal::String(text)) => Ok(text), + ExprKind::Literal(Literal::DollarQuoted { text, tag }) => { + // Only a body with nothing to escape means the same in single quotes. + let plain = !text.contains(['\'', '\\']); + if !plain && !tag.is_empty() { + return Err(p.expected("a comment in plain dollar quotes")); + } + Ok(StringLiteral { + text, + quote: if plain { '\'' } else { '$' }, + backslash_escapes: false, + national: false, + prefix: Default::default(), + triple: false, + }) + } + _ => Err(p.expected("a string")), + } +} + +fn parse_tag<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = grammar::parse_object_name(p)?; + p.expect_op("=")?; + let token = p.expect_kind(TokenKind::String, "a string")?; + Ok(Tag { + name, + value: D::string_literal(token), + }) +} + +fn parse_tags<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + p.expect_op("(")?; + let tags = p.parse_comma_separated(parse_tag)?; + p.expect_op(")")?; + Ok(tags) +} + +/// Parses a policy's name and its `ON (columns)`. +fn parse_policy_on<'a, D: Dialect>( + p: &mut Parser<'a, D>, + kind: &'static str, +) -> PResult> { + let name = grammar::parse_object_name(p)?; + p.expect_keyword("ON")?; + let on = grammar::parse_ident_list(p)?; + Ok(TableClause::Policy { + kind: kind.into(), + name, + on, + }) +} + +fn parse_on_commit>(p: &mut Parser<'_, D>) -> PResult<&'static str> { + if p.eat_keyword("DROP") { + return Ok("DROP"); + } + let action = if p.eat_keyword("PRESERVE") { + "PRESERVE ROWS" + } else { + p.expect_keyword("DELETE")?; + "DELETE ROWS" + }; + p.expect_keyword("ROWS")?; + Ok(action) +} + +const TABLE_OPTIONS: [&str; 14] = [ + "ENABLE_SCHEMA_EVOLUTION", + "CHANGE_TRACKING", + "DATA_RETENTION_TIME_IN_DAYS", + "MAX_DATA_EXTENSION_TIME_IN_DAYS", + "DEFAULT_DDL_COLLATION", + "EXTERNAL_VOLUME", + "CATALOG", + "BASE_LOCATION", + "CATALOG_SYNC", + "STORAGE_SERIALIZATION_POLICY", + "TARGET_LAG", + "WAREHOUSE", + "REFRESH_MODE", + "INITIALIZE", +]; + +const DATABASE_OPTIONS: [&str; 11] = [ + "DATA_RETENTION_TIME_IN_DAYS", + "MAX_DATA_EXTENSION_TIME_IN_DAYS", + "EXTERNAL_VOLUME", + "CATALOG", + "REPLACE_INVALID_CHARACTERS", + "DEFAULT_DDL_COLLATION", + "STORAGE_SERIALIZATION_POLICY", + "COMMENT", + "CATALOG_SYNC", + "CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER", + "CATALOG_SYNC_NAMESPACE_MODE", +]; + +/// True at `key =` for one of `keys`. +fn at_option>(p: &Parser<'_, D>, keys: &[&str]) -> bool { + p.peek_nth(1).is_op("=") && keys.iter().any(|key| p.at_keyword(key)) +} + +/// Parses one clause, or returns `None` at the end of them. +fn parse_table_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let clause = if p.eat_keyword("COPY") { + p.expect_keyword("GRANTS")?; + TableClause::CopyGrants + } else if p.eat_keyword("COMMENT") { + let equals = p.eat_op("="); + TableClause::Comment { + equals, + text: parse_comment(p)?, + } + } else if p.eat_keyword("CLONE") { + TableClause::Clone(grammar::parse_object_name(p)?) + } else if p.eat_keyword("LIKE") { + TableClause::Like(grammar::parse_object_name(p)?) + } else if (p.at_keyword("AT") || p.at_keyword("BEFORE")) && p.peek_nth(1).is_op("(") { + TableClause::Version(parse_named_call(p)?) + } else if p.eat_keyword("CLUSTER") { + p.expect_keyword("BY")?; + p.expect_op("(")?; + let exprs = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + TableClause::ClusterBy(exprs) + } else if p.eat_keyword("AGGREGATION") { + p.expect_keyword("POLICY")?; + TableClause::Policy { + kind: "AGGREGATION POLICY".into(), + name: grammar::parse_object_name(p)?, + on: Vec::new(), + } + } else if p.at_keyword("ROW") && p.peek_nth(1).is_word("ACCESS") { + p.advance(); + p.expect_keywords(&["ACCESS", "POLICY"])?; + parse_policy_on(p, "ROW ACCESS POLICY")? + } else if p.at_keyword("STORAGE") && p.peek_nth(1).is_word("LIFECYCLE") { + p.advance(); + p.expect_keywords(&["LIFECYCLE", "POLICY"])?; + parse_policy_on(p, "STORAGE LIFECYCLE POLICY")? + } else if p.eat_keyword("TAG") { + TableClause::Tags(parse_tags(p)?) + } else if p.at_keyword("ON") && p.peek_nth(1).is_word("COMMIT") { + p.advance(); + p.advance(); + TableClause::OnCommit(parse_on_commit(p)?.into()) + } else if p.at_keyword("REQUIRE") && p.peek_nth(1).is_word("USER") { + p.advance(); + p.advance(); + TableClause::RequireUser + } else if at_option(p, &TABLE_OPTIONS) { + TableClause::Option(parse_key_value(p)?) + } else { + return Ok(None); + }; + Ok(Some(clause)) +} + +/// True at a `WITH` that only introduces the next table clause. +fn at_optional_with>(p: &Parser<'_, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("WITH") + && ["AGGREGATION", "STORAGE", "TAG", "ROW"] + .iter() + .any(|word| next.is_word(word)) +} + +pub fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let scope = first_of(p, &["LOCAL", "GLOBAL"]); + let dynamic = p.eat_keyword("DYNAMIC"); + let lifetime = if p.eat_keyword("TEMP") || p.eat_keyword("TEMPORARY") { + Some("TEMPORARY") + } else { + first_of(p, &["VOLATILE", "TRANSIENT", "ICEBERG"]) + }; + p.expect_keyword("TABLE")?; + let mut if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + + let mut columns = Vec::new(); + let mut constraints = Vec::new(); + let mut clauses = Vec::new(); + let mut query = None; + // Snowflake does not enforce an order on these. + loop { + if p.at_op("(") && p.peek_nth(1).is_op(")") { + p.advance(); + p.advance(); + } else if p.at_op("(") { + if !columns.is_empty() || !constraints.is_empty() { + return Err(p.expected("only one column list")); + } + (columns, constraints) = grammar::parse_columns(p)?; + } else if p.eat_keyword("AS") { + query = Some(Box::new(D::parse_query(p)?)); + } else if p.at_keyword("IF") { + if_not_exists = grammar::parse_if_not_exists(p)?; + if !if_not_exists { + return Err(p.expected("IF NOT EXISTS")); + } + } else { + if at_optional_with(p) { + p.advance(); + } + match parse_table_clause(p)? { + Some(clause) => clauses.push(clause), + None => break, + } + } + } + + let has_base_location = clauses.iter().any(|clause| { + matches!(clause, TableClause::Option(option) + if option.key.text.eq_ignore_ascii_case("BASE_LOCATION")) + }); + if lifetime == Some("ICEBERG") && !has_base_location { + return Err(p.expected("BASE_LOCATION for an ICEBERG table")); + } + + let is_core = scope.is_none() + && !dynamic + && matches!(lifetime, None | Some("TEMPORARY")) + && clauses.is_empty() + && (!columns.is_empty() || query.is_some()); + if is_core { + return Ok(StatementKind::CreateTable(Box::new(CreateTable { + or_replace, + temporary: lifetime.is_some(), + name, + if_not_exists, + columns, + constraints, + query, + })) + .into()); + } + let create = SnowflakeCreateTable { + or_replace, + scope: scope.map(Cow::Borrowed), + dynamic, + lifetime: lifetime.map(Cow::Borrowed), + if_not_exists, + name, + columns, + constraints, + clauses, + query, + }; + Ok(StatementKind::Ext(BuiltinStatement::Snowflake( + SnowflakeStatement::CreateTable(Box::new(create)), + )) + .into()) +} + +fn parse_contact<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(Ident<'a>, Ident<'a>)> { + let purpose = p.parse_ident()?; + p.expect_op("=")?; + let token = p.peek(); + if token.kind == TokenKind::String { + p.advance(); + let contact = Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: None, + span: token.span, + }; + return Ok((purpose, contact)); + } + Ok((purpose, p.parse_ident()?)) +} + +fn eat_copy_grants>(p: &mut Parser<'_, D>) -> bool { + let at_copy = p.at_keyword("COPY") && p.peek_nth(1).is_word("GRANTS"); + if at_copy { + p.advance(); + p.advance(); + } + at_copy +} + +/// True at an option that a view's column can have. +fn at_view_column_option>(p: &Parser<'_, D>) -> bool { + let at_any = |n: usize| { + ["MASKING", "PROJECTION", "TAG"] + .iter() + .any(|word| p.peek_nth(n).is_word(word)) + }; + p.at_keyword("COMMENT") || at_any(0) || (p.at_keyword("WITH") && at_any(1)) +} + +fn parse_view_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let mut options = Vec::new(); + while at_view_column_option(p) { + match D::parse_column_option(p)? { + Some(option) => options.push(option), + None => break, + } + } + Ok(ViewColumn { name, options }) +} + +pub fn parse_create_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let mut secure = p.eat_keyword("SECURE"); + let temporary = p.eat_keyword("TEMP") || p.eat_keyword("TEMPORARY"); + secure |= p.eat_keyword("SECURE"); + let materialized = p.eat_keyword("MATERIALIZED"); + p.expect_keyword("VIEW")?; + let mut if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let if_not_exists_after_name = !if_not_exists && grammar::parse_if_not_exists(p)?; + if_not_exists |= if_not_exists_after_name; + let mut copy_grants = eat_copy_grants(p); + let columns = if p.eat_op("(") { + let columns = p.parse_comma_separated(parse_view_column)?; + p.expect_op(")")?; + columns + } else { + Vec::new() + }; + copy_grants |= eat_copy_grants(p); + let cluster_by = if p.at_keyword("CLUSTER") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + p.expect_op("(")?; + let exprs = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + exprs + } else { + Vec::new() + }; + let comment = if p.eat_keyword("COMMENT") { + p.expect_op("=")?; + Some(parse_comment(p)?) + } else { + None + }; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + + let is_core = !secure + && !if_not_exists_after_name + && !copy_grants + && cluster_by.is_empty() + && comment.is_none() + && columns.iter().all(|column| column.options.is_empty()); + if is_core { + return Ok(StatementKind::CreateView(Box::new(CreateView { + no_schema_binding: false, + with: Vec::new(), + or_replace, + temporary, + materialized, + if_not_exists, + name, + columns: columns.into_iter().map(|column| column.name).collect(), + query, + })) + .into()); + } + let create = SnowflakeCreateView { + or_replace, + secure, + materialized, + temporary, + if_not_exists, + if_not_exists_after_name, + name, + copy_grants, + columns, + cluster_by, + comment, + query, + }; + Ok( + StatementKind::Ext(BuiltinStatement::Snowflake(SnowflakeStatement::CreateView( + Box::new(create), + ))) + .into(), + ) +} + +pub fn at_alter_iceberg_table>(p: &Parser<'_, D>) -> bool { + p.at_keyword("ALTER") && p.peek_nth(1).is_word("ICEBERG") && p.peek_nth(2).is_word("TABLE") +} + +pub fn parse_alter_iceberg_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + p.advance(); + p.advance(); + let if_exists = p.eat_keyword("IF"); + if if_exists { + p.expect_keyword("EXISTS")?; + } + let name = grammar::parse_object_name(p)?; + let operations = p.parse_comma_separated(D::parse_alter_table_op)?; + Ok(SnowflakeStatement::AlterIcebergTable(Box::new( + AlterTable { + if_exists, + only: false, + name, + operations, + }, + ))) +} + +fn parse_structured_field<'a, D: Dialect>( + p: &mut Parser<'a, D>, + named: bool, +) -> PResult> { + let name = if named { + Some(p.parse_name_part()?) + } else { + None + }; + let data_type = p.nested(D::parse_data_type)?; + let not_null = p.eat_keyword("NOT"); + if not_null { + p.expect_keyword("NULL")?; + } + Ok(StructField { + name, + colon: false, + data_type, + not_null, + comment: None, + options: Vec::new(), + }) +} + +/// Parses a data type, which can be a structured `ARRAY(T)`, `MAP(K, V)` or +/// `OBJECT(name T, ...)`, whose elements can be `NOT NULL`. +pub fn parse_data_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let object = p.at_keyword("OBJECT"); + let count = if object { + None + } else if p.at_keyword("ARRAY") { + Some(1) + } else if p.at_keyword("MAP") { + Some(2) + } else { + return grammar::parse_data_type(p); + }; + if !p.peek_nth(1).is_op("(") { + return grammar::parse_data_type(p); + } + let name = p.parse_ident()?; + p.advance(); + let mut fields = Vec::new(); + if !p.at_op(")") || !object { + fields = p.parse_comma_separated(|p| parse_structured_field(p, object))?; + } + p.expect_op(")")?; + if count.is_some_and(|count| fields.len() != count) { + return Err(p.expected("the right number of type arguments")); + } + let mut data_type = grammar::parse_data_type_after_name(p, name)?; + data_type.angle = Some(Box::new(AngleArguments::ParenFields(fields))); + Ok(data_type) +} + +pub fn parse_create_database<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let transient = p.eat_keyword("TRANSIENT"); + p.expect_keyword("DATABASE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let mut clauses = Vec::new(); + loop { + if p.eat_keyword("CLONE") { + clauses.push(DatabaseClause::Clone(grammar::parse_object_name(p)?)); + } else if p.eat_keyword("WITH") { + if p.eat_keyword("TAG") { + clauses.push(DatabaseClause::Tags(parse_tags(p)?)); + } else { + p.expect_keyword("CONTACT")?; + p.expect_op("(")?; + let contacts = p.parse_comma_separated(parse_contact)?; + p.expect_op(")")?; + clauses.push(DatabaseClause::Contacts(contacts)); + } + } else if at_option(p, &DATABASE_OPTIONS) { + clauses.push(DatabaseClause::Option(parse_key_value(p)?)); + } else { + break; + } + } + if !or_replace && !transient && clauses.is_empty() { + return Ok(StatementKind::CreateDatabase(Box::new(CreateDatabase { + if_not_exists, + name, + })) + .into()); + } + let create = SnowflakeCreateDatabase { + or_replace, + transient, + if_not_exists, + name, + clauses, + }; + Ok(StatementKind::Ext(BuiltinStatement::Snowflake( + SnowflakeStatement::CreateDatabase(Box::new(create)), + )) + .into()) +} + +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.at_keyword("IDENTITY") || p.at_keyword("AUTOINCREMENT") { + return parse_identity(p).map(Some); + } + if p.eat_keyword("COMMENT") { + return parse_comment(p).map(|text| Some(ColumnOption::Comment(text))); + } + if p.at_keyword("COLLATE") && p.peek_nth(1).kind == TokenKind::String { + p.advance(); + let token = p.peek(); + p.advance(); + let name = ObjectName { + parts: vec![Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some('\''), + span: token.span, + }], + }; + return Ok(Some(ColumnOption::Collate(name))); + } + let next = p.peek_nth(1); + let with = p.at_keyword("WITH") + && ["MASKING", "PROJECTION", "TAG"] + .iter() + .any(|word| next.is_word(word)); + if with { + p.advance(); + } + if p.eat_keyword("TAG") { + return Ok(Some(ColumnOption::Tags { + with, + tags: parse_tags(p)?, + })); + } + let masking = p.at_keyword("MASKING"); + if masking || p.at_keyword("PROJECTION") { + p.advance(); + p.expect_keyword("POLICY")?; + let name = grammar::parse_object_name(p)?; + let using = if p.eat_keyword("USING") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + return Ok(Some(ColumnOption::Policy { + with, + masking, + name, + using, + })); + } + grammar::parse_column_option(p) +} + +fn parse_identity<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let autoincrement = p.at_keyword("AUTOINCREMENT"); + p.advance(); + let params = if p.eat_op("(") { + let seed = grammar::parse_number_text(p)?; + p.expect_op(",")?; + let increment = grammar::parse_number_text(p)?; + p.expect_op(")")?; + Some(IdentityParams { + seed: seed.into(), + increment: increment.into(), + start_form: false, + }) + } else if p.eat_keyword("START") { + let seed = grammar::parse_number_text(p)?; + p.expect_keyword("INCREMENT")?; + let increment = grammar::parse_number_text(p)?; + Some(IdentityParams { + seed: seed.into(), + increment: increment.into(), + start_form: true, + }) + } else { + None + }; + let order = if p.eat_keyword("ORDER") { + Some(true) + } else if p.eat_keyword("NOORDER") { + Some(false) + } else { + None + }; + Ok(ColumnOption::Identity { + autoincrement, + params, + order, + }) +} + +pub fn at_alter_table_kind>(p: &Parser<'_, D>) -> bool { + let kind = p.peek_nth(1); + p.at_keyword("ALTER") + && (kind.is_word("DYNAMIC") || kind.is_word("EXTERNAL")) + && p.peek_nth(2).is_word("TABLE") +} + +pub fn parse_alter_table_kind<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let dynamic = p.at_keyword("DYNAMIC"); + p.advance(); + p.advance(); + let if_exists = !dynamic && p.at_keyword("IF"); + if if_exists { + p.advance(); + p.expect_keyword("EXISTS")?; + } + let name = grammar::parse_object_name(p)?; + let action = if p.eat_keyword("REFRESH") { + "REFRESH" + } else if dynamic && p.eat_keyword("SUSPEND") { + "SUSPEND" + } else if dynamic && p.eat_keyword("RESUME") { + "RESUME" + } else { + return Err(p.expected("REFRESH, SUSPEND or RESUME")); + }; + let token = p.peek(); + let subpath = if !dynamic && token.kind == TokenKind::String { + p.advance(); + Some(D::string_literal(token)) + } else { + None + }; + Ok(SnowflakeStatement::AlterTableKind { + dynamic, + if_exists, + name, + action: action.into(), + subpath, + }) +} + +/// True at a `BEGIN` that starts a block rather than a transaction. +pub fn at_block>(p: &Parser<'_, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("BEGIN") + && !next.is_word("TRANSACTION") + && !next.is_word("WORK") + && !next.is_word("NAME") + && !next.is_op(";") + && next.kind != TokenKind::Eof +} + +fn at_block_end>(p: &Parser<'_, D>) -> bool { + p.at_keyword("END") || p.at_keyword("EXCEPTION") || p.at_keyword("WHEN") +} + +fn parse_statements<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut statements = Vec::new(); + while !at_block_end(p) { + statements.push(p.nested(Parser::parse_statement)?); + p.expect_op(";")?; + } + Ok(statements) +} + +pub fn parse_block<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("BEGIN")?; + let statements = parse_statements(p)?; + let exception = if p.eat_keyword("EXCEPTION") { + let mut arms = Vec::new(); + while !p.at_keyword("END") { + p.expect_keyword("WHEN")?; + let mut names = vec![p.parse_ident()?]; + while p.eat_keyword("OR") { + names.push(p.parse_ident()?); + } + p.expect_keyword("THEN")?; + let statements = parse_statements(p)?; + arms.push(ExceptionWhen { names, statements }); + } + Some(arms) + } else { + None + }; + p.expect_keyword("END")?; + Ok(SnowflakeStatement::Block(Box::new(Block { + statements, + exception, + }))) +} + +pub fn parse_raise<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("RAISE")?; + if p.eat_keyword("USING") { + p.expect_keyword("MESSAGE")?; + p.expect_op("=")?; + let message = p.parse_expr()?; + return Ok(SnowflakeStatement::Raise(Some(RaiseValue::Message( + message, + )))); + } + let value = if p.at_op(";") || p.peek().kind == TokenKind::Eof { + None + } else { + Some(RaiseValue::Expr(p.parse_expr()?)) + }; + Ok(SnowflakeStatement::Raise(value)) +} + +fn parse_assignment<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("DEFAULT") { + return Ok(Some(Assignment::Default(p.parse_expr()?))); + } + if p.eat_op(":=") { + return Ok(Some(Assignment::Walrus(p.parse_expr()?))); + } + Ok(None) +} + +fn parse_declaration<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let kind = if p.eat_keyword("CURSOR") { + p.expect_keyword("FOR")?; + if p.at_keyword("SELECT") || p.at_keyword("WITH") { + DeclarationKind::CursorQuery(Box::new(D::parse_query(p)?)) + } else { + DeclarationKind::CursorExpr(p.parse_expr()?) + } + } else if p.eat_keyword("RESULTSET") { + DeclarationKind::ResultSet(parse_assignment(p)?) + } else if p.eat_keyword("EXCEPTION") { + let value = if p.at_op("(") { + Some(p.parse_expr()?) + } else { + None + }; + DeclarationKind::Exception(value) + } else { + let mut value = parse_assignment(p)?; + let mut data_type = None; + if value.is_none() && p.peek().kind == TokenKind::Word { + data_type = Some(D::parse_data_type(p)?); + value = parse_assignment(p)?; + } + DeclarationKind::Variable { data_type, value } + }; + Ok(Declaration { name, kind }) +} + +/// True if the token after a `;` starts another declaration of the same +/// `DECLARE` rather than a new statement. +fn another_declaration_follows>(p: &Parser<'_, D>) -> bool { + const STATEMENTS: [&str; 36] = [ + "SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "CREATE", "DROP", "ALTER", "SET", + "USE", "BEGIN", "COPY", "DECLARE", "SHOW", "TRUNCATE", "CALL", "COMMIT", "ROLLBACK", + "LIST", "LS", "REMOVE", "RM", "PUT", "GET", "GRANT", "REVOKE", "DESCRIBE", "DESC", + "EXPLAIN", "START", "ABORT", "RAISE", "RETURN", "UNSET", "COMMENT", + ]; + let next = p.peek_nth(1); + next.kind == TokenKind::Word && !STATEMENTS.iter().any(|word| next.is_word(word)) +} + +pub fn parse_declare<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DECLARE")?; + let mut declarations = vec![parse_declaration(p)?]; + while p.at_op(";") && another_declaration_follows(p) { + p.advance(); + declarations.push(parse_declaration(p)?); + } + Ok(SnowflakeStatement::Declare(declarations)) +} + +pub fn at_set_tuple>(p: &Parser<'_, D>) -> bool { + p.at_keyword("SET") && p.peek_nth(1).is_op("(") +} + +fn parse_set_value<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("SELECT") || p.at_keyword("WITH") { + let query = p.nested(D::parse_query)?; + return Ok(ExprKind::Subquery(Box::new(query)).into()); + } + p.parse_expr() +} + +pub fn parse_set_tuple<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SET")?; + let names = grammar::parse_ident_list(p)?; + p.expect_op("=")?; + p.expect_op("(")?; + let values = p.parse_comma_separated(|p| p.spanned_expr(parse_set_value))?; + p.expect_op(")")?; + Ok(SnowflakeStatement::SetTuple { names, values }) +} + +fn write_comma(f: &mut fmt::Formatter<'_>, items: &[T]) -> fmt::Result { + for (i, item) in items.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{item}")?; + } + Ok(()) +} + +impl Display for ViewColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name)?; + for option in &self.options { + write!(f, " {option}")?; + } + Ok(()) + } +} + +impl Display for SnowflakeCreateView<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + for (written, word) in [ + (self.or_replace, "OR REPLACE "), + (self.secure, "SECURE "), + (self.materialized, "MATERIALIZED "), + (self.temporary, "TEMPORARY "), + ] { + if written { + f.write_str(word)?; + } + } + f.write_str("VIEW ")?; + if self.if_not_exists && !self.if_not_exists_after_name { + f.write_str("IF NOT EXISTS ")?; + } + write!(f, "{}", self.name)?; + if self.if_not_exists_after_name { + f.write_str(" IF NOT EXISTS")?; + } + if self.copy_grants { + f.write_str(" COPY GRANTS")?; + } + if !self.columns.is_empty() { + f.write_str(" (")?; + write_comma(f, &self.columns)?; + f.write_str(")")?; + } + if !self.cluster_by.is_empty() { + f.write_str(" CLUSTER BY (")?; + write_comma(f, &self.cluster_by)?; + f.write_str(")")?; + } + if let Some(comment) = &self.comment { + write!(f, " COMMENT = {}", comment)?; + } + crate::display::write_view_query(f, &self.query) + } +} + +pub fn write_alter_iceberg_table( + f: &mut fmt::Formatter<'_>, + alter: &AlterTable<'_, Builtin>, +) -> fmt::Result { + f.write_str("ALTER ICEBERG TABLE ")?; + if alter.if_exists { + f.write_str("IF EXISTS ")?; + } + write!(f, "{} ", alter.name)?; + write_comma(f, &alter.operations) +} + +impl Display for SemanticView<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name)?; + for (keyword, list) in [ + ("DIMENSIONS", &self.dimensions), + ("METRICS", &self.metrics), + ("FACTS", &self.facts), + ] { + if !list.is_empty() { + write!(f, " {keyword} ")?; + write_comma(f, list)?; + } + } + if let Some(selection) = &self.selection { + write!(f, " WHERE {selection}")?; + } + Ok(()) + } +} + +impl Display for TableClause<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TableClause::CopyGrants => f.write_str("COPY GRANTS"), + TableClause::Comment { equals, text } => { + let equals = if *equals { "= " } else { "" }; + write!(f, "COMMENT {equals}{}", text) + } + TableClause::Clone(name) => write!(f, "CLONE {name}"), + TableClause::Like(name) => write!(f, "LIKE {name}"), + TableClause::Version(call) => write!(f, "{call}"), + TableClause::ClusterBy(exprs) => { + f.write_str("CLUSTER BY (")?; + write_comma(f, exprs)?; + f.write_str(")") + } + TableClause::Option(option) => write!(f, "{option}"), + TableClause::Policy { kind, name, on } => { + write!(f, "WITH {kind} {name}")?; + if !on.is_empty() { + f.write_str(" ON (")?; + write_comma(f, on)?; + f.write_str(")")?; + } + Ok(()) + } + TableClause::Tags(tags) => { + f.write_str("WITH TAG (")?; + write_comma(f, tags)?; + f.write_str(")") + } + TableClause::OnCommit(action) => write!(f, "ON COMMIT {action}"), + TableClause::RequireUser => f.write_str("REQUIRE USER"), + } + } +} + +impl Display for SnowflakeCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + if let Some(ref scope) = self.scope { + write!(f, "{scope} ")?; + } + if self.dynamic { + f.write_str("DYNAMIC ")?; + } + if let Some(ref lifetime) = self.lifetime { + write!(f, "{lifetime} ")?; + } + f.write_str("TABLE ")?; + if self.if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + write!(f, "{}", self.name)?; + if !self.columns.is_empty() || !self.constraints.is_empty() { + write_columns(f, &self.columns, &self.constraints)?; + } else if self.query.is_none() && !self.clauses.iter().any(TableClause::names_a_source) { + f.write_str(" ()")?; + } + for clause in self.clauses.iter().filter(|c| c.renders_first()) { + write!(f, " {clause}")?; + } + for clause in self.clauses.iter().filter(|c| !c.renders_first()) { + write!(f, " {clause}")?; + } + if let Some(query) = &self.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} + +impl Display for SnowflakeCreateDatabase<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE ")?; + if self.or_replace { + f.write_str("OR REPLACE ")?; + } + if self.transient { + f.write_str("TRANSIENT ")?; + } + f.write_str("DATABASE ")?; + if self.if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + write!(f, "{}", self.name)?; + for clause in &self.clauses { + match clause { + DatabaseClause::Clone(name) => write!(f, " CLONE {name}")?, + DatabaseClause::Option(option) => { + write!(f, " {} = ", option.key)?; + write_value(f, &option.value)?; + } + DatabaseClause::Tags(tags) => { + f.write_str(" WITH TAG (")?; + write_comma(f, tags)?; + f.write_str(")")?; + } + DatabaseClause::Contacts(contacts) => { + f.write_str(" WITH CONTACT (")?; + for (i, (purpose, contact)) in contacts.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{purpose} = {contact}")?; + } + f.write_str(")")?; + } + } + } + Ok(()) + } +} + +fn write_statements( + f: &mut fmt::Formatter<'_>, + statements: &[Statement<'_, Builtin>], +) -> fmt::Result { + for statement in statements { + write!(f, " {statement};")?; + } + Ok(()) +} + +impl Display for Block<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BEGIN")?; + write_statements(f, &self.statements)?; + if let Some(arms) = &self.exception { + f.write_str(" EXCEPTION")?; + for arm in arms { + f.write_str(" WHEN ")?; + for (i, name) in arm.names.iter().enumerate() { + if i > 0 { + f.write_str(" OR ")?; + } + write!(f, "{name}")?; + } + f.write_str(" THEN")?; + write_statements(f, &arm.statements)?; + } + } + f.write_str(" END") + } +} + +impl Display for Assignment<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Assignment::Default(expr) => write!(f, "DEFAULT {expr}"), + Assignment::Walrus(expr) => write!(f, ":= {expr}"), + } + } +} + +impl Display for Declaration<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name)?; + match &self.kind { + DeclarationKind::Variable { data_type, value } => { + if let Some(data_type) = data_type { + write!(f, " {data_type}")?; + } + if let Some(value) = value { + write!(f, " {value}")?; + } + Ok(()) + } + DeclarationKind::ResultSet(value) => { + f.write_str(" RESULTSET")?; + match value { + Some(value) => write!(f, " {value}"), + None => Ok(()), + } + } + DeclarationKind::CursorQuery(query) => write!(f, " CURSOR FOR {query}"), + DeclarationKind::CursorExpr(expr) => write!(f, " CURSOR FOR {expr}"), + DeclarationKind::Exception(value) => { + f.write_str(" EXCEPTION")?; + match value { + Some(value) => write!(f, " {value}"), + None => Ok(()), + } + } + } + } +} + +impl Display for RaiseValue<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RaiseValue::Expr(expr) => write!(f, "{expr}"), + RaiseValue::Message(expr) => write!(f, "USING MESSAGE = {expr}"), + } + } +} + +pub fn write_set_tuple( + f: &mut fmt::Formatter<'_>, + names: &[Ident<'_>], + values: &[Expr<'_, Builtin>], +) -> fmt::Result { + f.write_str("SET (")?; + write_comma(f, names)?; + f.write_str(") = (")?; + write_comma(f, values)?; + f.write_str(")") +} + +pub fn write_declare(f: &mut fmt::Formatter<'_>, declarations: &[Declaration<'_>]) -> fmt::Result { + f.write_str("DECLARE ")?; + for (i, declaration) in declarations.iter().enumerate() { + if i > 0 { + f.write_str("; ")?; + } + write!(f, "{declaration}")?; + } + Ok(()) +} diff --git a/sqlparser_v2/src/dialect/spark.rs b/sqlparser_v2/src/dialect/spark.rs new file mode 100644 index 0000000000..81dce2a4e8 --- /dev/null +++ b/sqlparser_v2/src/dialect/spark.rs @@ -0,0 +1,1378 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Apache Spark SQL. + +use std::borrow::Cow; +use std::fmt; +use std::mem::discriminant; + +use crate::PResult; +use crate::ast::{ + AlterTableOp, AngleArguments, BinaryOp, ColumnOption, CreateTable, Cte, DataType, Expr, + ExprKind, GroupByModifier, Ident, Insert, InsertSource, Join, JoinKind, LateralView, + ObjectName, OrderByItem, PipeOperator, Pivot, Quantifier, Query, QueryDistribution, + SampleAmount, SampleClause, SelectItem, SelectItemKind, Span, SpecialExpr, Statement, + StatementKind, StringLiteral, StructField, TableFactor, TableRef, TableSample, UnaryOp, + Unpivot, WildcardOptions, +}; +use crate::dialect::builtin::BuiltinStatement; +use crate::dialect::mysql::{self, MySqlExpr}; +use crate::dialect::{Builtin, Dialect, ExprExtOf}; +use crate::dialect::{bigquery, oracle, postgres}; +use crate::display::{ + SpaceOrNewline, comma, write_columns, write_create_flags, write_if_not_exists, +}; +use crate::grammar::{self, prec}; +use crate::lexer::{LexResult, Lexeme, Token, TokenKind, quoted, quoted_with_backslash}; +use crate::parser::{InfixAction, InfixRule, Parser, SetOperatorRule}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Spark; + +#[derive(Debug, Clone, PartialEq)] +pub enum SparkStatement<'a> { + CreateTable(Box>), + Insert(Box>), + InsertDirectory(Box>), + Cache(Box>), + Uncache { + table: ObjectName<'a>, + if_exists: bool, + }, +} + +/// `CACHE [flag] TABLE name [OPTIONS(...)] [[AS] query]` +#[derive(Debug, Clone, PartialEq)] +pub struct SparkCache<'a> { + /// The word before `TABLE`, such as `LAZY`. + pub flag: Option>, + pub table: ObjectName<'a>, + pub options: Vec>, + /// True if `AS` was written before the query. + pub has_as: bool, + pub query: Option>, +} + +/// `INSERT` with syntax only Spark has. Without it, the statement is the core +/// [`Insert`]. +#[derive(Debug, Clone, PartialEq)] +pub struct SparkInsert<'a> { + pub overwrite: bool, + pub into: bool, + /// True if the optional `TABLE` keyword was written. + pub table_keyword: bool, + pub table: ObjectName<'a>, + pub columns: Vec>, + pub partition: Vec>, + /// True if the column list was written after `PARTITION (...)`. + pub columns_after_partition: bool, + pub source: InsertSource<'a, Builtin>, +} + +/// `INSERT OVERWRITE [LOCAL] DIRECTORY 'path' [STORED AS format] query` +#[derive(Debug, Clone, PartialEq)] +pub struct SparkInsertDirectory<'a> { + pub local: bool, + pub path: StringLiteral<'a>, + pub stored_as: Option>, + pub source: Query<'a, Builtin>, +} + +/// `CREATE TABLE` with clauses only Spark has. Without them, the statement is +/// the core [`CreateTable`]. +#[derive(Debug, Clone, PartialEq)] +pub struct SparkCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + pub external: bool, + /// In the order written. + pub clauses: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SparkTableClause<'a> { + Using(Ident<'a>), + Options(Vec>), + PartitionedBy(Vec>), + Location(StringLiteral<'a>), + Comment(StringLiteral<'a>), + TblProperties(Vec>), + /// `LIKE source` + Like(ObjectName<'a>), +} + +/// `key = value` or `key value` in `OPTIONS` and `TBLPROPERTIES`. +#[derive(Debug, Clone, PartialEq)] +pub struct SparkOption<'a> { + pub key: Expr<'a, Builtin>, + pub equals: bool, + pub value: Option>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct PartitionColumn<'a> { + pub name: Ident<'a>, + pub data_type: Option>, +} + +/// Reads backtick-quoted names, strings in either quote with backslash +/// escapes, and the operators the core does not have. +#[inline] +/// Lexes Spark's tokens: those of [`lex_token`], plus raw strings, `r'...'`, +/// in which a backslash is an ordinary character. +pub fn lex_spark_token(rest: &str) -> Option { + if let [b'r' | b'R', b'"' | b'\'', ..] = rest.as_bytes() { + return Some(quoted(&rest[1..], TokenKind::String).map(|l| Lexeme { + kind: TokenKind::String, + len: l.len + 1, + })); + } + lex_token(rest) +} + +/// Lexes the tokens Spark shares with Hive. +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) + }; + match rest.as_bytes() { + [b'`', ..] => Some(quoted(rest, TokenKind::QuotedIdent)), + [b'"' | b'\'', ..] => Some(quoted_with_backslash(rest, TokenKind::String)), + [b'-', b'>', ..] | [b'|', b'>', ..] => op(2), + [b'!', b'=', ..] => None, + [b'!', ..] => op(1), + // Type arguments close one at a time, as in `ARRAY>`. + [b'>', b'>', ..] => op(1), + // `:` before a name is a parameter, which the core reads. + [b':', b':', ..] => op(2), + [b':', next, ..] if !next.is_ascii_alphanumeric() && *next != b'_' => op(1), + _ => None, + } +} + +/// Builds a string literal, in which a backslash starts an escape unless the +/// string is raw: `r'...'`. +pub fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + if matches!(token.text.as_bytes()[0], b'r' | b'R') { + let text = &token.text[1..]; + return StringLiteral { + text: Cow::Borrowed(&text[1..text.len() - 1]), + quote: char::from(text.as_bytes()[0]), + backslash_escapes: false, + national: false, + prefix: crate::ast::StringPrefix::Raw, + triple: false, + }; + } + StringLiteral { + backslash_escapes: true, + ..grammar::string_literal(token) + } +} + +/// Parses `!`, lambdas, and otherwise the core's prefix expressions. +pub fn parse_prefix<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_op("!") { + let expr = p.parse_expr_bp(prec::NOT)?; + return Ok(ExprKind::Unary { + op: UnaryOp::BangNot, + expr: Box::new(expr), + } + .into()); + } + if at_lambda(p) { + return parse_lambda(p); + } + grammar::parse_prefix(p) +} + +fn is_name(token: Token<'_>) -> bool { + matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +/// True at `x ->` or `(x, y) ->`. +pub fn at_lambda<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if is_name(p.peek()) { + return p.peek_nth(1).is_op("->"); + } + if !p.at_op("(") { + return false; + } + let mut n = 1; + loop { + if !is_name(p.peek_nth(n)) { + return false; + } + let separator = p.peek_nth(n + 1); + if separator.is_op(")") { + return p.peek_nth(n + 2).is_op("->"); + } + if !separator.is_op(",") { + return false; + } + n += 2; + } +} + +pub fn parse_lambda<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let parenthesized = p.eat_op("("); + let params = if parenthesized { + let params = p.parse_comma_separated(Parser::parse_ident)?; + p.expect_op(")")?; + params + } else { + vec![p.parse_ident()?] + }; + p.expect_op("->")?; + let body = p.parse_expr()?; + Ok(ExprKind::Special(Box::new(SpecialExpr::Lambda { + params, + parenthesized, + body, + })) + .into()) +} + +pub fn infix_rule<'a, D>(p: &Parser<'a, D>) -> Option> +where + D: Dialect, + ExprExtOf<'a, D>: From>, +{ + if p.at_keyword("DIV") { + return Some(InfixRule::custom(prec::MUL, mysql::parse_int_div)); + } + if p.at_op("||") { + return Some(InfixRule::binary(prec::ADD, BinaryOp::StringConcat)); + } + if p.at_op("::") { + return Some(InfixRule::custom( + prec::POSTFIX, + postgres::parse_double_colon, + )); + } + if p.at_keyword("ILIKE") { + return Some(InfixRule::custom(prec::COMPARE, postgres::parse_ilike)); + } + if p.at_keyword("NOT") && postgres::next_is_ilike(p) { + return Some(InfixRule::custom(prec::COMPARE, postgres::parse_not_ilike)); + } + grammar::infix_rule(p) +} + +/// Parses an `ALTER TABLE` operation, adding `SET TBLPROPERTIES`. +pub fn parse_alter_table_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("SET") && p.peek_nth(1).is_word("TBLPROPERTIES") { + p.advance(); + p.advance(); + p.expect_op("(")?; + let properties = p.parse_comma_separated(|p| { + let key = p.parse_expr_bp(grammar::prec::COMPARE)?; + p.expect_op("=")?; + Ok((key, p.parse_expr()?)) + })?; + p.expect_op(")")?; + return Ok(AlterTableOp::SetTblProperties(properties)); + } + grammar::parse_alter_table_op(p) +} + +/// Parses a select item, which can be `* EXCEPT (a, b)`. +pub fn parse_select_item<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + // `(*)` is `*`. + if p.at_op("(") && p.peek_nth(1).is_op("*") && p.peek_nth(2).is_op(")") { + p.advance(); + p.advance(); + p.advance(); + return Ok(SelectItemKind::Wildcard.into()); + } + let item = grammar::parse_select_item(p)?; + let qualifier = match &item.kind { + SelectItemKind::Wildcard => None, + SelectItemKind::QualifiedWildcard(name) => Some(name.clone()), + _ => return Ok(item), + }; + let query_follows = ["SELECT", "WITH", "VALUES"] + .iter() + .any(|word| p.peek_nth(2).is_word(word)); + if !p.at_keyword("EXCEPT") || !p.peek_nth(1).is_op("(") || query_follows { + return Ok(item); + } + p.advance(); + let exclude = grammar::parse_ident_list(p)?; + Ok(SelectItemKind::WildcardWithOptions { + qualifier, + options: Box::new(WildcardOptions { + ilike: None, + exclude, + exclude_parens: true, + except_keyword: true, + replace: Vec::new(), + rename: Vec::new(), + rename_parens: false, + }), + } + .into()) +} + +/// Parses a table, which can be `VALUES (...)` with no parentheses around it. +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !(p.at_keyword("VALUES") && p.peek_nth(1).is_op("(")) { + return grammar::parse_table_factor(p); + } + p.advance(); + let mut rows = vec![grammar::parse_values_row(p)?]; + // A comma before anything else starts the next table. + while p.at_op(",") && p.peek_nth(1).is_op("(") { + p.advance(); + rows.push(grammar::parse_values_row(p)?); + } + Ok(TableFactor::Values(rows)) +} + +/// Parses a common table expression, in which `AS` is optional. +pub fn parse_cte<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + let columns = D::parse_cte_columns(p)?; + p.eat_keyword("AS"); + p.expect_op("(")?; + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + Ok(Cte { + name, + columns, + materialized: None, + query, + }) +} + +/// Parses a type, which can be `ARRAY`, `MAP` or `STRUCT`. +pub fn at_interval_with_fields<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("INTERVAL") + && ["YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND"] + .into_iter() + .any(|field| next.is_word(field)) +} + +pub fn parse_data_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + // Interval fields are rejected rather than leaving `DAY` in + // `x::INTERVAL DAY` to be read as an alias. + if at_interval_with_fields(p) { + return Err(p.expected("an INTERVAL type without fields")); + } + let name = p.parse_ident()?; + parse_type_after_name(p, name) +} + +fn parse_type_after_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Ident<'a>, +) -> PResult> { + let mut data_type = grammar::parse_data_type_after_name(p, name.clone())?; + let complex = name.quote.is_none() + && ["ARRAY", "MAP", "STRUCT"] + .iter() + .any(|word| name.text.eq_ignore_ascii_case(word)); + if !complex || !p.at_op("<") { + return Ok(data_type); + } + p.advance(); + let arguments = if name.text.eq_ignore_ascii_case("STRUCT") { + AngleArguments::Fields(p.parse_comma_separated(parse_struct_field)?) + } else { + let types = p.parse_comma_separated(|p| p.nested(D::parse_data_type))?; + let expected = if name.text.eq_ignore_ascii_case("MAP") { + 2 + } else { + 1 + }; + if types.len() != expected { + return Err(p.expected("the right number of type arguments")); + } + AngleArguments::Types(types) + }; + p.expect_angle_close()?; + data_type.angle = Some(Box::new(arguments)); + Ok(data_type) +} + +fn parse_struct_field<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_name_part()?; + let token = p.peek(); + // With no space, the lexer reads `:INT` as a parameter. + let (colon, data_type) = if token.kind == TokenKind::Placeholder && token.text.starts_with(':') + { + p.advance(); + let type_name = Ident { + text: Cow::Borrowed(&token.text[1..]), + quote: None, + span: Span { + start: token.span.start + 1, + end: token.span.end, + }, + }; + (true, p.nested(|p| parse_type_after_name(p, type_name))?) + } else { + let colon = p.eat_op(":"); + (colon, p.nested(D::parse_data_type)?) + }; + let comment = parse_optional_comment(p)?; + Ok(StructField { + name: Some(name), + colon, + data_type, + not_null: false, + comment, + options: Vec::new(), + }) +} + +pub use grammar::parse_string; + +pub fn parse_optional_comment<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("COMMENT") { + parse_string(p).map(Some) + } else { + Ok(None) + } +} + +/// Parses a column option, adding `COMMENT 'text'` to the core's. +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if let Some(comment) = parse_optional_comment(p)? { + return Ok(Some(ColumnOption::Comment(comment))); + } + grammar::parse_column_option(p) +} + +fn parse_option<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let key = p.nested(Parser::parse_prefix)?; + let equals = p.eat_op("="); + if !equals && p.peek().kind == TokenKind::Op && !p.at_op(",") && !p.at_op(")") { + return Err(p.expected("an option value")); + } + let value = if equals || !(p.at_op(",") || p.at_op(")")) { + Some(p.parse_expr_bp(prec::COMPARE)?) + } else { + None + }; + Ok(SparkOption { key, equals, value }) +} + +pub fn parse_option_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + p.expect_op("(")?; + let options = p.parse_comma_separated(parse_option)?; + p.expect_op(")")?; + Ok(options) +} + +pub fn parse_partition_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + let data_type = if p.at_op(",") || p.at_op(")") { + None + } else { + Some(D::parse_data_type(p)?) + }; + Ok(PartitionColumn { name, data_type }) +} + +fn parse_table_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("USING") { + return p.parse_ident().map(SparkTableClause::Using).map(Some); + } + if p.eat_keyword("LIKE") { + return grammar::parse_object_name(p) + .map(SparkTableClause::Like) + .map(Some); + } + if p.eat_keyword("OPTIONS") { + return parse_option_list(p) + .map(SparkTableClause::Options) + .map(Some); + } + if p.at_keyword("PARTITIONED") { + p.advance(); + p.expect_keyword("BY")?; + p.expect_op("(")?; + let columns = p.parse_comma_separated(parse_partition_column)?; + p.expect_op(")")?; + return Ok(Some(SparkTableClause::PartitionedBy(columns))); + } + if p.eat_keyword("LOCATION") { + return parse_string(p).map(SparkTableClause::Location).map(Some); + } + if let Some(comment) = parse_optional_comment(p)? { + return Ok(Some(SparkTableClause::Comment(comment))); + } + if p.eat_keyword("TBLPROPERTIES") { + return parse_option_list(p) + .map(SparkTableClause::TblProperties) + .map(Some); + } + Ok(None) +} + +/// True at `CREATE [OR REPLACE] [TEMPORARY] [EXTERNAL] TABLE`. +pub fn at_create_table<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if !p.at_keyword("CREATE") { + return false; + } + let mut n = 1; + if p.peek_nth(n).is_word("OR") { + n += 2; + } + if p.peek_nth(n).is_word("TEMPORARY") || p.peek_nth(n).is_word("TEMP") { + n += 1; + } + if p.peek_nth(n).is_word("EXTERNAL") { + n += 1; + } + p.peek_nth(n).is_word("TABLE") +} + +/// Parses `CREATE`, handling Spark's table clauses. +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !at_create_table(p) { + return grammar::parse_create(p); + } + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + let external = p.eat_keyword("EXTERNAL"); + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let mut clauses: Vec> = Vec::new(); + while let Some(clause) = parse_table_clause(p)? { + if clauses + .iter() + .any(|seen| discriminant(seen) == discriminant(&clause)) + { + return Err(p.expected("each table clause only once")); + } + clauses.push(clause); + } + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() && clauses.is_empty() { + return Err(p.expected("column definitions, table clauses or AS")); + } + let table = CreateTable { + or_replace, + temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + if !external && clauses.is_empty() { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + let create = SparkCreateTable { + table, + external, + clauses, + }; + Ok( + StatementKind::Ext(BuiltinStatement::Spark(SparkStatement::CreateTable( + Box::new(create), + ))) + .into(), + ) +} + +/// True where a word that could be a table alias starts a clause instead. +fn at_clause_after_table<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + if next.is_word("BY") { + return p.at_keyword("SORT") || p.at_keyword("CLUSTER") || p.at_keyword("DISTRIBUTE"); + } + (p.at_keyword("LATERAL") && next.is_word("VIEW")) + || ((p.at_keyword("SEMI") || p.at_keyword("ANTI")) && next.is_word("JOIN")) + || at_sample(p) + || at_pivot(p) + || at_unpivot(p) +} + +fn at_sample<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("TABLESAMPLE") + && (next.is_op("(") + || ["BERNOULLI", "ROW", "SYSTEM", "BLOCK"] + .into_iter() + .any(|method| next.is_word(method))) +} + +fn at_pivot<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("PIVOT") && p.peek_nth(1).is_op("(") +} + +fn at_unpivot<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("UNPIVOT") + && (next.is_op("(") || next.is_word("INCLUDE") || next.is_word("EXCLUDE")) +} + +fn parse_table_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if at_clause_after_table(p) { + return Ok(None); + } + grammar::parse_optional_table_alias(p) +} + +/// Levels of tree height added for a clause that wraps the table before it, +/// whose nodes take twice the stack of an ordinary level to clone or render. +const TABLE_CLAUSE_LEVELS: usize = 2; + +fn parse_sample<'a, D: Dialect>( + p: &mut Parser<'a, D>, + table: TableRef<'a, D::Ext>, +) -> PResult> { + p.deepen_by(TABLE_CLAUSE_LEVELS)?; + p.advance(); + let sample = D::parse_sample_clause(p, true)?; + Ok(TableRef { + factor: TableFactor::Sampled(Box::new(TableSample { table, sample })), + alias: None, + span: Span::default(), + }) +} + +/// Parses what follows `TABLESAMPLE`: an amount, or a `BUCKET` in parentheses. +pub fn parse_sample_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, + long_form: bool, +) -> PResult> { + if !p.at_op("(") { + return Err(p.expected("( after TABLESAMPLE")); + } + if !p.peek_nth(1).is_word("BUCKET") { + return grammar::parse_sample_clause(p, long_form); + } + p.advance(); + p.advance(); + let bucket = grammar::parse_number(p)?; + p.expect_keyword("OUT")?; + p.expect_keyword("OF")?; + let total = grammar::parse_number(p)?; + let on = if p.eat_keyword("ON") { + Some(Box::new(p.parse_expr()?)) + } else { + None + }; + p.expect_op(")")?; + Ok(SampleClause { + long_form, + method: None, + amount: SampleAmount::Bucket { + bucket: bucket.into(), + total: total.into(), + on, + }, + parenthesized: true, + seed: None, + offset: None, + }) +} + +/// Parses a table with any sample, alias, `PIVOT` and `UNPIVOT`. A sample can +/// be written before or after the alias. +pub fn parse_table_ref<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut table = TableRef { + factor: D::parse_table_factor(p)?, + alias: None, + span: Span::default(), + }; + if at_sample(p) { + table = parse_sample(p, table)?; + } + table.alias = parse_table_alias(p)?; + loop { + let factor = if at_sample(p) { + table = parse_sample(p, table)?; + continue; + } else if at_pivot(p) { + p.deepen_by(TABLE_CLAUSE_LEVELS)?; + p.advance(); + let clause = grammar::parse_pivot_head(p)?; + p.expect_op(")")?; + TableFactor::Pivot(Box::new(Pivot { table, clause })) + } else if at_unpivot(p) { + p.deepen_by(TABLE_CLAUSE_LEVELS)?; + p.advance(); + let clause = grammar::parse_unpivot_clause(p)?; + TableFactor::Unpivot(Box::new(Unpivot { table, clause })) + } else { + return Ok(table); + }; + let alias = parse_table_alias(p)?; + table = TableRef { + factor, + alias, + span: Span::default(), + }; + } +} + +/// Consumes the words of a semi or anti join, if one starts here. +fn eat_semi_or_anti<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let next = p.peek_nth(1); + let (kind, words) = if p.at_keyword("LEFT") && next.is_word("SEMI") { + (JoinKind::LeftSemi, 2) + } else if p.at_keyword("LEFT") && next.is_word("ANTI") { + (JoinKind::LeftAnti, 2) + } else if p.at_keyword("SEMI") && next.is_word("JOIN") { + (JoinKind::Semi, 1) + } else if p.at_keyword("ANTI") && next.is_word("JOIN") { + (JoinKind::Anti, 1) + } else { + return Ok(None); + }; + for _ in 0..words { + p.advance(); + } + p.expect_keyword("JOIN")?; + Ok(Some(kind)) +} + +/// Parses a join, which can be a semi or anti join. +pub fn parse_join<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let Some(kind) = eat_semi_or_anti(p)? else { + return grammar::parse_join(p); + }; + let table = p.parse_table_ref()?; + let constraint = grammar::parse_join_constraint(p)?; + Ok(Some(Join { + kind, + spelled_out: false, + table, + constraint, + })) +} + +/// Finishes a select item, which can name several columns: `f(a) AS (b, c)`. +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, D::Ext>, +) -> PResult> { + if p.at_keyword("AS") && p.peek_nth(1).is_op("(") { + p.advance(); + let aliases = grammar::parse_ident_list(p)?; + return Ok(SelectItemKind::ExprWithAliases { expr, aliases }.into()); + } + grammar::parse_select_item_alias(p, expr) +} + +/// Parses `LATERAL VIEW` clauses. +pub fn parse_lateral_views<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut views = Vec::new(); + while p.at_keyword("LATERAL") && p.peek_nth(1).is_word("VIEW") { + p.advance(); + p.advance(); + let outer = p.eat_keyword("OUTER"); + let function = p.parse_expr()?; + let name = grammar::parse_object_name(p)?; + let mut columns = Vec::new(); + if let Some(column) = grammar::parse_optional_alias(p)? { + columns.push(column); + while p.eat_op(",") { + columns.push(p.parse_ident()?); + } + } + views.push(LateralView { + outer, + function, + name, + columns, + }); + } + Ok(views) +} + +/// Parses `[CLUSTER BY ...] [DISTRIBUTE BY ...] [SORT BY ...]`. +pub fn parse_query_distribution<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + let cluster_by = parse_by_list(p, "CLUSTER", Parser::parse_expr)?; + let distribute_by = parse_by_list(p, "DISTRIBUTE", Parser::parse_expr)?; + let sort_by: Vec> = parse_by_list(p, "SORT", D::parse_order_by_item)?; + if cluster_by.is_empty() && distribute_by.is_empty() && sort_by.is_empty() { + return Ok(None); + } + Ok(Some(Box::new(QueryDistribution { + cluster_by, + distribute_by, + sort_by, + }))) +} + +fn parse_by_list<'a, D: Dialect, T>( + p: &mut Parser<'a, D>, + keyword: &str, + item: impl FnMut(&mut Parser<'a, D>) -> PResult, +) -> PResult> { + if !p.eat_keyword(keyword) { + return Ok(Vec::new()); + } + p.expect_keyword("BY")?; + p.parse_comma_separated(item) +} + +/// Parses a bound of `BETWEEN`, which can be one comparison. +pub fn parse_between_bound<'a, D: Dialect>( + p: &mut Parser<'a, D>, + bound: Expr<'a, D::Ext>, +) -> PResult> { + if !["=", "<>", "!=", "<", "<=", ">", ">="] + .into_iter() + .any(|op| p.at_op(op)) + { + return Ok(bound); + } + let Some(rule) = D::infix_rule(p) else { + return Ok(bound); + }; + match rule.action { + InfixAction::Binary(op) => { + p.advance(); + grammar::parse_binary_right(p, bound, op, rule.bp) + } + InfixAction::Custom(parse) => parse(p, bound, rule.bp), + } +} + +/// True at `[LOCAL] DIRECTORY 'path'`. +fn at_directory<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let (word, path) = if p.at_keyword("LOCAL") { + (p.peek_nth(1), p.peek_nth(2)) + } else { + (p.peek(), p.peek_nth(1)) + }; + word.is_word("DIRECTORY") && path.kind == TokenKind::String +} + +fn parse_insert_directory<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let local = p.eat_keyword("LOCAL"); + p.expect_keyword("DIRECTORY")?; + let path = D::string_literal(p.peek()); + p.advance(); + let stored_as = if p.eat_keyword("STORED") { + p.expect_keyword("AS")?; + Some(p.parse_ident()?) + } else { + None + }; + let source = D::parse_query(p)?; + Ok( + StatementKind::Ext(BuiltinStatement::Spark(SparkStatement::InsertDirectory( + Box::new(SparkInsertDirectory { + local, + path, + stored_as, + source, + }), + ))) + .into(), + ) +} + +/// Parses `INSERT`, producing the core statement unless Spark's syntax is used. +pub fn parse_insert<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("INSERT")?; + let modifiers = D::parse_insert_modifiers(p)?; + let overwrite = p.eat_keyword("OVERWRITE"); + if overwrite && at_directory(p) { + return parse_insert_directory(p); + } + let into = p.eat_keyword("INTO"); + if !overwrite && !into { + return Err(p.expected("INTO or OVERWRITE")); + } + let table_keyword = p.eat_keyword("TABLE"); + let table = grammar::parse_object_name(p)?; + let mut columns = if grammar::at_column_list(p) { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let partition = if p.eat_keyword("PARTITION") { + p.expect_op("(")?; + let partition = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + partition + } else { + Vec::new() + }; + let columns_after_partition = columns.is_empty() && grammar::at_column_list(p); + if columns_after_partition { + columns = grammar::parse_ident_list(p)?; + } + let source = grammar::parse_insert_source(p)?; + if !overwrite && !table_keyword && partition.is_empty() { + let returning = D::parse_returning(p)?; + return Ok(StatementKind::Insert(Box::new(Insert { + modifiers, + into: true, + table, + columns, + output: None, + source, + returning, + })) + .into()); + } + Ok( + StatementKind::Ext(BuiltinStatement::Spark(SparkStatement::Insert(Box::new( + SparkInsert { + overwrite, + into, + table_keyword, + table, + columns, + partition, + columns_after_partition, + source, + }, + )))) + .into(), + ) +} + +/// Parses a table name, which here can also be written as a string. +fn parse_cache_table_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind != TokenKind::String { + return grammar::parse_object_name(p); + } + p.advance(); + Ok(ObjectName { + parts: vec![Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: token.text.chars().next(), + span: token.span, + }], + }) +} + +fn at_query<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_op("(") || p.at_keyword("SELECT") || p.at_keyword("WITH") || p.at_keyword("VALUES") +} + +fn parse_cache<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CACHE")?; + let flag = if p.at_keyword("TABLE") { + None + } else { + Some(p.parse_ident()?) + }; + p.expect_keyword("TABLE")?; + let table = parse_cache_table_name(p)?; + let options = if p.eat_keyword("OPTIONS") { + parse_option_list(p)? + } else { + Vec::new() + }; + let has_as = p.eat_keyword("AS"); + let query = if has_as || at_query(p) { + Some(D::parse_query(p)?) + } else { + None + }; + Ok( + StatementKind::Ext(BuiltinStatement::Spark(SparkStatement::Cache(Box::new( + SparkCache { + flag, + table, + options, + has_as, + query, + }, + )))) + .into(), + ) +} + +fn parse_uncache<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("UNCACHE")?; + p.expect_keyword("TABLE")?; + let if_exists = p.eat_keyword("IF"); + if if_exists { + p.expect_keyword("EXISTS")?; + } + let table = parse_cache_table_name(p)?; + Ok( + StatementKind::Ext(BuiltinStatement::Spark(SparkStatement::Uncache { + table, + if_exists, + })) + .into(), + ) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if grammar::at_alter_view(p) { + return grammar::parse_alter_view(p, false) + .map(|a| StatementKind::AlterView(Box::new(a)).into()); + } + if p.at_keyword("CACHE") { + return parse_cache(p); + } + if p.at_keyword("UNCACHE") { + return parse_uncache(p); + } + grammar::parse_statement(p) +} + +impl fmt::Display for SparkInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("INSERT")?; + if self.overwrite { + f.write_str(" OVERWRITE")?; + } + if self.into { + f.write_str(" INTO")?; + } + if self.table_keyword { + f.write_str(" TABLE")?; + } + write!(f, " {}", self.table)?; + if !self.columns_after_partition && !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + if !self.partition.is_empty() { + write!(f, " PARTITION ({})", comma(&self.partition))?; + } + if self.columns_after_partition && !self.columns.is_empty() { + SpaceOrNewline.fmt(f)?; + write!(f, "({})", comma(&self.columns))?; + } + let on_new_line = !self.columns.is_empty() || !self.partition.is_empty(); + crate::display::write_insert_source(f, &self.source, on_new_line) + } +} + +impl fmt::Display for SparkCache<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CACHE ")?; + if let Some(flag) = &self.flag { + write!(f, "{flag} ")?; + } + write!(f, "TABLE {}", self.table)?; + if !self.options.is_empty() { + write!(f, " OPTIONS({})", comma(&self.options))?; + } + if self.has_as { + f.write_str(" AS")?; + } + match &self.query { + Some(query) => write!(f, " {query}"), + None => Ok(()), + } + } +} + +impl fmt::Display for SparkInsertDirectory<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("INSERT OVERWRITE")?; + if self.local { + f.write_str(" LOCAL")?; + } + write!(f, " DIRECTORY {}", self.path)?; + if let Some(format) = &self.stored_as { + write!(f, " STORED AS {format}")?; + } + write!(f, " {}", self.source) + } +} + +impl Dialect for Spark { + type Ext = Builtin; + + fn parse_alter_table_op<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_alter_table_op(p) + } + + fn parse_like_quantifier<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Ok(grammar::parse_like_any(p)) + } + + fn eat_limit_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + grammar::set_operator_rule_with_minus(p) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + word.eq_ignore_ascii_case("MINUS") || grammar::is_reserved_for_alias(word) + } + + fn parse_group_by_suffix<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_group_by_grouping_sets(p) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, true, false) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + !word.eq_ignore_ascii_case("ALL") && grammar::is_reserved(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if p.at_keyword("EXECUTE") && p.peek_nth(1).is_word("IMMEDIATE") { + let execute = oracle::parse_execute_immediate(p)?; + return Ok(StatementKind::Ext(BuiltinStatement::Oracle(execute)).into()); + } + parse_statement(p) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_join<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_join(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_lateral_views<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_lateral_views(p) + } + + fn parse_query_distribution<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + parse_query_distribution(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert(p) + } + + fn parse_sample_clause<'a>( + p: &mut Parser<'a, Self>, + long_form: bool, + ) -> PResult> { + parse_sample_clause(p, long_form) + } + + fn parse_between_low<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let low = grammar::parse_between_low(p)?; + parse_between_bound(p, low) + } + + fn parse_between_high<'a>(p: &mut Parser<'a, Self>) -> PResult> { + let high = grammar::parse_between_high(p)?; + parse_between_bound(p, high) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_spark_token(rest) + } + + #[inline] + fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + string_literal(token) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + // `STRUCT(value AS name, ...)`, which BigQuery writes the same way. + if p.at_keyword("STRUCT") && p.peek_nth(1).is_op("(") { + return bigquery::parse_struct(p); + } + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_cte<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_cte(p) + } + + fn parse_pipe_operators<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_pipe_operators(p) + } + + fn eat_group_by_all<'a>(p: &mut Parser<'a, Self>) -> bool { + p.eat_keyword("ALL") + } + + fn parse_group_by_modifier<'a>(p: &mut Parser<'a, Self>) -> Option { + grammar::parse_group_by_with(p, true) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } +} + +impl fmt::Display for SparkOption<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.key.fmt(f)?; + match &self.value { + Some(value) if self.equals => write!(f, " = {value}"), + Some(value) => write!(f, " {value}"), + None => Ok(()), + } + } +} + +impl fmt::Display for PartitionColumn<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.name.fmt(f)?; + match &self.data_type { + Some(data_type) => write!(f, " {data_type}"), + None => Ok(()), + } + } +} + +impl fmt::Display for SparkTableClause<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Using(format) => write!(f, "USING {format}"), + Self::Options(options) => write!(f, "OPTIONS ({})", comma(options)), + Self::PartitionedBy(columns) => write!(f, "PARTITIONED BY ({})", comma(columns)), + Self::Location(location) => write!(f, "LOCATION {}", location), + Self::Comment(comment) => write!(f, "COMMENT {}", comment), + Self::TblProperties(options) => write!(f, "TBLPROPERTIES ({})", comma(options)), + Self::Like(source) => write!(f, "LIKE {source}"), + } + } +} + +impl fmt::Display for SparkCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + write_create_flags(f, table.or_replace, table.temporary)?; + f.write_str(if self.external { + "EXTERNAL TABLE " + } else { + "TABLE " + })?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + if !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + for clause in &self.clauses { + write!(f, " {clause}")?; + } + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} + +impl fmt::Display for SparkStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CreateTable(create) => create.fmt(f), + Self::Insert(insert) => insert.fmt(f), + Self::InsertDirectory(insert) => insert.fmt(f), + Self::Cache(cache) => cache.fmt(f), + Self::Uncache { table, if_exists } => { + let if_exists = if *if_exists { "IF EXISTS " } else { "" }; + write!(f, "UNCACHE TABLE {if_exists}{table}") + } + } + } +} diff --git a/sqlparser_v2/src/dialect/sqlite.rs b/sqlparser_v2/src/dialect/sqlite.rs new file mode 100644 index 0000000000..0d5e0e8a73 --- /dev/null +++ b/sqlparser_v2/src/dialect/sqlite.rs @@ -0,0 +1,2113 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! SQLite. + +use crate::ast::Span; +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + ArrayType, Assignment, BinaryOp, ColumnDef, ColumnOption, CreateTable, DataType, + DataTypeSuffix, Delete, Expr, ExprKind, Generated, GeneratedKind, GeneratedStorage, + GeneratedWhen, Ident, IndexColumn, Insert, InsertSource, IsTest, Join, JoinKind, Limit, + ObjectName, ObjectType, OrderByItem, SelectItem, SelectItemKind, Statement, StatementKind, + TableAlias, TableFactor, TableRef, TableWithJoins, UnaryOp, Update, WindowOver, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinStatement, BuiltinTableFactor}; +use crate::dialect::{Builtin, Dialect, mysql, postgres}; +use crate::display::{ + Indent, SpaceOrNewline, comma, write_columns, write_create_flags, write_if_not_exists, + write_indented_clause, write_list_clause, write_where_clause, +}; +use crate::grammar::{self, prec}; +use crate::lexer::{self, LexResult, Lexeme, Token, TokenKind, quoted}; +use crate::parser::{InfixParseFn, InfixRule, Parser}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Sqlite; + +/// Statements only SQLite has. +#[derive(Debug, Clone, PartialEq)] +pub enum SqliteStatement<'a> { + /// `PRAGMA name`, `PRAGMA name = value` or `PRAGMA name(value)` + Pragma { + name: ObjectName<'a>, + value: Option<(PragmaForm, Expr<'a, Builtin>)>, + }, + /// `ATTACH [DATABASE] file AS schema` + Attach { + database_keyword: bool, + file: Expr<'a, Builtin>, + schema: Ident<'a>, + }, + /// `BEGIN {DEFERRED | IMMEDIATE | EXCLUSIVE} [TRANSACTION]` + Begin { + modifier: Cow<'a, str>, + transaction_keyword: bool, + }, + CreateTable(Box>), + CreateVirtualTable(Box>), + CreateTrigger(Box>), + Insert(Box>), + Update(Box>), + Delete(Box>), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PragmaForm { + Equals, + Call, +} + +/// `CREATE TABLE` with table options, which come after the column list. +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + /// True if a comma comes before the first option. + pub leading_comma: bool, + pub options: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SqliteTableOption { + WithoutRowid, + Strict, +} + +/// `CREATE VIRTUAL TABLE [IF NOT EXISTS] name USING module [(args)]` +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteVirtualTable<'a> { + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub module: Ident<'a>, + pub args: Vec>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TriggerPeriod { + Before, + After, + InsteadOf, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TriggerEvent<'a> { + Delete, + Insert, + /// `UPDATE [OF columns]` + Update(Vec>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteTrigger<'a> { + pub temporary: bool, + pub if_not_exists: bool, + pub name: ObjectName<'a>, + pub period: Option, + pub event: TriggerEvent<'a>, + pub table: ObjectName<'a>, + pub for_each_row: bool, + pub when: Option>, + /// The statements between `BEGIN` and `END`, each followed by `;`. + pub statements: Vec>, +} + +/// An assignment in `UPDATE` or an upsert. +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteAssignment<'a> { + pub target: SqliteAssignmentTarget<'a>, + pub value: Expr<'a, Builtin>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SqliteAssignmentTarget<'a> { + Column(ObjectName<'a>), + /// `(a, b) = ...` + Tuple(Vec>), +} + +/// `INSERT` with syntax the core has no place for. +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteInsert<'a> { + /// The word after `OR`, also set for `REPLACE`, which means the same. + pub or_action: Option>, + pub table: ObjectName<'a>, + pub columns: Vec>, + /// `None` for `DEFAULT VALUES`. + pub source: Option>, + pub on_conflict: Option>, + pub returning: Vec>, +} + +/// `ON CONFLICT [(columns) [WHERE condition]] DO ...` +#[derive(Debug, Clone, PartialEq)] +pub struct OnConflict<'a> { + pub columns: Vec>, + pub predicate: Option>, + pub action: OnConflictAction<'a>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum OnConflictAction<'a> { + DoNothing, + DoUpdate { + assignments: Vec>, + selection: Option>, + }, +} + +/// `UPDATE` with syntax the core has no place for. +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteUpdate<'a> { + pub or_action: Option>, + pub table: TableRef<'a, Builtin>, + pub assignments: Vec>, + pub from: Vec>, + pub selection: Option>, + pub returning: Vec>, + pub limit: Option>, +} + +/// `DELETE` with syntax the core has no place for. +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteDelete<'a> { + pub table: TableRef<'a, Builtin>, + pub selection: Option>, + pub returning: Vec>, + pub order_by: Vec>, + pub limit: Option>, +} + +/// Expressions only SQLite has. +#[derive(Debug, Clone, PartialEq)] +pub enum SqliteExpr<'a> { + /// `expr [NOT] IN table`, where `target` is a name or a table function. + InTable { + expr: Box>, + target: Box>, + negated: bool, + }, +} + +/// A table with `INDEXED BY` or `NOT INDEXED` after it. The alias is on `table`. +#[derive(Debug, Clone, PartialEq)] +pub struct SqliteIndexedTable<'a> { + pub table: TableRef<'a, Builtin>, + /// The index name, or `None` for `NOT INDEXED`. + pub index: Option>, +} + +/// SQLite's binding powers. `=`, `IN` and the pattern operators share one +/// level, as in the core; the others are placed around it. +const EQUALITY: u8 = prec::COMPARE; +/// `<`, `<=`, `>` and `>=` bind tighter than the equality level. +const RELATIONAL: u8 = prec::COMPARE + 1; +/// `&`, `|`, `<<` and `>>` share one level. +const BITWISE: u8 = prec::BIT_AND; +/// `||`, `->` and `->>` bind tighter than `*`. +const CONCAT: u8 = prec::MUL + 2; + +/// The words that cannot name something. Everything else can fall back to an +/// identifier. See . +const MAX_RESERVED_LEN: usize = 13; + +#[inline] +pub fn is_reserved(word: &str) -> bool { + if word.len() > MAX_RESERVED_LEN { + return false; + } + let mut buffer = [0; MAX_RESERVED_LEN]; + let upper = &mut buffer[..word.len()]; + upper.copy_from_slice(word.as_bytes()); + upper.make_ascii_uppercase(); + matches!( + &*upper, + b"ADD" + | b"ALL" + | b"ALTER" + | b"AND" + | b"AS" + | b"AUTOINCREMENT" + | b"BETWEEN" + | b"CASE" + | b"CHECK" + | b"COLLATE" + | b"COMMIT" + | b"CONSTRAINT" + | b"CREATE" + | b"DEFAULT" + | b"DEFERRABLE" + | b"DELETE" + | b"DISTINCT" + | b"DROP" + | b"ELSE" + | b"ESCAPE" + | b"EXCEPT" + | b"EXISTS" + | b"FOREIGN" + | b"FROM" + | b"GROUP" + | b"HAVING" + | b"IN" + | b"INDEX" + | b"INSERT" + | b"INTERSECT" + | b"INTO" + | b"IS" + | b"JOIN" + | b"LIMIT" + | b"NOT" + | b"NOTHING" + | b"NOTNULL" + | b"NULL" + | b"ON" + | b"OR" + | b"ORDER" + | b"PRIMARY" + | b"REFERENCES" + | b"RETURNING" + | b"SELECT" + | b"SET" + | b"TABLE" + | b"THEN" + | b"TO" + | b"TRANSACTION" + | b"UNION" + | b"UNIQUE" + | b"UPDATE" + | b"USING" + | b"VALUES" + | b"WHEN" + | b"WHERE" + ) +} + +/// Words that end a select list, so cannot be a column alias without `AS`. +fn ends_select_item(word: &str) -> bool { + [ + "SELECT", + "WHERE", + "GROUP", + "HAVING", + "ORDER", + "LIMIT", + "UNION", + "EXCEPT", + "INTERSECT", + "RETURNING", + "VALUES", + "FROM", + "INTO", + ] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) +} + +/// Words that continue a `FROM` clause, so cannot be a table alias without `AS`. +fn ends_table_factor(word: &str) -> bool { + [ + "WITH", + "EXPLAIN", + "ANALYZE", + "SELECT", + "WHERE", + "GROUP", + "SORT", + "HAVING", + "ORDER", + "PIVOT", + "UNPIVOT", + "TOP", + "LATERAL", + "VIEW", + "LIMIT", + "OFFSET", + "FETCH", + "UNION", + "EXCEPT", + "INTERSECT", + "MINUS", + "ON", + "JOIN", + "INNER", + "CROSS", + "FULL", + "LEFT", + "RIGHT", + "NATURAL", + "USING", + "CLUSTER", + "DISTRIBUTE", + "GLOBAL", + "ANTI", + "SEMI", + "RETURNING", + "OUTPUT", + "ASOF", + "MATCH_CONDITION", + "OUTER", + "SET", + "QUALIFY", + "WINDOW", + "END", + "FOR", + "PARTITION", + "ARRAY", + "PREWHERE", + "SETTINGS", + "FORMAT", + "START", + "CONNECT", + "MATCH_RECOGNIZE", + "SAMPLE", + "TABLESAMPLE", + "FROM", + "OPEN", + "INDEXED", + "NOT", + ] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) +} + +#[inline] +fn is_word_start(byte: u8) -> bool { + byte.is_ascii_alphabetic() || byte == b'_' || byte >= 0x80 +} + +#[inline] +fn is_word_part(byte: u8) -> bool { + is_word_start(byte) || byte.is_ascii_digit() || byte == b'$' +} + +/// Lexes `[name]`, which has no escape for `]`. +#[inline] +fn bracketed(rest: &str) -> LexResult { + match rest.as_bytes().iter().position(|&b| b == b']') { + Some(end) => Ok(Lexeme { + kind: TokenKind::QuotedIdent, + len: end + 1, + }), + None => Err("unterminated quoted text"), + } +} + +/// Counts digits from `from`, allowing one `_` between two digits. +#[inline] +fn digits(bytes: &[u8], from: usize) -> usize { + let mut end = from; + while end < bytes.len() + && (bytes[end].is_ascii_digit() + || (bytes[end] == b'_' + && end > from + && bytes[end - 1].is_ascii_digit() + && bytes.get(end + 1).is_some_and(u8::is_ascii_digit))) + { + end += 1; + } + end - from +} + +/// Lexes a number. Digits can be grouped with `_`, and `1.e5` has no fraction. +fn number(bytes: &[u8]) -> LexResult { + let mut len = digits(bytes, 0); + if bytes.get(len) == Some(&b'.') { + len += 1 + digits(bytes, len + 1); + } + if matches!(bytes.get(len), Some(b'e' | b'E')) { + let sign = usize::from(matches!(bytes.get(len + 1), Some(b'+' | b'-'))); + let exponent = digits(bytes, len + 1 + sign); + if exponent > 0 { + len += 1 + sign + exponent; + } + } + if bytes.get(len).is_some_and(|&b| is_word_start(b)) { + return Err("invalid number"); + } + Ok(Lexeme { + kind: TokenKind::Number, + len, + }) +} + +/// Lexes `$name`, `:name` and `@name`. Unlike the others, `$` needs no name. +fn placeholder(bytes: &[u8]) -> Option { + let name = bytes[1..].iter().take_while(|&&b| is_word_part(b)).count(); + (name > 0 || bytes[0] == b'$').then_some(Ok(Lexeme { + kind: TokenKind::Placeholder, + len: 1 + name, + })) +} + +#[inline] +pub fn lex_token(rest: &str) -> Option { + let op = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Op, + len, + })) + }; + let bytes = rest.as_bytes(); + match bytes { + [b'`', ..] => Some(quoted(rest, TokenKind::QuotedIdent)), + [b'[', ..] => Some(bracketed(rest)), + [b'=', b'=', ..] | [b':', b':', ..] => op(2), + [b'-', b'>', b'>', ..] => op(3), + [b'-', b'>', ..] => op(2), + [b'~', ..] => op(1), + [b'0', b'x', ..] => None, + [b'x' | b'X', b'\'', ..] => None, + [b'0'..=b'9', ..] | [b'.', b'0'..=b'9', ..] => Some(number(bytes)), + [b'$' | b':' | b'@', ..] => placeholder(bytes), + [b, ..] if is_word_start(*b) => Some(Ok(Lexeme { + kind: TokenKind::Word, + len: bytes.iter().take_while(|&&b| is_word_part(b)).count(), + })), + _ => None, + } +} + +/// `--` comments, and `/* */` comments that do not nest and need not be closed. +#[inline] +pub fn lex_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'-', b'-', ..] => Some(Ok(lexer::line_comment(rest))), + [b'/', b'*', ..] => Some(Ok(lexer::block_comment(rest, false).unwrap_or(rest.len()))), + _ => None, + } +} + +fn string_ident(token: Token<'_>) -> Ident<'_> { + Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some('\''), + span: token.span, + } +} + +/// Parses any word, quoted name or string as a name, for aliases and windows. +fn parse_any_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::Word => { + p.advance(); + Ok(Ident { + text: token.text.into(), + quote: None, + span: token.span, + }) + } + TokenKind::QuotedIdent => p.parse_ident(), + TokenKind::String => { + p.advance(); + Ok(string_ident(token)) + } + _ => Err(p.expected("a name")), + } +} + +/// Parses a dotted name in which any part can be a string. +fn parse_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let first = if p.peek().kind == TokenKind::String { + parse_any_name(p)? + } else { + p.parse_ident()? + }; + let mut parts = vec![first]; + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + Ok(ObjectName { parts }) +} + +pub fn parse_name_part<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.peek().kind == TokenKind::String { + return parse_any_name(p); + } + grammar::parse_name_part(p) +} + +/// True at a `'name'.*` reference, whose first part is a string. +fn at_string_wildcard<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if p.peek().kind != TokenKind::String { + return false; + } + let mut n = 1; + loop { + if !p.peek_nth(n).is_op(".") { + return false; + } + let next = p.peek_nth(n + 1); + if next.is_op("*") { + return true; + } + if !matches!( + next.kind, + TokenKind::Word | TokenKind::QuotedIdent | TokenKind::String + ) { + return false; + } + n += 2; + } +} + +pub fn parse_select_item<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if at_string_wildcard(p) { + let mut parts = vec![parse_any_name(p)?]; + loop { + p.expect_op(".")?; + if p.eat_op("*") { + return Ok(SelectItemKind::QualifiedWildcard(ObjectName { parts }).into()); + } + parts.push(p.parse_name_part()?); + } + } + grammar::parse_select_item(p) +} + +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, D::Ext>, +) -> PResult> { + let explicit = p.eat_keyword("AS"); + let token = p.peek(); + let implicit = matches!(token.kind, TokenKind::QuotedIdent | TokenKind::String) + || (token.kind == TokenKind::Word && !ends_select_item(token.text)); + let alias = if explicit || implicit { + Some(parse_any_name(p)?) + } else { + None + }; + Ok(SelectItemKind::Expr { expr, alias }.into()) +} + +fn parse_table_alias<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let explicit = p.eat_keyword("AS"); + let token = p.peek(); + let implicit = match token.kind { + TokenKind::QuotedIdent | TokenKind::String => true, + TokenKind::Word => !ends_table_factor(token.text), + _ => false, + }; + if !explicit && !implicit { + return Ok(None); + } + let name = parse_any_name(p)?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + Ok(Some(TableAlias { + name, + explicit, + columns, + column_types: Vec::new(), + })) +} + +/// Parses `INDEXED BY name` or `NOT INDEXED`. +fn parse_indexed_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if p.at_keyword("INDEXED") { + p.advance(); + p.expect_keyword("BY")?; + return p.parse_ident().map(|index| Some(Some(index))); + } + if p.at_keyword("NOT") && p.peek_nth(1).is_word("INDEXED") { + p.advance(); + p.advance(); + return Ok(Some(None)); + } + Ok(None) +} + +/// Removes parentheses around a single table, which only group a join in the +/// core. An alias outside moves onto the table inside. +fn flatten_parentheses<'a, D: Dialect>( + p: &Parser<'a, D>, + table: TableRef<'a, Builtin>, +) -> PResult> { + match table.factor { + TableFactor::NestedJoin(nested) + if nested.joins.is_empty() + && !matches!(nested.relation.factor, TableFactor::NestedJoin(_)) => + { + let mut inner = nested.relation; + let Some(alias) = table.alias else { + return Ok(inner); + }; + if let TableFactor::Ext(BuiltinTableFactor::Sqlite(indexed)) = &mut inner.factor { + if indexed.table.alias.is_none() { + indexed.table.alias = Some(alias); + return Ok(inner); + } + } else if inner.alias.is_none() { + inner.alias = Some(alias); + return Ok(inner); + } + Err(p.expected("one alias for a parenthesized table")) + } + factor => Ok(TableRef { + factor, + alias: table.alias, + span: Span::default(), + }), + } +} + +pub fn parse_table_ref<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let factor = D::parse_table_factor(p)?; + let can_be_indexed = matches!(factor, TableFactor::Named(_) | TableFactor::Function { .. }); + let alias = parse_table_alias(p)?; + let table = TableRef { + factor, + alias, + span: Span::default(), + }; + if can_be_indexed && let Some(index) = parse_indexed_clause(p)? { + let indexed = SqliteIndexedTable { table, index }; + return Ok(TableRef { + factor: TableFactor::Ext(BuiltinTableFactor::Sqlite(Box::new(indexed))), + alias: None, + span: Span::default(), + }); + } + flatten_parentheses(p, table) +} + +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.peek().kind == TokenKind::String { + return parse_name(p).map(TableFactor::Named); + } + grammar::parse_table_factor(p) +} + +/// Parses a `FROM` list, where a comma can act as a join with a constraint. +pub fn parse_from_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut tables: Vec> = Vec::new(); + loop { + let table = D::parse_table_with_joins(p)?; + let has_constraint = p.at_keyword("ON") || p.at_keyword("USING"); + match tables.last_mut() { + Some(previous) if table.joins.is_empty() && has_constraint => { + let constraint = grammar::parse_join_constraint(p)?; + previous.joins.push(Join { + kind: JoinKind::Inner, + spelled_out: false, + table: table.relation, + constraint, + }); + while let Some(join) = D::parse_join(p)? { + previous.joins.push(join); + } + } + _ => tables.push(table), + } + if !p.eat_op(",") { + return Ok(tables); + } + } +} + +fn parse_is<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + bp: u8, +) -> PResult> { + let negated = p.peek_nth(1).is_word("NOT"); + let next = p.peek_nth(if negated { 2 } else { 1 }); + let core_test = ["NULL", "TRUE", "FALSE", "DISTINCT"] + .iter() + .any(|word| next.is_word(word)); + if core_test { + return grammar::parse_is(p, left, bp); + } + p.advance(); + if negated { + p.advance(); + } + let right = p.parse_expr_bp(bp)?; + Ok(ExprKind::Binary { + left: Box::new(left), + op: BinaryOp::Named(if negated { + "IS NOT".into() + } else { + "IS".into() + }), + right: Box::new(right), + } + .into()) +} + +/// Parses `IN` and `NOT IN`, whose right side can name a table. +fn parse_in_operand<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + negated: bool, +) -> PResult> { + let token = p.peek(); + let table_name = token.kind == TokenKind::QuotedIdent + || (token.kind == TokenKind::Word && !D::is_reserved(token.text)); + if table_name { + let start = p.peek().span.start; + let name = grammar::parse_object_name(p)?; + let target = if p.at_op("(") { + p.parse_function_call(name)? + } else { + ExprKind::Compound(name).into() + }; + let target = Expr::new(target.kind, p.span_since(start)); + return Ok(ExprKind::Ext(BuiltinExpr::Sqlite(SqliteExpr::InTable { + expr: Box::new(left), + target: Box::new(target), + negated, + })) + .into()); + } + p.expect_op("(")?; + if grammar::query_starts_at(p, 0) { + let subquery = Box::new(grammar::parse_subquery_body(p)?); + return Ok(ExprKind::InSubquery { + expr: Box::new(left), + subquery, + negated, + } + .into()); + } + let list = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op(")")?; + Ok(ExprKind::InList { + expr: Box::new(left), + list, + negated, + } + .into()) +} + +fn parse_in<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.advance(); + parse_in_operand(p, left, false) +} + +fn parse_not_in<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, Builtin>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + parse_in_operand(p, left, true) +} + +/// A postfix `ISNULL`, `NOTNULL` or `NOT NULL`, as an `IS` test. +fn null_test<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + words: usize, + negated: bool, +) -> PResult> { + for _ in 0..words { + p.advance(); + } + Ok(ExprKind::Is { + expr: Box::new(left), + test: IsTest::Null, + negated, + } + .into()) +} + +fn parse_isnull<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + null_test(p, left, 1, false) +} + +fn parse_notnull<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + null_test(p, left, 1, true) +} + +fn parse_not_null<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + null_test(p, left, 2, true) +} + +fn parse_not_pattern<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + bp: u8, +) -> PResult> { + p.advance(); + let token = p.advance(); + let op = if token.is_word("MATCH") { + BinaryOp::Named("NOT MATCH".into()) + } else if token.is_word("GLOB") { + BinaryOp::Named("NOT GLOB".into()) + } else { + BinaryOp::Named("NOT REGEXP".into()) + }; + let right = p.parse_expr_bp(bp)?; + Ok(ExprKind::Binary { + left: Box::new(left), + op, + right: Box::new(right), + } + .into()) +} + +fn pattern_op(word: &str) -> Option> { + if word.eq_ignore_ascii_case("MATCH") { + Some(BinaryOp::Named("MATCH".into())) + } else if word.eq_ignore_ascii_case("GLOB") { + Some(BinaryOp::Named("GLOB".into())) + } else if word.eq_ignore_ascii_case("REGEXP") { + Some(BinaryOp::Named("REGEXP".into())) + } else { + None + } +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + let token = p.peek(); + match token.kind { + TokenKind::Op => { + let op = |op| Some((RELATIONAL, op)); + let bit = |op| Some((BITWISE, op)); + let concat = |op| Some((CONCAT, op)); + let rule = match token.text { + "==" => Some((EQUALITY, BinaryOp::Eq)), + "<" => op(BinaryOp::Lt), + "<=" => op(BinaryOp::LtEq), + ">" => op(BinaryOp::Gt), + ">=" => op(BinaryOp::GtEq), + "&" => bit(BinaryOp::BitAnd), + "|" => bit(BinaryOp::BitOr), + "<<" => bit(BinaryOp::ShiftLeft), + ">>" => bit(BinaryOp::ShiftRight), + "||" => concat(BinaryOp::StringConcat), + "->" => concat(BinaryOp::Named("->".into())), + "->>" => concat(BinaryOp::Named("->>".into())), + "::" => { + let parse: InfixParseFn<'a, D> = postgres::parse_double_colon; + return Some(InfixRule::custom(prec::POSTFIX, parse)); + } + _ => None, + }; + if let Some((bp, op)) = rule { + return Some(InfixRule::binary(bp, op)); + } + } + TokenKind::Word => { + if let Some(op) = pattern_op(token.text) { + return Some(InfixRule::binary(EQUALITY, op)); + } + if token.is_word("IS") { + let parse: InfixParseFn<'a, D> = parse_is; + return Some(InfixRule::custom(EQUALITY, parse)); + } + if token.is_word("IN") { + let parse: InfixParseFn<'a, D> = parse_in; + return Some(InfixRule::custom(EQUALITY, parse)); + } + if token.is_word("ISNULL") { + let parse: InfixParseFn<'a, D> = parse_isnull; + return Some(InfixRule::custom(EQUALITY, parse)); + } + if token.is_word("NOTNULL") { + let parse: InfixParseFn<'a, D> = parse_notnull; + return Some(InfixRule::custom(EQUALITY, parse)); + } + if token.is_word("NOT") { + let next = p.peek_nth(1); + let parse: Option> = if next.is_word("IN") { + Some(parse_not_in) + } else if next.is_word("NULL") { + Some(parse_not_null) + } else if next.kind == TokenKind::Word && pattern_op(next.text).is_some() { + Some(parse_not_pattern) + } else { + None + }; + if let Some(parse) = parse { + return Some(InfixRule::custom(EQUALITY, parse)); + } + } + } + _ => {} + } + grammar::infix_rule(p) +} + +pub fn parse_between_low<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.parse_expr_bp(prec::AND) +} + +pub fn parse_prefix<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.peek().kind == TokenKind::String && p.peek_nth(1).is_op(".") { + let name = parse_name(p)?; + return if p.at_op("(") { + p.parse_function_call(name) + } else { + Ok(ExprKind::Compound(name).into()) + }; + } + if p.eat_op("~") { + let expr = p.parse_expr_bp(prec::UNARY)?; + return Ok(ExprKind::Unary { + op: UnaryOp::BitNot, + expr: Box::new(expr), + } + .into()); + } + grammar::parse_prefix(p) +} + +/// `OVER` starts a window only before `(` or a name. Otherwise it is an alias, +/// left for the select list to read. +pub fn parse_function_over<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.at_keyword("OVER") { + return Ok(None); + } + let next = p.peek_nth(1); + if next.is_op("(") { + p.advance(); + return grammar::parse_window_over(p).map(Some); + } + let names_window = match next.kind { + TokenKind::Word => !ends_select_item(next.text), + TokenKind::String | TokenKind::QuotedIdent => true, + _ => false, + }; + if !names_window { + return Ok(None); + } + p.advance(); + parse_any_name(p).map(|name| Some(WindowOver::Named(name))) +} + +/// The arguments of a data type, with their signs, if they can only be read +/// by SQLite: at most two, and signed or not integers. +fn signed_args<'a, D: Dialect>(p: &Parser<'a, D>) -> Option<(Vec<&'a str>, [u8; 2], usize)> { + if !p.peek_nth(1).is_op("(") { + return None; + } + let mut args = Vec::with_capacity(2); + let mut signs = [0; 2]; + let mut n = 2; + let mut unusual = false; + for sign in &mut signs { + let token = p.peek_nth(n); + if token.is_op("-") || token.is_op("+") { + *sign = token.text.as_bytes()[0]; + unusual = true; + n += 1; + } + let number = p.peek_nth(n); + if number.kind != TokenKind::Number { + return None; + } + unusual |= number.text.parse::().is_err(); + args.push(number.text); + n += 1; + if p.peek_nth(n).is_op(")") { + n += 1; + return unusual.then_some((args, signs, n)); + } + if !p.peek_nth(n).is_op(",") { + return None; + } + n += 1; + } + None +} + +pub fn parse_data_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.at_op(")") { + return Ok(DataType::unspecified(p.peek().span)); + } + if matches!(p.peek().kind, TokenKind::Word | TokenKind::QuotedIdent) + && let Some((args, signs, tokens)) = signed_args(p) + { + let name = p.parse_ident()?; + for _ in 1..tokens { + p.advance(); + } + return Ok(DataType { + qualifier: Vec::new(), + name, + angle: None, + args: args.into_iter().map(Cow::Borrowed).collect(), + suffix: DataTypeSuffix::SignedArgs(signs), + array: ArrayType::None, + }); + } + let mut data_type = grammar::parse_data_type(p)?; + if data_type.args.iter().any(|arg| arg.parse::().is_err()) { + return Err(p.expected("at most two numeric type arguments")); + } + if data_type.suffix == DataTypeSuffix::None && p.eat_keyword("UNSIGNED") { + data_type.suffix = DataTypeSuffix::Unsigned; + } + Ok(data_type) +} + +/// True if a column definition goes straight to its constraints. +fn at_untyped_column<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let token = p.peek(); + match token.kind { + TokenKind::QuotedIdent => false, + TokenKind::Word => [ + "CONSTRAINT", + "PRIMARY", + "NOT", + "UNIQUE", + "CHECK", + "DEFAULT", + "COLLATE", + "REFERENCES", + "GENERATED", + "AS", + ] + .iter() + .any(|word| token.is_word(word)), + _ => true, + } +} + +pub fn parse_column_def<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = if p.peek().kind == TokenKind::String { + parse_any_name(p)? + } else { + p.parse_ident()? + }; + let data_type = if at_untyped_column(p) { + DataType::unspecified(p.peek().span) + } else { + D::parse_data_type(p)? + }; + let mut options = Vec::new(); + while let Some(option) = D::parse_column_option(p)? { + options.push(option); + } + grammar::check_column_attributes(p, &options)?; + Ok(ColumnDef { + name, + data_type, + options, + }) +} + +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.at_keyword("ON") && p.peek_nth(1).is_word("CONFLICT") { + p.advance(); + p.advance(); + const ACTIONS: [(&str, &str); 5] = [ + ("ROLLBACK", "ON CONFLICT ROLLBACK"), + ("ABORT", "ON CONFLICT ABORT"), + ("FAIL", "ON CONFLICT FAIL"), + ("IGNORE", "ON CONFLICT IGNORE"), + ("REPLACE", "ON CONFLICT REPLACE"), + ]; + let Some((_, keyword)) = ACTIONS.iter().find(|(word, _)| p.eat_keyword(word)) else { + return Err(p.expected("ROLLBACK, ABORT, FAIL, IGNORE or REPLACE")); + }; + return Ok(Some(ColumnOption::Keyword { + keyword: (*keyword).into(), + expr: None, + })); + } + for keyword in ["AUTOINCREMENT", "ASC", "DESC"] { + if p.eat_keyword(keyword) { + return Ok(Some(ColumnOption::Keyword { + keyword: keyword.into(), + expr: None, + })); + } + } + if p.eat_keyword("CONSTRAINT") { + let name = p.parse_ident()?; + let Some(option) = D::parse_column_option(p)? else { + return Err(p.expected("constraint details after CONSTRAINT ")); + }; + return Ok(Some(ColumnOption::Named { + name, + option: Box::new(option), + })); + } + // A full expression here would read a following `NOT NULL` as a postfix test. + if p.eat_keyword("DEFAULT") { + return p + .nested(Parser::parse_prefix) + .map(|expr| Some(ColumnOption::Default(expr))); + } + if p.at_keyword("AS") && p.peek_nth(1).is_op("(") { + p.advance(); + p.advance(); + let expr = p.parse_expr()?; + p.expect_op(")")?; + let storage = if p.eat_keyword("STORED") { + Some(GeneratedStorage::Stored) + } else if p.eat_keyword("VIRTUAL") { + Some(GeneratedStorage::Virtual) + } else { + None + }; + return Ok(Some(ColumnOption::Generated(Box::new(Generated { + when: Some(GeneratedWhen::Omitted), + kind: GeneratedKind::Expr { expr, storage }, + })))); + } + grammar::parse_column_option(p) +} + +/// Parses `(columns)`, returning no columns if there is no list. +fn parse_optional_columns<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if grammar::at_column_list(p) { + grammar::parse_ident_list(p) + } else { + Ok(Vec::new()) + } +} + +fn parse_table_option<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("WITHOUT") { + p.expect_keyword("ROWID")?; + return Ok(Some(SqliteTableOption::WithoutRowid)); + } + Ok(p.eat_keyword("STRICT").then_some(SqliteTableOption::Strict)) +} + +/// Parses `[,] option [, option ...]`, or nothing if no option comes next. +fn parse_table_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(bool, Vec)> { + let next = p.peek_nth(1); + let leading_comma = p.at_op(",") && (next.is_word("STRICT") || next.is_word("WITHOUT")); + if leading_comma { + p.advance(); + } + let mut options = Vec::new(); + let Some(first) = parse_table_option(p)? else { + return Ok((false, options)); + }; + options.push(first); + while p.eat_op(",") { + match parse_table_option(p)? { + Some(option) => options.push(option), + None => return Err(p.expected("WITHOUT ROWID or STRICT")), + } + } + Ok((leading_comma, options)) +} + +fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + temporary: bool, +) -> PResult> { + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_name(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let (leading_comma, options) = parse_table_options(p)?; + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && constraints.is_empty() && query.is_none() { + return Err(p.expected("column definitions or AS")); + } + let table = CreateTable { + or_replace: false, + temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + if options.is_empty() { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + Ok(sqlite(SqliteStatement::CreateTable(Box::new( + SqliteCreateTable { + table, + leading_comma, + options, + }, + )))) +} + +fn parse_virtual_table<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("VIRTUAL")?; + p.expect_keyword("TABLE")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_name(p)?; + p.expect_keyword("USING")?; + let module = parse_any_name(p)?; + let args = if p.eat_op("(") { + let args = p.parse_comma_separated(parse_any_name)?; + p.expect_op(")")?; + args + } else { + Vec::new() + }; + Ok(SqliteVirtualTable { + if_not_exists, + name, + module, + args, + }) +} + +fn parse_trigger_event<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("DELETE") { + return Ok(TriggerEvent::Delete); + } + if p.eat_keyword("INSERT") { + return Ok(TriggerEvent::Insert); + } + p.expect_keyword("UPDATE")?; + let columns = if p.eat_keyword("OF") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + Ok(TriggerEvent::Update(columns)) +} + +fn parse_trigger<'a, D: Dialect>( + p: &mut Parser<'a, D>, + temporary: bool, +) -> PResult> { + p.expect_keyword("TRIGGER")?; + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = parse_name(p)?; + let period = if p.eat_keyword("BEFORE") { + Some(TriggerPeriod::Before) + } else if p.eat_keyword("AFTER") { + Some(TriggerPeriod::After) + } else if p.eat_keyword("INSTEAD") { + p.expect_keyword("OF")?; + Some(TriggerPeriod::InsteadOf) + } else { + None + }; + let event = parse_trigger_event(p)?; + p.expect_keyword("ON")?; + let table = parse_name(p)?; + let for_each_row = p.eat_keyword("FOR"); + if for_each_row { + p.expect_keyword("EACH")?; + p.expect_keyword("ROW")?; + } + let when = if p.eat_keyword("WHEN") { + Some(p.parse_expr()?) + } else { + None + }; + p.expect_keyword("BEGIN")?; + let mut statements = Vec::new(); + while !p.at_keyword("END") { + statements.push(p.nested(|p| p.parse_statement())?); + p.expect_op(";")?; + } + if statements.is_empty() { + return Err(p.expected("a statement in the trigger body")); + } + p.expect_keyword("END")?; + Ok(SqliteTrigger { + temporary, + if_not_exists, + name, + period, + event, + table, + for_each_row, + when, + statements, + }) +} + +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let temporary = p.peek_nth(1).is_word("TEMP") || p.peek_nth(1).is_word("TEMPORARY"); + let object = p.peek_nth(if temporary { 2 } else { 1 }); + if object.is_word("TRIGGER") || object.is_word("TABLE") || object.is_word("VIRTUAL") { + p.advance(); + if temporary { + p.advance(); + } + if object.is_word("TRIGGER") { + let trigger = parse_trigger(p, temporary)?; + return Ok(sqlite(SqliteStatement::CreateTrigger(Box::new(trigger)))); + } + if object.is_word("TABLE") { + return parse_create_table(p, temporary); + } + if temporary { + return Err(p.expected("TABLE or TRIGGER")); + } + let table = parse_virtual_table(p)?; + return Ok(sqlite(SqliteStatement::CreateVirtualTable(Box::new(table)))); + } + grammar::parse_create(p) +} + +fn sqlite<'a>(statement: SqliteStatement<'a>) -> Statement<'a, Builtin> { + StatementKind::Ext(BuiltinStatement::Sqlite(statement)).into() +} + +fn parse_or_action<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.eat_keyword("OR") { + return Ok(None); + } + match ["ROLLBACK", "ABORT", "REPLACE", "FAIL", "IGNORE"] + .into_iter() + .find(|word| p.eat_keyword(word)) + { + Some(action) => Ok(Some(action)), + None => Err(p.expected("ROLLBACK, ABORT, REPLACE, FAIL or IGNORE")), + } +} + +fn parse_assignment<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let target = if p.eat_op("(") { + let targets = p.parse_comma_separated(grammar::parse_object_name)?; + p.expect_op(")")?; + SqliteAssignmentTarget::Tuple(targets) + } else { + SqliteAssignmentTarget::Column(grammar::parse_object_name(p)?) + }; + if !p.eat_op("=") && !p.eat_op("==") { + return Err(p.expected("=")); + } + let value = p.parse_expr()?; + Ok(SqliteAssignment { target, value }) +} + +/// Converts assignments to the core's, or hands them back if one is a tuple. +fn core_assignments<'a>( + assignments: Vec>, +) -> Result>, Vec>> { + let has_tuple = assignments + .iter() + .any(|assignment| matches!(assignment.target, SqliteAssignmentTarget::Tuple(_))); + if has_tuple { + return Err(assignments); + } + Ok(assignments + .into_iter() + .filter_map(|assignment| match assignment.target { + SqliteAssignmentTarget::Column(target) => Some(Assignment { + target, + value: assignment.value, + }), + SqliteAssignmentTarget::Tuple(_) => None, + }) + .collect()) +} + +fn parse_on_conflict<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ON")?; + p.expect_keyword("CONFLICT")?; + let columns = if p.at_op("(") { + grammar::parse_ident_list(p)? + } else { + Vec::new() + }; + let predicate = grammar::parse_optional_where(p)?; + p.expect_keyword("DO")?; + let action = if p.eat_keyword("NOTHING") { + OnConflictAction::DoNothing + } else { + p.expect_keyword("UPDATE")?; + p.expect_keyword("SET")?; + OnConflictAction::DoUpdate { + assignments: p.parse_comma_separated(parse_assignment)?, + selection: grammar::parse_optional_where(p)?, + } + }; + Ok(OnConflict { + columns, + predicate, + action, + }) +} + +pub fn parse_insert<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let or_action = if p.eat_keyword("REPLACE") { + Some("REPLACE") + } else { + p.expect_keyword("INSERT")?; + parse_or_action(p)? + }; + p.expect_keyword("INTO")?; + let table = parse_name(p)?; + let columns = parse_optional_columns(p)?; + let source = if columns.is_empty() && p.at_keyword("DEFAULT") && p.peek_nth(1).is_word("VALUES") + { + p.advance(); + p.advance(); + None + } else { + Some(grammar::parse_insert_source(p)?) + }; + let on_conflict = if p.at_keyword("ON") { + Some(parse_on_conflict(p)?) + } else { + None + }; + let returning = D::parse_returning(p)?; + match source { + Some(source) if or_action.is_none() && on_conflict.is_none() => { + Ok(StatementKind::Insert(Box::new(Insert { + into: true, + output: None, + modifiers: Default::default(), + table, + columns, + source, + returning, + })) + .into()) + } + source => Ok(sqlite(SqliteStatement::Insert(Box::new(SqliteInsert { + or_action: or_action.map(Cow::Borrowed), + table, + columns, + source, + on_conflict, + returning, + })))), + } +} + +fn parse_limit_expr<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("LIMIT") { + p.parse_expr().map(Some) + } else { + Ok(None) + } +} + +fn parse_update<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("UPDATE")?; + let or_action = parse_or_action(p)?; + let table = p.parse_table_ref()?; + p.expect_keyword("SET")?; + let mut assignments = p.parse_comma_separated(parse_assignment)?; + let from = if p.eat_keyword("FROM") { + D::parse_from_list(p)? + } else { + Vec::new() + }; + let selection = grammar::parse_optional_where(p)?; + let returning = D::parse_returning(p)?; + let limit = parse_limit_expr(p)?; + if or_action.is_none() && from.is_empty() && limit.is_none() { + match core_assignments(assignments) { + Ok(assignments) => { + return Ok(StatementKind::Update(Box::new(Update { + output: None, + from: Vec::new(), + from_before_set: false, + table, + joins: Vec::new(), + assignments, + selection, + order_by: Vec::new(), + limit: None, + returning, + })) + .into()); + } + Err(unchanged) => assignments = unchanged, + } + } + Ok(sqlite(SqliteStatement::Update(Box::new(SqliteUpdate { + or_action: or_action.map(Cow::Borrowed), + table, + assignments, + from, + selection, + returning, + limit, + })))) +} + +fn parse_delete<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DELETE")?; + p.expect_keyword("FROM")?; + let table = p.parse_table_ref()?; + let selection = grammar::parse_optional_where(p)?; + let returning = D::parse_returning(p)?; + let order_by = if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + p.parse_comma_separated(D::parse_order_by_item)? + } else { + Vec::new() + }; + let limit = parse_limit_expr(p)?; + if order_by.is_empty() && limit.is_none() { + return Ok(StatementKind::Delete(Box::new(Delete { + output: None, + multi: None, + using: Vec::new(), + table, + selection, + order_by: Vec::new(), + limit: None, + returning, + })) + .into()); + } + Ok(sqlite(SqliteStatement::Delete(Box::new(SqliteDelete { + table, + selection, + returning, + order_by, + limit, + })))) +} + +fn parse_pragma_value<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::Word { + p.advance(); + return Ok(Expr::new( + ExprKind::Ident(Ident { + text: token.text.into(), + quote: None, + span: token.span, + }), + token.span, + )); + } + if p.at_op("(") { + return Err(p.expected("a pragma value")); + } + p.nested(Parser::parse_prefix) +} + +fn parse_pragma<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("PRAGMA")?; + let name = parse_name(p)?; + let value = if p.eat_op("=") { + Some((PragmaForm::Equals, parse_pragma_value(p)?)) + } else if p.eat_op("(") { + let value = parse_pragma_value(p)?; + p.expect_op(")")?; + Some((PragmaForm::Call, value)) + } else { + None + }; + Ok(SqliteStatement::Pragma { name, value }) +} + +fn parse_attach<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ATTACH")?; + let database_keyword = p.eat_keyword("DATABASE"); + let file = p.parse_expr()?; + p.expect_keyword("AS")?; + let schema = parse_any_name(p)?; + Ok(SqliteStatement::Attach { + database_keyword, + file, + schema, + }) +} + +fn at_begin_modifier<'a, D: Dialect>(p: &Parser<'a, D>) -> Option<&'static str> { + if !p.at_keyword("BEGIN") { + return None; + } + let next = p.peek_nth(1); + ["DEFERRED", "IMMEDIATE", "EXCLUSIVE"] + .into_iter() + .find(|word| next.is_word(word)) +} + +fn parse_begin<'a, D: Dialect>( + p: &mut Parser<'a, D>, + modifier: &'static str, +) -> SqliteStatement<'a> { + p.advance(); + p.advance(); + let transaction_keyword = p.eat_keyword("TRANSACTION"); + SqliteStatement::Begin { + modifier: modifier.into(), + transaction_keyword, + } +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("ANALYZE") { + return grammar::parse_analyze(p); + } + if p.at_keyword("PRAGMA") { + return parse_pragma(p).map(sqlite); + } + if p.at_keyword("ATTACH") { + return parse_attach(p).map(sqlite); + } + if let Some(modifier) = at_begin_modifier(p) { + return Ok(sqlite(parse_begin(p, modifier))); + } + if p.at_keyword("REPLACE") || p.at_keyword("INSERT") { + return D::parse_insert_statement(p); + } + if p.at_keyword("UPDATE") { + return parse_update(p); + } + if p.at_keyword("DELETE") { + return parse_delete(p); + } + grammar::parse_statement(p) +} + +impl Dialect for Sqlite { + type Ext = Builtin; + + fn parse_statement_after_with<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_dml_after_with(p, true, true) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn lex_comment(rest: &str) -> Option> { + lex_comment(rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + is_reserved(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_insert_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_insert(p) + } + + fn parse_returning<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + postgres::parse_returning(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + p.eat_keyword("TRIGGER") + .then_some(ObjectType::Named("TRIGGER".into())) + } + + fn parse_column_def<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_column_def(p) + } + + fn parse_column_option<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_column_option(p) + } + + fn parse_data_type<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_data_type(p) + } + + // Every word that can name a column can also stand here, so there is no + // operator class to look for. + fn parse_index_column<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_order_by_item(p).map(|item| IndexColumn { + item, + operator_class: None, + }) + } + + fn parse_from_list<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + parse_from_list(p) + } + + fn check_nested_join<'a>( + _p: &Parser<'a, Self>, + _table: &TableWithJoins<'a, Builtin>, + ) -> PResult<()> { + Ok(()) + } + + fn parse_table_ref<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_ref(p) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_table_factor(p) + } + + fn parse_name_part<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_name_part(p) + } + + fn parse_select_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_item(p) + } + + fn parse_select_item_alias<'a>( + p: &mut Parser<'a, Self>, + expr: Expr<'a, Builtin>, + ) -> PResult> { + parse_select_item_alias(p, expr) + } + + fn parse_between_low<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_between_low(p) + } + + fn parse_limit<'a>(p: &mut Parser<'a, Self>) -> PResult> { + mysql::parse_limit(p) + } + + fn at_empty_function_args<'a>(p: &Parser<'a, Self>) -> bool { + p.at_op(")") || p.at_keyword("ORDER") + } + + fn parse_function_over<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + parse_function_over(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn infix_rule<'a>(p: &Parser<'a, Self>) -> Option> { + infix_rule(p) + } +} + +impl fmt::Display for SqliteIndexedTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.table.fmt(f)?; + match &self.index { + Some(index) => write!(f, " INDEXED BY {index}"), + None => f.write_str(" NOT INDEXED"), + } + } +} + +impl fmt::Display for SqliteExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InTable { + expr, + target, + negated, + } => { + let not = if *negated { "NOT " } else { "" }; + write!(f, "{expr} {not}IN {target}") + } + } + } +} + +impl fmt::Display for SqliteAssignmentTarget<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Column(column) => column.fmt(f), + Self::Tuple(columns) => write!(f, "({})", comma(columns)), + } + } +} + +impl fmt::Display for SqliteAssignment<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} = {}", self.target, self.value) + } +} + +impl fmt::Display for SqliteTableOption { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::WithoutRowid => "WITHOUT ROWID", + Self::Strict => "STRICT", + }) + } +} + +impl fmt::Display for SqliteCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + write_create_flags(f, table.or_replace, table.temporary)?; + f.write_str("TABLE ")?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + if !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + let comma_prefix = if self.leading_comma { ", " } else { " " }; + write!(f, "{comma_prefix}{}", comma(&self.options))?; + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + Ok(()) + } +} + +impl fmt::Display for SqliteVirtualTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CREATE VIRTUAL TABLE ")?; + write_if_not_exists(f, self.if_not_exists)?; + write!(f, "{} USING {}", self.name, self.module)?; + if !self.args.is_empty() { + write!(f, " ({})", comma(&self.args))?; + } + Ok(()) + } +} + +impl fmt::Display for TriggerEvent<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Delete => f.write_str("DELETE"), + Self::Insert => f.write_str("INSERT"), + Self::Update(columns) if columns.is_empty() => f.write_str("UPDATE"), + Self::Update(columns) => write!(f, "UPDATE OF {}", comma(columns)), + } + } +} + +impl fmt::Display for SqliteTrigger<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_create_flags(f, false, self.temporary)?; + f.write_str("TRIGGER ")?; + write_if_not_exists(f, self.if_not_exists)?; + write!(f, "{} ", self.name)?; + match self.period { + Some(TriggerPeriod::Before) => f.write_str("BEFORE ")?, + Some(TriggerPeriod::After) => f.write_str("AFTER ")?, + Some(TriggerPeriod::InsteadOf) => f.write_str("INSTEAD OF ")?, + None => {} + } + write!(f, "{} ON {}", self.event, self.table)?; + if self.for_each_row { + f.write_str(" FOR EACH ROW")?; + } + if let Some(when) = &self.when { + write!(f, " WHEN {when}")?; + } + f.write_str(" BEGIN ")?; + for statement in &self.statements { + write!(f, "{statement}; ")?; + } + f.write_str("END") + } +} + +fn write_or_action(f: &mut fmt::Formatter<'_>, or_action: Option<&str>) -> fmt::Result { + match or_action { + Some(action) => write!(f, "OR {action} "), + None => Ok(()), + } +} + +fn write_returning( + f: &mut fmt::Formatter<'_>, + returning: &[SelectItem<'_, Builtin>], +) -> fmt::Result { + write_list_clause(f, "RETURNING", returning) +} + +impl fmt::Display for OnConflict<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ON CONFLICT")?; + if !self.columns.is_empty() { + write!(f, "({})", comma(&self.columns))?; + } + if let Some(predicate) = &self.predicate { + write!(f, " WHERE {predicate}")?; + } + match &self.action { + OnConflictAction::DoNothing => f.write_str(" DO NOTHING"), + OnConflictAction::DoUpdate { + assignments, + selection, + } => { + write!(f, " DO UPDATE SET {}", comma(assignments))?; + if let Some(selection) = selection { + write!(f, " WHERE {selection}")?; + } + Ok(()) + } + } + } +} + +impl fmt::Display for SqliteInsert<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("INSERT ")?; + write_or_action(f, self.or_action.as_deref())?; + write!(f, "INTO {}", self.table)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + match &self.source { + None => f.write_str(" DEFAULT VALUES")?, + Some(source) => { + crate::display::write_insert_source(f, source, !self.columns.is_empty())?; + } + } + if let Some(on_conflict) = &self.on_conflict { + write!(f, " {on_conflict}")?; + } + write_returning(f, &self.returning) + } +} + +impl fmt::Display for SqliteUpdate<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("UPDATE ")?; + write_or_action(f, self.or_action.as_deref())?; + self.table.fmt(f)?; + write_list_clause(f, "SET", &self.assignments)?; + write_list_clause(f, "FROM", &self.from)?; + write_where_clause(f, &self.selection)?; + write_returning(f, &self.returning)?; + if let Some(limit) = &self.limit { + SpaceOrNewline.fmt(f)?; + write!(f, "LIMIT {limit}")?; + } + Ok(()) + } +} + +impl fmt::Display for SqliteDelete<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("DELETE FROM")?; + SpaceOrNewline.fmt(f)?; + Indent(&self.table).fmt(f)?; + write_where_clause(f, &self.selection)?; + write_returning(f, &self.returning)?; + write_list_clause(f, "ORDER BY", &self.order_by)?; + if let Some(limit) = &self.limit { + write_indented_clause(f, "LIMIT", limit)?; + } + Ok(()) + } +} + +impl fmt::Display for SqliteStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Pragma { name, value } => { + write!(f, "PRAGMA {name}")?; + match value { + None => Ok(()), + Some((PragmaForm::Equals, value)) => write!(f, " = {value}"), + Some((PragmaForm::Call, value)) => write!(f, "({value})"), + } + } + Self::Attach { + database_keyword, + file, + schema, + } => { + let database = if *database_keyword { "DATABASE " } else { "" }; + write!(f, "ATTACH {database}{file} AS {schema}") + } + Self::Begin { + modifier, + transaction_keyword, + } => { + write!(f, "BEGIN {modifier}")?; + if *transaction_keyword { + f.write_str(" TRANSACTION")?; + } + Ok(()) + } + Self::CreateTable(table) => table.fmt(f), + Self::CreateVirtualTable(table) => table.fmt(f), + Self::CreateTrigger(trigger) => trigger.fmt(f), + Self::Insert(insert) => insert.fmt(f), + Self::Update(update) => update.fmt(f), + Self::Delete(delete) => delete.fmt(f), + } + } +} diff --git a/sqlparser_v2/src/dialect/teradata.rs b/sqlparser_v2/src/dialect/teradata.rs new file mode 100644 index 0000000000..4ea238144d --- /dev/null +++ b/sqlparser_v2/src/dialect/teradata.rs @@ -0,0 +1,735 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Teradata. + +use std::borrow::Cow; +use std::fmt; + +use crate::PResult; +use crate::ast::{ + CreateFlags, CreateTable, Expr, ExprKind, Ident, NullTreatment, ObjectName, ObjectType, + Quantifier, SelectInto, Statement, StatementKind, StringLiteral, TableFactor, TableWithJoins, +}; +use crate::dialect::builtin::{BuiltinExpr, BuiltinSelect, BuiltinStatement}; +use crate::dialect::snowflake; +use crate::dialect::{Builtin, Dialect}; +use crate::display::{comma, write_columns, write_if_not_exists}; +use crate::grammar; +use crate::lexer::{LexResult, Lexeme, TokenKind}; +use crate::parser::{Parser, SetOperatorRule}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Teradata; + +/// Statements only Teradata has. +#[derive(Debug, Clone, PartialEq)] +pub enum TeradataStatement<'a> { + CreateTable(Box>), + Execute(Box>), +} + +/// Expressions only Teradata has. +#[derive(Debug, Clone, PartialEq)] +pub enum TeradataExpr<'a> { + /// `'a' 'b'`, which is the single string `'ab'`. + AdjacentStrings(Vec>), +} + +impl TeradataExpr<'_> { + /// The value of the joined strings. + pub fn value(&self) -> String { + match self { + Self::AdjacentStrings(parts) => parts.iter().map(|part| part.value()).collect(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TeradataSetKind { + Set, + Multiset, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TeradataOnCommit { + DeleteRows, + PreserveRows, +} + +/// `WITH [NO] DATA [AND [NO] STATISTICS]` +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TeradataWithData { + pub data: bool, + pub statistics: Option, +} + +/// `CREATE TABLE` with clauses only Teradata has. +#[derive(Debug, Clone, PartialEq)] +pub struct TeradataCreateTable<'a> { + pub table: CreateTable<'a, Builtin>, + pub set_kind: Option, + pub global: bool, + pub volatile: bool, + /// `, FALLBACK` is true and `, NO FALLBACK` is false. + pub fallback: Option, + pub on_commit: Option, + /// True if `ON COMMIT` was written after the query. + pub on_commit_last: bool, + pub with_data: Option, +} + +/// One `expr [AS alias]` of `EXECUTE ... USING`. +#[derive(Debug, Clone, PartialEq)] +pub struct TeradataUsing<'a> { + pub expr: Expr<'a, Builtin>, + pub alias: Option>, +} + +/// `EXECUTE [IMMEDIATE] ...` +#[derive(Debug, Clone, PartialEq)] +pub struct TeradataExecute<'a> { + pub immediate: bool, + pub name: Option>, + pub parameters: Vec>, + pub parenthesized: bool, + pub into: Vec>, + pub using: Vec>, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum TeradataTopQuantity<'a> { + Number(Cow<'a, str>), + Expr(Expr<'a, Builtin>), +} + +/// `TOP` beyond a plain number: `TOP (expr)`, `PERCENT` and `WITH TIES`. +#[derive(Debug, Clone, PartialEq)] +pub struct TeradataTop<'a> { + pub quantity: TeradataTopQuantity<'a>, + pub percent: bool, + pub with_ties: bool, +} + +fn teradata(statement: TeradataStatement<'_>) -> Statement<'_, Builtin> { + StatementKind::Ext(BuiltinStatement::Teradata(statement)).into() +} + +/// The length of the identifier character at the start of `rest`, or `None` +/// if there is none. +#[inline] +fn name_char_len(rest: &str) -> Option { + let byte = *rest.as_bytes().first()?; + if byte.is_ascii() { + let is_part = byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'#' | b'$'); + return is_part.then_some(1); + } + let ch = rest.chars().next()?; + ch.is_alphanumeric().then(|| ch.len_utf8()) +} + +#[inline] +fn name_len(rest: &str) -> usize { + let mut len = 0; + while let Some(part) = name_char_len(&rest[len..]) { + len += part; + } + len +} + +/// Lexes names holding `#`, `$` or letters beyond ASCII. Anything else is left +/// to the core lexer. +#[inline] +pub fn lex_token(rest: &str) -> Option { + let bytes = rest.as_bytes(); + let word = |len| { + Some(Ok(Lexeme { + kind: TokenKind::Word, + len, + })) + }; + match bytes[0] { + b'$' => word(name_len(rest)), + // `#-`, `#>` and a lone `#` are operators. + b'#' => match bytes.get(1) { + None | Some(b' ' | b'-' | b'>') => None, + Some(_) if name_char_len(&rest[1..]).is_none() => None, + Some(_) => word(name_len(rest)), + }, + first if first.is_ascii_alphabetic() || first == b'_' => { + let len = name_len(rest); + let plain = bytes[..len] + .iter() + .all(|b| b.is_ascii_alphanumeric() || *b == b'_'); + // A non-ASCII byte here is not part of the name, but the core + // lexer would take it as part of one. + if plain && bytes.get(len).is_none_or(u8::is_ascii) { + None + } else { + word(len) + } + } + first if !first.is_ascii() => { + if rest.chars().next().is_some_and(char::is_alphabetic) { + word(name_len(rest)) + } else { + Some(Err("unexpected character")) + } + } + _ => None, + } +} + +/// True if the words after `CREATE` lead to `TABLE`. +fn at_create_table<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let mut n = 1; + if p.peek_nth(n).is_word("OR") && p.peek_nth(n + 1).is_word("REPLACE") { + n += 2; + } + if p.peek_nth(n).is_word("SET") || p.peek_nth(n).is_word("MULTISET") { + n += 1; + } + if p.peek_nth(n).is_word("GLOBAL") { + n += 1; + } + if p.peek_nth(n).is_word("TEMPORARY") || p.peek_nth(n).is_word("TEMP") { + n += 1; + } + if p.peek_nth(n).is_word("VOLATILE") { + n += 1; + } + p.peek_nth(n).is_word("TABLE") +} + +/// Parses `, FALLBACK` or `, NO FALLBACK` after the table's name. +fn parse_fallback<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.eat_op(",") { + return Ok(None); + } + if p.eat_keyword("FALLBACK") { + return Ok(Some(true)); + } + p.expect_keyword("NO")?; + p.expect_keyword("FALLBACK")?; + Ok(Some(false)) +} + +fn parse_on_commit<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !(p.at_keyword("ON") && p.peek_nth(1).is_word("COMMIT")) { + return Ok(None); + } + p.advance(); + p.advance(); + let action = if p.eat_keyword("DELETE") { + TeradataOnCommit::DeleteRows + } else { + p.expect_keyword("PRESERVE")?; + TeradataOnCommit::PreserveRows + }; + p.expect_keyword("ROWS")?; + Ok(Some(action)) +} + +fn parse_with_data<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.at_keyword("WITH") { + return Ok(None); + } + let data = if p.peek_nth(1).is_word("DATA") { + true + } else if p.peek_nth(1).is_word("NO") && p.peek_nth(2).is_word("DATA") { + false + } else { + return Ok(None); + }; + p.advance(); + if !data { + p.advance(); + } + p.advance(); + + let statistics = if p.eat_keyword("AND") { + let with_statistics = !p.eat_keyword("NO"); + p.expect_keyword("STATISTICS")?; + Some(with_statistics) + } else { + None + }; + Ok(Some(TeradataWithData { data, statistics })) +} + +/// Parses `CREATE TABLE` with Teradata's clauses. A table that uses none of +/// them is a core node. +pub fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = grammar::parse_or_replace(p)?; + let set_kind = if p.eat_keyword("SET") { + Some(TeradataSetKind::Set) + } else if p.eat_keyword("MULTISET") { + Some(TeradataSetKind::Multiset) + } else { + None + }; + let global = p.eat_keyword("GLOBAL"); + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + let volatile = p.eat_keyword("VOLATILE"); + p.expect_keyword("TABLE")?; + + let if_not_exists = grammar::parse_if_not_exists(p)?; + let name = grammar::parse_object_name(p)?; + let fallback = parse_fallback(p)?; + let (columns, constraints) = if p.at_op("(") { + grammar::parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + let mut on_commit = parse_on_commit(p)?; + + let query = if p.eat_keyword("AS") || p.at_keyword("SELECT") { + Some(Box::new(D::parse_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() { + return Err(p.expected("column definitions or AS")); + } + let with_data = if query.is_some() { + parse_with_data(p)? + } else { + None + }; + // The form Teradata documents puts this last, after `WITH DATA`. + let mut on_commit_last = false; + if on_commit.is_none() && with_data.is_some() { + on_commit = parse_on_commit(p)?; + on_commit_last = on_commit.is_some(); + } + + let table = CreateTable { + or_replace, + temporary, + name, + if_not_exists, + columns, + constraints, + query, + }; + let is_core = set_kind.is_none() + && !global + && !volatile + && fallback.is_none() + && on_commit.is_none() + && with_data.is_none(); + if is_core { + return Ok(StatementKind::CreateTable(Box::new(table)).into()); + } + Ok(teradata(TeradataStatement::CreateTable(Box::new( + TeradataCreateTable { + table, + set_kind, + global, + volatile, + fallback, + on_commit, + on_commit_last, + with_data, + }, + )))) +} + +pub fn parse_create<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if at_create_table(p) { + return parse_create_table(p); + } + grammar::parse_create(p) +} + +fn parse_using<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let expr = p.parse_expr()?; + let alias = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + Ok(TeradataUsing { expr, alias }) +} + +fn at_execute_end<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let token = p.peek(); + token.kind == TokenKind::Eof || token.is_op(";") || token.is_word("USING") +} + +/// Parses `EXECUTE` or `EXEC`, which renders as `EXECUTE`. +pub fn parse_execute<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.advance(); + let immediate = p.eat_keyword("IMMEDIATE"); + let name = if immediate { + None + } else { + Some(grammar::parse_object_name(p)?) + }; + let parenthesized = name.is_some() && p.eat_op("("); + let parameters = if parenthesized { + let parameters = if p.at_op(")") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op(")")?; + parameters + } else if at_execute_end(p) { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + let into = if p.eat_keyword("INTO") { + p.parse_comma_separated(Parser::parse_ident)? + } else { + Vec::new() + }; + let using = if p.eat_keyword("USING") { + p.parse_comma_separated(parse_using)? + } else { + Vec::new() + }; + Ok(TeradataExecute { + immediate, + name, + parameters, + parenthesized, + into, + using, + }) +} + +pub fn parse_statement<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("COMMENT") { + return grammar::parse_comment_on(p).map(|c| StatementKind::Comment(Box::new(c)).into()); + } + if p.at_keyword("EXECUTE") || p.at_keyword("EXEC") { + let execute = parse_execute(p)?; + return Ok(teradata(TeradataStatement::Execute(Box::new(execute)))); + } + grammar::parse_statement(p) +} + +/// Parses `TOP` after `SELECT`, which comes before any `DISTINCT` or `ALL`. +pub fn parse_select_modifiers<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.eat_keyword("TOP") { + return Ok(BuiltinSelect::default()); + } + let quantity = if p.eat_op("(") { + let quantity = p.parse_expr()?; + p.expect_op(")")?; + TeradataTopQuantity::Expr(quantity) + } else { + let token = p.peek(); + if token.kind != TokenKind::Number || !token.text.bytes().all(|b| b.is_ascii_digit()) { + return Err(p.expected("an integer after TOP")); + } + p.advance(); + TeradataTopQuantity::Number(token.text.into()) + }; + let percent = p.eat_keyword("PERCENT"); + let with_ties = p.at_keyword("WITH") && p.peek_nth(1).is_word("TIES"); + if with_ties { + p.advance(); + p.advance(); + } + Ok(match quantity { + TeradataTopQuantity::Number(number) if !percent && !with_ties => BuiltinSelect { + top: Some(number), + ..BuiltinSelect::default() + }, + quantity => BuiltinSelect { + teradata_top: Some(Box::new(TeradataTop { + quantity, + percent, + with_ties, + })), + ..BuiltinSelect::default() + }, + }) +} + +/// Reads `TRUE` and `FALSE` as names, and joins adjacent strings. +pub fn parse_prefix<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("TRUE") || p.at_keyword("FALSE") { + return grammar::parse_name_expr(p); + } + if p.peek().kind == TokenKind::String && p.peek_nth(1).kind == TokenKind::String { + let mut parts = Vec::with_capacity(2); + while p.peek().kind == TokenKind::String { + parts.push(D::string_literal(p.advance())); + } + return Ok( + ExprKind::Ext(BuiltinExpr::Teradata(TeradataExpr::AdjacentStrings(parts))).into(), + ); + } + grammar::parse_prefix(p) +} + +impl Dialect for Teradata { + type Ext = Builtin; + + fn parse_create_extension<'a>( + p: &mut Parser<'a, Self>, + flags: CreateFlags, + ) -> PResult>> { + grammar::parse_create_role(p, flags, false) + } + + fn parse_qualify<'a>(p: &mut Parser<'a, Self>) -> PResult>> { + snowflake::parse_qualify(p) + } + + fn parse_like_quantifier<'a>(p: &mut Parser<'a, Self>) -> PResult> { + Ok(grammar::parse_like_any(p)) + } + + fn parse_update_from_before_set<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>> { + grammar::parse_optional_update_from(p) + } + + fn parse_select_into<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult>>> { + grammar::parse_select_into_variables(p) + } + + fn parse_drop_object_type<'a>(p: &mut Parser<'a, Self>) -> Option> { + grammar::eat_drop_object_type(p, &["TYPE"]) + } + + fn parse_group_by_item<'a>(p: &mut Parser<'a, Self>) -> PResult> { + grammar::parse_grouping_item_or_empty_set(p) + } + + fn set_operator_rule<'a>(p: &Parser<'a, Self>) -> Option { + grammar::set_operator_rule_with_minus(p) + } + + fn parse_insert_into<'a>(p: &mut Parser<'a, Self>) -> PResult { + Ok(p.eat_keyword("INTO")) + } + + #[inline] + fn is_reserved_for_alias(word: &str) -> bool { + word.eq_ignore_ascii_case("MINUS") + || word.eq_ignore_ascii_case("QUALIFY") + || grammar::is_reserved_for_alias(word) + } + + fn parse_table_factor<'a>(p: &mut Parser<'a, Self>) -> PResult> { + if grammar::at_xml_table(p) { + return grammar::parse_xml_table(p, false); + } + grammar::parse_table_factor(p) + } + + #[inline] + fn lex_token(rest: &str) -> Option { + lex_token(rest) + } + + #[inline] + fn is_reserved(word: &str) -> bool { + !word.eq_ignore_ascii_case("TRUE") + && !word.eq_ignore_ascii_case("FALSE") + && grammar::is_reserved(word) + } + + fn parse_statement<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_statement(p) + } + + fn parse_create<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_create(p) + } + + fn parse_select_modifiers<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_select_modifiers(p) + } + + fn parse_prefix<'a>(p: &mut Parser<'a, Self>) -> PResult> { + parse_prefix(p) + } + + fn parse_function_arg_null_treatment<'a>( + p: &mut Parser<'a, Self>, + ) -> PResult> { + Ok(grammar::parse_null_treatment(p)) + } +} + +impl fmt::Display for TeradataStatement<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CreateTable(create) => create.fmt(f), + Self::Execute(execute) => execute.fmt(f), + } + } +} + +impl fmt::Display for TeradataExpr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AdjacentStrings(parts) => { + f.write_str("'")?; + for part in parts { + f.write_str(&part.text)?; + } + f.write_str("'") + } + } + } +} + +impl fmt::Display for TeradataOnCommit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::DeleteRows => "ON COMMIT DELETE ROWS", + Self::PreserveRows => "ON COMMIT PRESERVE ROWS", + }) + } +} + +impl fmt::Display for TeradataWithData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(if self.data { + "WITH DATA" + } else { + "WITH NO DATA" + })?; + match self.statistics { + Some(true) => f.write_str(" AND STATISTICS"), + Some(false) => f.write_str(" AND NO STATISTICS"), + None => Ok(()), + } + } +} + +impl fmt::Display for TeradataCreateTable<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let table = &self.table; + f.write_str("CREATE ")?; + if table.or_replace { + f.write_str("OR REPLACE ")?; + } + match self.set_kind { + Some(TeradataSetKind::Set) => f.write_str("SET ")?, + Some(TeradataSetKind::Multiset) => f.write_str("MULTISET ")?, + None => {} + } + if self.global { + f.write_str("GLOBAL ")?; + } + if table.temporary { + f.write_str("TEMPORARY ")?; + } + if self.volatile { + f.write_str("VOLATILE ")?; + } + f.write_str("TABLE ")?; + write_if_not_exists(f, table.if_not_exists)?; + table.name.fmt(f)?; + match self.fallback { + Some(true) => f.write_str(", FALLBACK")?, + Some(false) => f.write_str(", NO FALLBACK")?, + None => {} + } + if !table.columns.is_empty() || !table.constraints.is_empty() { + write_columns(f, &table.columns, &table.constraints)?; + } + if let (Some(on_commit), false) = (self.on_commit, self.on_commit_last) { + write!(f, " {on_commit}")?; + } + if let Some(query) = &table.query { + write!(f, " AS {query}")?; + } + if let Some(with_data) = self.with_data { + write!(f, " {with_data}")?; + } + if let (Some(on_commit), true) = (self.on_commit, self.on_commit_last) { + write!(f, " {on_commit}")?; + } + Ok(()) + } +} + +impl fmt::Display for TeradataUsing<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.expr.fmt(f)?; + if let Some(alias) = &self.alias { + write!(f, " AS {alias}")?; + } + Ok(()) + } +} + +impl fmt::Display for TeradataExecute<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("EXECUTE")?; + if self.immediate { + f.write_str(" IMMEDIATE")?; + } + if let Some(name) = &self.name { + write!(f, " {name}")?; + } + if self.parenthesized { + write!(f, "({})", comma(&self.parameters))?; + } else if !self.parameters.is_empty() { + write!(f, " {}", comma(&self.parameters))?; + } + if !self.into.is_empty() { + write!(f, " INTO {}", comma(&self.into))?; + } + if !self.using.is_empty() { + write!(f, " USING {}", comma(&self.using))?; + } + Ok(()) + } +} + +impl fmt::Display for TeradataTop<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.quantity { + TeradataTopQuantity::Number(number) => write!(f, "TOP {number}")?, + TeradataTopQuantity::Expr(expr) => write!(f, "TOP ({expr})")?, + } + if self.percent { + f.write_str(" PERCENT")?; + } + if self.with_ties { + f.write_str(" WITH TIES")?; + } + Ok(()) + } +} diff --git a/sqlparser_v2/src/display.rs b/sqlparser_v2/src/display.rs new file mode 100644 index 0000000000..f14a4511f1 --- /dev/null +++ b/sqlparser_v2/src/display.rs @@ -0,0 +1,3599 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Renders the AST back to SQL. +//! +//! Parsing then rendering reproduces the source's identifiers, literals, +//! parentheses and clause forms. Keywords are upper-cased, whitespace is +//! normalized, and equivalent spellings such as `INNER JOIN` take one form. +//! +//! `{:#}` renders the same text over several lines, using [`SpaceOrNewline`], +//! [`NewLine`] and [`Indent`]. A node that renders a child with `write!` drops +//! the alternate flag, which keeps that child on one line. + +use crate::ast::ExprKind; +use crate::ast::SelectItemKind; +use crate::ast::StatementKind; +use std::borrow::Cow; +use std::cell::Cell; +use std::fmt::{Display, Formatter, Result}; + +use crate::ast::*; +use crate::dialect::AstExt; + +thread_local! { + /// How many levels of [`Indent`] enclose the node being rendered. + /// + /// A counter, rather than a writer per level as in the original crate, + /// keeps the cost of a write independent of depth. It also means only the + /// line breaks written here are indented, and never a newline in a string. + static INDENT_DEPTH: Cell = const { Cell::new(0) }; +} + +const INDENT: &str = " "; +const PADDING: &str = " "; + +/// Restores the indent depth, even if a nested `Display` panics. +struct IndentScope; + +impl IndentScope { + fn enter() -> Self { + INDENT_DEPTH.with(|depth| depth.set(depth.get() + 1)); + IndentScope + } +} + +impl Drop for IndentScope { + fn drop(&mut self) { + INDENT_DEPTH.with(|depth| depth.set(depth.get() - 1)); + } +} + +fn write_line_break(f: &mut Formatter<'_>) -> Result { + f.write_str("\n")?; + let mut remaining = INDENT_DEPTH.with(Cell::get) * INDENT.len(); + while remaining > 0 { + let chunk = remaining.min(PADDING.len()); + f.write_str(&PADDING[..chunk])?; + remaining -= chunk; + } + Ok(()) +} + +/// A line break in `{:#}`, and nothing in `{}`. +pub struct NewLine; + +impl Display for NewLine { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if f.alternate() { + write_line_break(f)?; + } + Ok(()) + } +} + +/// A line break in `{:#}`, and a space in `{}`. +pub struct SpaceOrNewline; + +impl Display for SpaceOrNewline { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if f.alternate() { + write_line_break(f) + } else { + f.write_str(" ") + } + } +} + +/// Renders a value one level further in with `{:#}`, and unchanged with `{}`. +pub struct Indent(pub T); + +impl Display for Indent { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if !f.alternate() { + return self.0.fmt(f); + } + f.write_str(INDENT)?; + let _scope = IndentScope::enter(); + self.0.fmt(f) + } +} + +/// Renders a value with `{}` even inside `{:#}`, because `write!` resets the flag. +struct OneLine<'s, T>(&'s T); + +impl Display for OneLine<'_, T> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.0.fmt(f) + } +} + +/// Renders `items` separated by commas, one per line with `{:#}`. +pub struct CommaLines<'s, T>(pub &'s [T]); + +impl Display for CommaLines<'_, T> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let mut items = self.0.iter(); + if let Some(first) = items.next() { + first.fmt(f)?; + } + for item in items { + f.write_str(",")?; + SpaceOrNewline.fmt(f)?; + item.fmt(f)?; + } + Ok(()) + } +} + +/// Renders a space or line break, then `items` one per line and indented. +pub fn indented_list(f: &mut Formatter<'_>, items: &[T]) -> Result { + SpaceOrNewline.fmt(f)?; + Indent(CommaLines(items)).fmt(f) +} + +/// Renders a clause whose keyword and content are on separate lines in `{:#}`. +pub fn write_indented_clause( + f: &mut Formatter<'_>, + keyword: &str, + content: T, +) -> Result { + SpaceOrNewline.fmt(f)?; + f.write_str(keyword)?; + SpaceOrNewline.fmt(f)?; + Indent(content).fmt(f) +} + +/// Renders `keyword` and `items` one per line, or nothing if `items` is empty. +pub fn write_list_clause(f: &mut Formatter<'_>, keyword: &str, items: &[T]) -> Result { + if items.is_empty() { + return Ok(()); + } + SpaceOrNewline.fmt(f)?; + f.write_str(keyword)?; + indented_list(f, items) +} + +/// Renders `items` joined by `separator`. +pub struct Separated<'s, T>(&'s [T], &'static str); + +impl Display for Separated<'_, T> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let mut items = self.0.iter(); + if let Some(first) = items.next() { + first.fmt(f)?; + } + for item in items { + f.write_str(self.1)?; + item.fmt(f)?; + } + Ok(()) + } +} + +pub fn comma(items: &[T]) -> Separated<'_, T> { + Separated(items, ", ") +} + +pub fn space(items: &[T]) -> Separated<'_, T> { + Separated(items, " ") +} + +/// Renders a clause prefixed by `keyword`, or nothing if `items` is empty. +fn write_list(f: &mut Formatter<'_>, keyword: &str, items: &[T]) -> Result { + if items.is_empty() { + return Ok(()); + } + write!(f, " {keyword} {}", comma(items)) +} + +fn write_where(f: &mut Formatter<'_>, selection: &Option>) -> Result { + match selection { + Some(selection) => write!(f, " WHERE {selection}"), + None => Ok(()), + } +} + +pub fn write_where_clause( + f: &mut Formatter<'_>, + selection: &Option>, +) -> Result { + match selection { + Some(selection) => write_indented_clause(f, "WHERE", selection), + None => Ok(()), + } +} + +impl Display for Ident<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self.quote { + Some('[') => write!(f, "[{}]", self.text), + Some(quote) => write!(f, "{quote}{}{quote}", self.text), + None => f.write_str(&self.text), + } + } +} + +impl Display for ObjectName<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + Separated(&self.parts, ".").fmt(f) + } +} + +impl Display for Literal<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + Literal::Number(text) => f.write_str(text), + Literal::HexString(digits) => write!(f, "X'{digits}'"), + Literal::DollarQuoted { tag, text } => write!(f, "${tag}${text}${tag}$"), + Literal::Null => f.write_str("NULL"), + Literal::Boolean(value) => write!(f, "{value}"), + Literal::String(string) => string.fmt(f), + } + } +} + +impl Display for StringLiteral<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if self.quote == '$' { + return write!(f, "$${}$$", self.text); + } + if self.national { + f.write_str("N")?; + } + match self.prefix { + StringPrefix::None => {} + StringPrefix::Byte => f.write_str("B")?, + StringPrefix::Raw => f.write_str("R")?, + StringPrefix::Escape => f.write_str("E")?, + StringPrefix::Unicode => f.write_str("U&")?, + StringPrefix::Bit => f.write_str("B")?, + } + let quote = self.quote; + if self.triple { + write!(f, "{quote}{quote}{quote}{}{quote}{quote}{quote}", self.text) + } else { + write!(f, "{quote}{}{quote}", self.text) + } + } +} + +impl Display for BinaryOp<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self { + BinaryOp::Or => "OR", + BinaryOp::And => "AND", + BinaryOp::Eq => "=", + BinaryOp::NotEq => "<>", + BinaryOp::Lt => "<", + BinaryOp::LtEq => "<=", + BinaryOp::Gt => ">", + BinaryOp::GtEq => ">=", + BinaryOp::Add => "+", + BinaryOp::Sub => "-", + BinaryOp::Mul => "*", + BinaryOp::Div => "/", + BinaryOp::Mod => "%", + BinaryOp::StringConcat => "||", + BinaryOp::BitOr => "|", + BinaryOp::BitAnd => "&", + BinaryOp::BitXor => "^", + BinaryOp::ShiftLeft => "<<", + BinaryOp::ShiftRight => ">>", + BinaryOp::Named(text) => text, + }) + } +} + +fn not(negated: bool) -> &'static str { + if negated { "NOT " } else { "" } +} + +impl Display for ExprKind<'_, X> { + /// Left-deep chains recurse here once per level, up to the tree height + /// limit. The arms that form those chains avoid `write!`, whose formatter + /// frames and temporaries would overflow the stack in a debug build. + /// + /// Only `CASE` and window specifications have a multi-line form. Anything + /// else renders its children on one line, so `{:#}` drops to `{}` here, at + /// the cost of one `write!` per chain rather than per level. + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if f.alternate() && !matches!(self, ExprKind::Case(_) | ExprKind::Function { .. }) { + return write!(f, "{}", OneLine(self)); + } + match self { + ExprKind::Binary { left, op, right } => { + (**left).fmt(f)?; + f.write_str(" ")?; + op.fmt(f)?; + f.write_str(" ")?; + (**right).fmt(f) + } + ExprKind::Cast { + expr, + ty, + style: CastStyle::DoubleColon, + } => { + (**expr).fmt(f)?; + f.write_str("::")?; + ty.fmt(f) + } + ExprKind::InList { + expr, + list, + negated, + } => { + (**expr).fmt(f)?; + write_in_list(f, list, *negated) + } + ExprKind::InSubquery { + expr, + subquery, + negated, + } => { + (**expr).fmt(f)?; + write_in_subquery(f, subquery, *negated) + } + ExprKind::Is { + expr, + test, + negated, + } => { + (**expr).fmt(f)?; + write_is(f, test, *negated) + } + ExprKind::Like { + expr, + pattern, + negated, + kind, + escape, + } => { + (**expr).fmt(f)?; + write_like(f, pattern, *negated, kind, escape.as_deref()) + } + ExprKind::Between { + expr, + low, + high, + negated, + } => { + (**expr).fmt(f)?; + write_between(f, low, high, *negated) + } + ExprKind::Ext(ext) => ext.fmt(f), + other => write_non_chain_expr(f, other), + } + } +} + +fn write_in_list(f: &mut Formatter<'_>, list: &[Expr<'_, X>], negated: bool) -> Result { + write!(f, " {}IN ({})", not(negated), comma(list)) +} + +fn write_in_subquery( + f: &mut Formatter<'_>, + subquery: &Query<'_, X>, + negated: bool, +) -> Result { + write!(f, " {}IN ({subquery})", not(negated)) +} + +/// Renders the expressions that cannot form long left-deep chains. +fn write_non_chain_expr(f: &mut Formatter<'_>, expr: &ExprKind<'_, X>) -> Result { + match expr { + ExprKind::Ident(ident) => ident.fmt(f), + ExprKind::Literal(literal) => literal.fmt(f), + ExprKind::Nested(expr) => write!(f, "({expr})"), + ExprKind::Unary { + op: UnaryOp::Not, + expr, + } => write!(f, "NOT {expr}"), + ExprKind::Unary { + op: UnaryOp::BangNot, + expr, + } => write!(f, "!{expr}"), + ExprKind::Unary { + op: UnaryOp::BitNot, + expr, + } => write!(f, "~ {expr}"), + ExprKind::Unary { + op: UnaryOp::Neg, + expr, + } => { + // `--a` would read as the start of a comment. + let is_negation = matches!( + &expr.kind, + ExprKind::Unary { + op: UnaryOp::Neg, + .. + } + ); + let separator = if is_negation { " " } else { "" }; + write!(f, "-{separator}{expr}") + } + ExprKind::Unary { + op: UnaryOp::Plus, + expr, + } => write!(f, "+{expr}"), + ExprKind::Cast { + expr, + ty, + style: CastStyle::TryFunction, + } => write!(f, "TRY_CAST({expr} AS {ty})"), + ExprKind::Cast { expr, ty, .. } if ty.is_unspecified() => write!(f, "CAST({expr} AS)"), + ExprKind::Cast { + expr, + ty, + style: CastStyle::SafeFunction, + } => write!(f, "SAFE_CAST({expr} AS {ty})"), + ExprKind::Cast { expr, ty, .. } => write!(f, "CAST({expr} AS {ty})"), + ExprKind::Placeholder(text) => f.write_str(text), + ExprKind::Interval(interval) => interval.fmt(f), + ExprKind::TypedString(typed) => { + write!(f, "{} {}", typed.ty, typed.value) + } + ExprKind::Special(special) => special.fmt(f), + ExprKind::Compound(name) => name.fmt(f), + ExprKind::Function { + name, + args, + options, + } => write_function(f, name, args, options.as_deref()), + ExprKind::Subquery(query) => write!(f, "({query})"), + ExprKind::Exists(query) => write!(f, "EXISTS ({query})"), + ExprKind::Case(case) => write_case(f, case), + ExprKind::Binary { .. } + | ExprKind::InList { .. } + | ExprKind::InSubquery { .. } + | ExprKind::Is { .. } + | ExprKind::Like { .. } + | ExprKind::Between { .. } + | ExprKind::Ext(_) => { + unreachable!("rendered by Expr::fmt") + } + } +} + +impl Display for FunctionArg<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + FunctionArg::Wildcard => f.write_str("*"), + FunctionArg::QualifiedWildcard(name) => write!(f, "{name}.*"), + FunctionArg::Expr(expr) => expr.fmt(f), + FunctionArg::Named { name, value } => write!(f, "{name} => {value}"), + FunctionArg::NamedWith { + name, + operator, + value, + } => write!(f, "{name} {operator} {value}"), + } + } +} + +impl Display for SelectItemKind<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + SelectItemKind::Wildcard => f.write_str("*"), + SelectItemKind::QualifiedWildcard(name) => write!(f, "{name}.*"), + SelectItemKind::WildcardWithOptions { qualifier, options } => { + if let Some(qualifier) = qualifier { + write!(f, "{qualifier}.")?; + } + write!(f, "*{options}") + } + SelectItemKind::Expr { expr, alias: None } => expr.fmt(f), + SelectItemKind::ExprWithAliases { expr, aliases } => { + write!(f, "{expr} AS ({})", comma(aliases)) + } + SelectItemKind::Expr { + expr, + alias: Some(alias), + } => { + expr.fmt(f)?; + f.write_str(" AS ")?; + alias.fmt(f) + } + } + } +} + +impl Display for WildcardOptions<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(ref pattern) = self.ilike { + write!(f, " ILIKE {}", pattern)?; + } + if !self.exclude.is_empty() { + if self.except_keyword { + write!(f, " EXCEPT ({})", comma(&self.exclude))?; + } else if self.exclude_parens { + write!(f, " EXCLUDE ({})", comma(&self.exclude))?; + } else { + write!(f, " EXCLUDE {}", comma(&self.exclude))?; + } + } + if !self.replace.is_empty() { + f.write_str(" REPLACE (")?; + for (i, (expr, name)) in self.replace.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{expr} AS {name}")?; + } + f.write_str(")")?; + } + if !self.rename.is_empty() { + f.write_str(if self.rename_parens { + " RENAME (" + } else { + " RENAME " + })?; + for (i, (from, to)) in self.rename.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{from} AS {to}")?; + } + if self.rename_parens { + f.write_str(")")?; + } + } + Ok(()) + } +} + +impl Display for TableFactor<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write_table_call(f, self) + } +} + +impl Display for TableRef<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match &self.factor { + TableFactor::Named(name) => name.fmt(f)?, + TableFactor::Derived(query) => write_derived(f, query)?, + TableFactor::Values(rows) => write_table_values(f, rows)?, + TableFactor::NestedJoin(table) => write!(f, "({table})")?, + TableFactor::Ext(factor) => factor.fmt(f)?, + factor @ (TableFactor::Function { .. } + | TableFactor::Lateral(_) + | TableFactor::Versioned { .. } + | TableFactor::TimeTravel(_) + | TableFactor::Sampled(_) + | TableFactor::XmlTable(_) + | TableFactor::Pivot(_) + | TableFactor::Unpivot(_) + | TableFactor::MatchRecognize(_)) => { + write_table_call(f, factor)?; + } + } + let Some(alias) = &self.alias else { + return Ok(()); + }; + f.write_str(if alias.explicit { " AS " } else { " " })?; + alias.name.fmt(f)?; + if !alias.columns.is_empty() { + f.write_str(" (")?; + for (i, column) in alias.columns.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + column.fmt(f)?; + if let Some(data_type) = alias.column_types.get(i) { + write!(f, " {data_type}")?; + } + } + f.write_str(")")?; + } + Ok(()) + } +} + +/// Renders a query in parentheses, on its own indented lines in `{:#}`. +fn write_derived(f: &mut Formatter<'_>, query: &Query<'_, X>) -> Result { + f.write_str("(")?; + NewLine.fmt(f)?; + Indent(query).fmt(f)?; + NewLine.fmt(f)?; + f.write_str(")") +} + +/// Renders the table factors that can follow `LATERAL`. +fn write_table_call(f: &mut Formatter<'_>, factor: &TableFactor<'_, X>) -> Result { + match factor { + TableFactor::Named(name) => name.fmt(f), + TableFactor::Derived(query) => write_derived(f, query), + TableFactor::Values(rows) => write_table_values(f, rows), + TableFactor::NestedJoin(table) => write!(f, "({table})"), + TableFactor::Ext(factor) => factor.fmt(f), + TableFactor::Function { + call, + with_ordinality, + } => { + call.fmt(f)?; + f.write_str(if *with_ordinality { + " WITH ORDINALITY" + } else { + "" + }) + } + TableFactor::Lateral(inner) => { + f.write_str("LATERAL ")?; + write_table_call(f, inner) + } + TableFactor::TimeTravel(travel) => { + write!(f, "{} {} AS OF {}", travel.name, travel.kind, travel.at) + } + TableFactor::Versioned { name, calls } => { + name.fmt(f)?; + for call in calls { + write!(f, " {call}")?; + } + Ok(()) + } + TableFactor::Sampled(sample) => sample.fmt(f), + TableFactor::XmlTable(table) => table.fmt(f), + TableFactor::Pivot(pivot) => pivot.fmt(f), + TableFactor::Unpivot(unpivot) => unpivot.fmt(f), + TableFactor::MatchRecognize(recognize) => recognize.fmt(f), + } +} + +impl Display for MatchRecognize<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} MATCH_RECOGNIZE(", self.table)?; + if !self.partition_by.is_empty() { + write!(f, "PARTITION BY {} ", comma(&self.partition_by))?; + } + if !self.order_by.is_empty() { + write!(f, "ORDER BY {} ", comma(&self.order_by))?; + } + if !self.measures.is_empty() { + f.write_str("MEASURES ")?; + for (i, (expr, alias)) in self.measures.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{expr} AS {alias}")?; + } + f.write_str(" ")?; + } + match self.rows_per_match { + Some(RowsPerMatch::OneRow) => f.write_str("ONE ROW PER MATCH ")?, + Some(RowsPerMatch::AllRows(empty)) => { + f.write_str("ALL ROWS PER MATCH ")?; + f.write_str(match empty { + Some(EmptyMatches::Show) => "SHOW EMPTY MATCHES ", + Some(EmptyMatches::Omit) => "OMIT EMPTY MATCHES ", + Some(EmptyMatches::WithUnmatchedRows) => "WITH UNMATCHED ROWS ", + None => "", + })?; + } + None => {} + } + match self.after_match_skip { + Some(AfterMatchSkip::PastLastRow) => f.write_str("AFTER MATCH SKIP PAST LAST ROW ")?, + Some(AfterMatchSkip::ToNextRow) => f.write_str("AFTER MATCH SKIP TO NEXT ROW ")?, + Some(AfterMatchSkip::ToFirst(ref symbol)) => { + write!(f, "AFTER MATCH SKIP TO FIRST {symbol} ")?; + } + Some(AfterMatchSkip::ToLast(ref symbol)) => { + write!(f, "AFTER MATCH SKIP TO LAST {symbol} ")?; + } + None => {} + } + write!(f, "PATTERN ({}) DEFINE ", self.pattern)?; + for (i, (symbol, definition)) in self.symbols.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{symbol} AS {definition}")?; + } + f.write_str(")") + } +} + +impl Display for MatchPattern<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + MatchPattern::Symbol(symbol) => symbol.fmt(f), + MatchPattern::Start => f.write_str("^"), + MatchPattern::End => f.write_str("$"), + MatchPattern::Exclude(symbol) => write!(f, "{{- {symbol} -}}"), + MatchPattern::Permute(symbols) => write!(f, "PERMUTE({})", comma(symbols)), + MatchPattern::Concat(patterns) => Separated(patterns, " ").fmt(f), + MatchPattern::Group(pattern) => write!(f, "( {pattern} )"), + MatchPattern::Alternation(patterns) => Separated(patterns, " | ").fmt(f), + MatchPattern::Repetition { + pattern, + quantifier, + reluctant, + } => { + pattern.fmt(f)?; + match quantifier { + PatternQuantifier::ZeroOrMore => f.write_str("*")?, + PatternQuantifier::OneOrMore => f.write_str("+")?, + PatternQuantifier::AtMostOne => f.write_str("?")?, + PatternQuantifier::Exactly(n) => write!(f, "{{{n}}}")?, + PatternQuantifier::AtLeast(n) => write!(f, "{{{n},}}")?, + PatternQuantifier::AtMost(m) => write!(f, "{{,{m}}}")?, + PatternQuantifier::Range(n, m) => write!(f, "{{{n},{m}}}")?, + } + f.write_str(if *reluctant { "?" } else { "" }) + } + } + } +} + +impl Display for ExprWithAlias<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match &self.alias { + Some(alias) => write!(f, "{} AS {alias}", self.expr), + None => self.expr.fmt(f), + } + } +} + +impl Display for TableSample<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} {}", self.table, self.sample) + } +} + +impl Display for SampleClause<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let keyword = if self.long_form { + "TABLESAMPLE" + } else { + "SAMPLE" + }; + write!(f, "{keyword} ")?; + if let Some(ref method) = self.method { + write!(f, "{method} ")?; + } + if self.parenthesized { + f.write_str("(")?; + } + self.amount.fmt(f)?; + if self.parenthesized { + f.write_str(")")?; + } + if let Some(ref seed) = self.seed { + let keyword = if seed.repeatable { + "REPEATABLE" + } else { + "SEED" + }; + write!(f, " {keyword} ({})", seed.value)?; + } + if let Some(offset) = &self.offset { + write!(f, " OFFSET {offset}")?; + } + Ok(()) + } +} + +impl Display for SampleAmount<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + SampleAmount::Quantity { value, unit } => { + value.fmt(f)?; + f.write_str(match unit { + Some(SampleUnit::Rows) => " ROWS", + Some(SampleUnit::Percent) => " PERCENT", + None => "", + }) + } + SampleAmount::Bucket { bucket, total, on } => { + write!(f, "BUCKET {bucket} OUT OF {total}")?; + match on { + Some(on) => write!(f, " ON {on}"), + None => Ok(()), + } + } + } + } +} + +impl Display for Pivot<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} {}", self.table, self.clause) + } +} + +impl Display for PivotClause<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "PIVOT({} FOR ", comma(&self.aggregates))?; + match self.columns.as_slice() { + [only] => only.fmt(f)?, + columns => write!(f, "({})", comma(columns))?, + } + f.write_str(" IN (")?; + match &self.source { + PivotSource::List(values) => comma(values).fmt(f)?, + PivotSource::Any(order_by) => { + f.write_str("ANY")?; + write_list(f, "ORDER BY", order_by)?; + } + PivotSource::Query(query) => query.fmt(f)?, + } + f.write_str(")")?; + if let Some(default) = &self.default_on_null { + write!(f, " DEFAULT ON NULL ({default})")?; + } + f.write_str(")") + } +} + +impl Display for Unpivot<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} {}", self.table, self.clause) + } +} + +impl Display for UnpivotClause<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("UNPIVOT")?; + f.write_str(match self.include_nulls { + Some(true) => " INCLUDE NULLS ", + Some(false) => " EXCLUDE NULLS ", + None => "", + })?; + write!( + f, + "({} FOR {} IN ({}))", + self.value, + self.name, + comma(&self.columns) + ) + } +} + +impl Display for Join<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if matches!(self.constraint, JoinConstraint::Natural) { + f.write_str("NATURAL ")?; + } + f.write_str(match (&self.kind, self.spelled_out) { + (JoinKind::Custom(keywords), _) => keywords, + (JoinKind::Inner, false) => "JOIN", + (JoinKind::Inner, true) => "INNER JOIN", + (JoinKind::Left, false) => "LEFT JOIN", + (JoinKind::Left, true) => "LEFT OUTER JOIN", + (JoinKind::Right, false) => "RIGHT JOIN", + (JoinKind::Right, true) => "RIGHT OUTER JOIN", + (JoinKind::Full, _) => "FULL JOIN", + (JoinKind::Cross, _) => "CROSS JOIN", + (JoinKind::AsOf, _) => "ASOF JOIN", + (JoinKind::Semi, _) => "SEMI JOIN", + (JoinKind::LeftSemi, _) => "LEFT SEMI JOIN", + (JoinKind::Anti, _) => "ANTI JOIN", + (JoinKind::LeftAnti, _) => "LEFT ANTI JOIN", + (JoinKind::RightSemi, _) => "RIGHT SEMI JOIN", + (JoinKind::RightAnti, _) => "RIGHT ANTI JOIN", + })?; + write!(f, " {}", self.table)?; + match &self.constraint { + JoinConstraint::Ext(constraint) => write!(f, " {constraint}"), + JoinConstraint::None | JoinConstraint::Natural => Ok(()), + JoinConstraint::On(expr) => write!(f, " ON {expr}"), + JoinConstraint::Using(columns) => write!(f, " USING({})", comma(columns)), + JoinConstraint::AsOf { + condition, + constraint, + } => { + write!(f, " MATCH_CONDITION ({condition})")?; + match constraint.as_ref() { + JoinConstraint::On(on) => write!(f, " ON {on}"), + JoinConstraint::Using(columns) => write!(f, " USING({})", comma(columns)), + _ => Ok(()), + } + } + } + } +} + +impl Display for TableWithJoins<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.relation.fmt(f)?; + for join in &self.joins { + SpaceOrNewline.fmt(f)?; + join.fmt(f)?; + } + Ok(()) + } +} + +impl Display for Cte<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let materialized = match self.materialized { + Some(true) => "MATERIALIZED ", + Some(false) => "NOT MATERIALIZED ", + None => "", + }; + self.name.fmt(f)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + write!(f, " AS {materialized}(")?; + NewLine.fmt(f)?; + Indent(&self.query).fmt(f)?; + NewLine.fmt(f)?; + f.write_str(")") + } +} + +impl Display for ListAggOnOverflow<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("ON OVERFLOW ")?; + match self { + ListAggOnOverflow::Error => f.write_str("ERROR"), + ListAggOnOverflow::Truncate { filler, with_count } => { + f.write_str("TRUNCATE ")?; + if let Some(filler) = filler { + write!(f, "{filler} ")?; + } + f.write_str(if *with_count { + "WITH COUNT" + } else { + "WITHOUT COUNT" + }) + } + } + } +} + +impl Display for SelectInto<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("INTO ")?; + if let Some(ref modifier) = self.modifier { + write!(f, "{modifier} ")?; + } + if self.table_keyword { + f.write_str("TABLE ")?; + } + write!(f, "{}", comma(&self.targets)) + } +} + +impl Display for XmlTable<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("XMLTABLE(")?; + if !self.namespaces.is_empty() { + write!(f, "XMLNAMESPACES({}), ", comma(&self.namespaces))?; + } + write!(f, "{}", self.row_expression)?; + if !self.passing.is_empty() { + write!(f, " PASSING {}", comma(&self.passing))?; + } + write!(f, " COLUMNS {})", comma(&self.columns)) + } +} + +impl Display for XmlNamespace<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} AS {}", self.uri, self.name) + } +} + +impl Display for XmlPassingArgument<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if self.by_value { + f.write_str("BY VALUE ")?; + } + write!(f, "{}", self.expr)?; + if let Some(alias) = &self.alias { + write!(f, " AS {alias}")?; + } + Ok(()) + } +} + +impl Display for XmlTableColumn<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.name.fmt(f)?; + match &self.kind { + XmlColumnKind::ForOrdinality => f.write_str(" FOR ORDINALITY"), + XmlColumnKind::Data { + data_type, + path, + default, + not_null, + } => { + write!(f, " {data_type}")?; + if let Some(path) = path { + write!(f, " PATH {path}")?; + } + if let Some(default) = default { + write!(f, " DEFAULT {default}")?; + } + if *not_null { + f.write_str(" NOT NULL")?; + } + Ok(()) + } + } + } +} + +impl Display for OrderByItem<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.expr.fmt(f)?; + if let Some(using) = &self.using { + f.write_str(" USING ")?; + write_order_operator(f, using)?; + } + write_order_modifiers(f, self)?; + self.ext.fmt(f) + } +} + +fn write_order_operator(f: &mut Formatter<'_>, name: &OperatorName<'_>) -> Result { + if name.schema.is_empty() && !name.operator.contains(|c: char| c.is_alphabetic()) { + return f.write_str(&name.operator); + } + f.write_str("OPERATOR(")?; + for part in &name.schema { + write!(f, "{part}.")?; + } + write!(f, "{})", name.operator) +} + +fn write_order_modifiers(f: &mut Formatter<'_>, item: &OrderByItem<'_, X>) -> Result { + match item.asc { + Some(true) => f.write_str(" ASC")?, + Some(false) => f.write_str(" DESC")?, + None => {} + } + match item.nulls_first { + Some(true) => f.write_str(" NULLS FIRST"), + Some(false) => f.write_str(" NULLS LAST"), + None => Ok(()), + } +} + +impl Display for Limit<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match (&self.count, &self.offset) { + (Some(count), Some(offset)) if self.offset_comma => { + return write!(f, "LIMIT {offset}, {count}"); + } + (Some(count), Some(_)) => write!(f, "LIMIT {count} ")?, + (Some(count), None) => write!(f, "LIMIT {count}")?, + (None, Some(_)) if self.all => f.write_str("LIMIT ALL ")?, + (None, None) if self.all => f.write_str("LIMIT ALL")?, + (None, _) => {} + } + if let Some(offset) = &self.offset { + write!(f, "OFFSET {offset}")?; + f.write_str(match self.offset_rows { + OffsetRows::None => "", + OffsetRows::Row => " ROW", + OffsetRows::Rows => " ROWS", + })?; + } + write_list(f, "BY", &self.by) + } +} + +impl Display for Fetch<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("FETCH FIRST ")?; + if let Some(quantity) = &self.quantity { + write!(f, "{quantity} ")?; + if self.percent { + f.write_str("PERCENT ")?; + } + } + f.write_str(if self.with_ties { + "ROWS WITH TIES" + } else { + "ROWS ONLY" + }) + } +} + +impl Display for LockClause<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self.lock_type { + LockType::Update => "FOR UPDATE", + LockType::Share => "FOR SHARE", + })?; + if let Some(of) = &self.of { + write!(f, " OF {of}")?; + } + match self.nonblock { + Some(NonBlock::Nowait) => f.write_str(" NOWAIT"), + Some(NonBlock::SkipLocked) => f.write_str(" SKIP LOCKED"), + None => Ok(()), + } + } +} + +/// Renders a date or time unit in upper case, or as written if it is quoted +/// or not a known unit. +fn write_unit(f: &mut Formatter<'_>, unit: &str) -> Result { + if unit.starts_with('\'') || !crate::grammar::is_date_time_field(unit) { + f.write_str(unit) + } else { + f.write_str(&unit.to_ascii_uppercase()) + } +} + +impl Display for Interval<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "INTERVAL {}", self.value)?; + if let Some(ref field) = self.leading_field { + f.write_str(" ")?; + write_unit(f, field)?; + } + let is_second = self + .leading_field + .as_ref() + .is_some_and(|field| field.eq_ignore_ascii_case("SECOND")); + if let (true, Some(leading), Some(fractional)) = ( + is_second, + self.leading_precision.clone(), + self.fractional_seconds_precision.clone(), + ) { + return write!(f, " ({leading}, {fractional})"); + } + if let Some(ref precision) = self.leading_precision { + write!(f, " ({precision})")?; + } + if let Some(ref field) = self.last_field { + f.write_str(" TO ")?; + write_unit(f, field)?; + } + if let Some(ref precision) = self.fractional_seconds_precision { + write!(f, " ({precision})")?; + } + Ok(()) + } +} + +impl Display for SpecialExpr<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + SpecialExpr::Quantified { + left, + op, + quantifier, + right, + } => { + left.fmt(f)?; + f.write_str(" ")?; + op.fmt(f)?; + f.write_str(match quantifier { + Quantifier::Any => " ANY", + Quantifier::Some => " SOME", + Quantifier::All => " ALL", + })?; + // A subquery renders its own parentheses. + if matches!(right.kind, ExprKind::Subquery(_)) { + right.fmt(f) + } else { + f.write_str("(")?; + right.fmt(f)?; + f.write_str(")") + } + } + SpecialExpr::FieldAccess { expr, field } => { + expr.fmt(f)?; + f.write_str(".")?; + field.fmt(f) + } + SpecialExpr::AtTimeZone { expr, zone } => { + expr.fmt(f)?; + f.write_str(" AT TIME ZONE ")?; + zone.fmt(f) + } + SpecialExpr::Collate { expr, collation } => { + expr.fmt(f)?; + f.write_str(" COLLATE ")?; + collation.fmt(f) + } + SpecialExpr::Subscript { expr, index } => { + expr.fmt(f)?; + f.write_str("[")?; + index.fmt(f)?; + f.write_str("]") + } + SpecialExpr::Slice { + expr, + lower, + upper, + step, + } => { + expr.fmt(f)?; + f.write_str("[")?; + if let Some(lower) = lower { + lower.fmt(f)?; + } + f.write_str(":")?; + if let Some(upper) = upper { + upper.fmt(f)?; + } + if let Some(step) = step { + write!(f, ":{step}")?; + } + f.write_str("]") + } + SpecialExpr::OuterJoinMark(expr) => write!(f, "{expr} (+)"), + SpecialExpr::QuantifiedList { quantifier, items } => { + let quantifier = match quantifier { + Quantifier::Any => "ANY", + Quantifier::Some => "SOME", + Quantifier::All => "ALL", + }; + write!(f, "{quantifier} ({})", comma(items)) + } + SpecialExpr::OdbcEscape { kind, expr } => write!(f, "{{{kind} {expr}}}"), + SpecialExpr::Prior(expr) => write!(f, "PRIOR {expr}"), + SpecialExpr::Lambda { + params, + parenthesized, + body, + } => { + if *parenthesized { + write!(f, "({}) -> {body}", comma(params)) + } else { + write!(f, "{} -> {body}", comma(params)) + } + } + SpecialExpr::ConnectByRoot(expr) => write!(f, "CONNECT_BY_ROOT {expr}"), + SpecialExpr::Array(items) => write!(f, "ARRAY[{}]", comma(items)), + SpecialExpr::Tuple(items) => write!(f, "({})", comma(items)), + SpecialExpr::Extract { field, expr } => { + f.write_str("EXTRACT(")?; + write_unit(f, field)?; + write!(f, " FROM {expr})") + } + SpecialExpr::Round { ceil, expr, field } => { + let name = if *ceil { "CEIL" } else { "FLOOR" }; + write!(f, "{name}({expr} TO ")?; + write_unit(f, field)?; + f.write_str(")") + } + SpecialExpr::Niladic(name) => name.fmt(f), + SpecialExpr::Position { needle, haystack } => { + write!(f, "POSITION({needle} IN {haystack})") + } + SpecialExpr::Substring { + shorthand, + expr, + from, + length, + } => { + let name = if *shorthand { "SUBSTR" } else { "SUBSTRING" }; + write!(f, "{name}({expr}")?; + if let Some(from) = from { + write!(f, " FROM {from}")?; + } + if let Some(length) = length { + write!(f, " FOR {length}")?; + } + f.write_str(")") + } + SpecialExpr::Trim { side, what, expr } => { + f.write_str("TRIM(")?; + f.write_str(match side { + Some(TrimSide::Both) => "BOTH ", + Some(TrimSide::Leading) => "LEADING ", + Some(TrimSide::Trailing) => "TRAILING ", + None => "", + })?; + if let Some(what) = what { + write!(f, "{what} FROM ")?; + } + write!(f, "{expr})") + } + SpecialExpr::Grouping { kind, sets } => { + f.write_str(match kind { + GroupingKind::Rollup => "ROLLUP (", + GroupingKind::Cube => "CUBE (", + GroupingKind::Sets => "GROUPING SETS (", + })?; + for (i, set) in sets.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + match set.as_slice() { + [only] if *kind != GroupingKind::Sets => only.fmt(f)?, + _ => write!(f, "({})", comma(set))?, + } + } + f.write_str(")") + } + SpecialExpr::Overlay { + expr, + what, + from, + length, + } => { + write!(f, "OVERLAY({expr} PLACING {what} FROM {from}")?; + if let Some(length) = length { + write!(f, " FOR {length}")?; + } + f.write_str(")") + } + } + } +} + +impl Display for Query<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(with) = &self.with { + f.write_str(if with.recursive { + "WITH RECURSIVE " + } else { + "WITH " + })?; + comma(&with.ctes).fmt(f)?; + SpaceOrNewline.fmt(f)?; + } + self.body.fmt(f)?; + write_list(f, "ORDER BY", &self.order_by)?; + if let Some(distribution) = &self.distribution { + if !distribution.cluster_by.is_empty() { + write_indented_clause(f, "CLUSTER BY", comma(&distribution.cluster_by))?; + } + if !distribution.distribute_by.is_empty() { + SpaceOrNewline.fmt(f)?; + f.write_str("DISTRIBUTE BY")?; + SpaceOrNewline.fmt(f)?; + comma(&distribution.distribute_by).fmt(f)?; + } + if !distribution.sort_by.is_empty() { + write_indented_clause(f, "SORT BY", comma(&distribution.sort_by))?; + } + } + if let Some(limit) = &self.limit { + write!(f, " {limit}")?; + } + if let Some(fetch) = &self.fetch { + write!(f, " {fetch}")?; + } + for lock in &self.locks { + write!(f, " {lock}")?; + } + self.tail.fmt(f)?; + for pipe in &self.pipes { + write!(f, " |> {pipe}")?; + } + Ok(()) + } +} + +fn write_optional_as(f: &mut Formatter<'_>, alias: &Option>) -> Result { + match alias { + Some(alias) => write!(f, " AS {alias}"), + None => Ok(()), + } +} + +impl Display for PipeOperator<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + PipeOperator::Select(items) => write!(f, "SELECT {}", comma(items)), + PipeOperator::Extend(items) => write!(f, "EXTEND {}", comma(items)), + PipeOperator::Set(assignments) => write!(f, "SET {}", comma(assignments)), + PipeOperator::Drop(columns) => write!(f, "DROP {}", comma(columns)), + PipeOperator::As(alias) => write!(f, "AS {alias}"), + PipeOperator::Where(condition) => write!(f, "WHERE {condition}"), + PipeOperator::Limit { count, offset } => { + write!(f, "LIMIT {count}")?; + match offset { + Some(offset) => write!(f, " OFFSET {offset}"), + None => Ok(()), + } + } + PipeOperator::OrderBy(items) => write!(f, "ORDER BY {}", comma(items)), + PipeOperator::Aggregate { + aggregates, + group_by, + } => { + f.write_str("AGGREGATE")?; + if !aggregates.is_empty() { + write!(f, " {}", comma(aggregates))?; + } + write_list(f, "GROUP BY", group_by) + } + PipeOperator::TableSample(sample) => sample.fmt(f), + PipeOperator::Rename(renames) => write!(f, "RENAME {}", comma(renames)), + PipeOperator::SetOperation { + op, + quantifier, + by_name, + queries, + } => { + f.write_str(match op { + SetOperator::Union => "UNION", + SetOperator::Except => "EXCEPT", + SetOperator::Intersect => "INTERSECT", + SetOperator::Minus => "MINUS", + })?; + f.write_str(match quantifier { + SetQuantifier::None => "", + SetQuantifier::All => " ALL", + SetQuantifier::Distinct => " DISTINCT", + })?; + if *by_name { + f.write_str(" BY NAME")?; + } + let mut separator = " "; + for query in queries { + write!(f, "{separator}({query})")?; + separator = ", "; + } + Ok(()) + } + PipeOperator::Call { function, alias } => { + write!(f, "CALL {function}")?; + write_optional_as(f, alias) + } + PipeOperator::Pivot { clause, alias } => { + clause.fmt(f)?; + write_optional_as(f, alias) + } + PipeOperator::Unpivot { clause, alias } => { + clause.fmt(f)?; + write_optional_as(f, alias) + } + PipeOperator::Join(join) => join.fmt(f), + } + } +} + +impl Display for PipeAggregate<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.expr.fmt(f)?; + f.write_str(match self.asc { + Some(true) => " ASC", + Some(false) => " DESC", + None => "", + }) + } +} + +impl Display for PipeRename<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} AS {}", self.name, self.new_name) + } +} + +impl Display for SetExpr<'_, X> { + /// Long `UNION` chains recurse here, so this avoids `write!` as + /// [`Expr`]'s rendering does. + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + SetExpr::Select(select) => select.fmt(f), + SetExpr::Query(query) => { + f.write_str("(")?; + query.fmt(f)?; + f.write_str(")") + } + SetExpr::Statement(statement) => statement.fmt(f), + SetExpr::Table(name) => write!(f, "TABLE {name}"), + SetExpr::Values(rows) => write_values(f, rows, ""), + SetExpr::RowValues(rows) => write_values(f, rows, "ROW"), + SetExpr::SetOperation { + left, + op, + quantifier, + by_name, + right, + } => { + (**left).fmt(f)?; + SpaceOrNewline.fmt(f)?; + f.write_str(match op { + SetOperator::Union => "UNION", + SetOperator::Except => "EXCEPT", + SetOperator::Intersect => "INTERSECT", + SetOperator::Minus => "MINUS", + })?; + f.write_str(match quantifier { + SetQuantifier::None => "", + SetQuantifier::All => " ALL", + SetQuantifier::Distinct => " DISTINCT", + })?; + if *by_name { + f.write_str(" BY NAME")?; + } + SpaceOrNewline.fmt(f)?; + (**right).fmt(f) + } + } + } +} + +pub fn write_rows(f: &mut Formatter<'_>, rows: &[Vec>]) -> Result { + for (i, row) in rows.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "({})", comma(row))?; + } + Ok(()) +} + +/// Renders `VALUES` and rows that each start with `prefix`, one per line in `{:#}`. +fn write_values( + f: &mut Formatter<'_>, + rows: &[Vec>], + prefix: &str, +) -> Result { + f.write_str("VALUES")?; + for (i, row) in rows.iter().enumerate() { + if i > 0 { + f.write_str(",")?; + } + SpaceOrNewline.fmt(f)?; + Indent(format_args!("{prefix}({})", comma(row))).fmt(f)?; + } + Ok(()) +} + +impl Select<'_, X> { + fn write_head(&self, f: &mut Formatter<'_>) -> Result { + if self.projection.is_empty() { + return f.write_str("SELECT"); + } + let quantifier = quantifier_prefix(self.quantifier); + if f.alternate() { + let prefix = if X::modifiers_follow_quantifier(&self.modifiers) { + format!("{quantifier}{}", self.modifiers) + } else { + format!("{}{quantifier}", self.modifiers) + }; + f.write_str("SELECT")?; + let prefix = prefix.trim_end(); + if !prefix.is_empty() { + f.write_str(" ")?; + f.write_str(prefix)?; + } + return indented_list(f, &self.projection); + } + if X::modifiers_follow_quantifier(&self.modifiers) { + write!(f, "SELECT {quantifier}{}", self.modifiers)?; + } else { + write!(f, "SELECT {}{quantifier}", self.modifiers)?; + } + comma(&self.projection).fmt(f) + } +} + +impl Display for GroupByModifier { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + GroupByModifier::Rollup => f.write_str(" WITH ROLLUP"), + GroupByModifier::Cube => f.write_str(" WITH CUBE"), + GroupByModifier::Totals => f.write_str(" WITH TOTALS"), + GroupByModifier::Chain(modifiers) => modifiers.iter().try_for_each(|m| m.fmt(f)), + } + } +} + +impl Display for Select<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if self.from_first { + write!(f, "FROM {}", comma(&self.from))?; + if !self.projection.is_empty() { + f.write_str(" ")?; + self.write_head(f)?; + } + } else { + self.write_head(f)?; + if let Some(into) = &self.into { + write!(f, " {into}")?; + } + write_list_clause(f, "FROM", &self.from)?; + } + for view in &self.lateral_views { + write!(f, " {view}")?; + } + if let Some(prewhere) = &self.prewhere { + write!(f, " PREWHERE {prewhere}")?; + } + write_where_clause(f, &self.selection)?; + for clause in &self.connect_by { + SpaceOrNewline.fmt(f)?; + clause.fmt(f)?; + } + if self.group_by_all { + SpaceOrNewline.fmt(f)?; + f.write_str("GROUP BY ALL")?; + } + if !self.group_by.is_empty() { + write_indented_clause(f, "GROUP BY", comma(&self.group_by))?; + } + if let Some(modifier) = &self.group_by_modifier { + modifier.fmt(f)?; + } + if let Some(sets) = &self.grouping_sets { + write!(f, " {sets}")?; + } + if let Some(having) = &self.having { + write_indented_clause(f, "HAVING", having)?; + } + if let Some(qualify) = &self.qualify { + SpaceOrNewline.fmt(f)?; + f.write_str("QUALIFY")?; + SpaceOrNewline.fmt(f)?; + qualify.fmt(f)?; + } + if !self.windows.is_empty() { + SpaceOrNewline.fmt(f)?; + f.write_str("WINDOW")?; + SpaceOrNewline.fmt(f)?; + comma(&self.windows).fmt(f)?; + } + Ok(()) + } +} + +impl Display for LateralView<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let outer = if self.outer { " OUTER" } else { "" }; + write!(f, "LATERAL VIEW{outer} {} {}", self.function, self.name)?; + if !self.columns.is_empty() { + write!(f, " AS {}", comma(&self.columns))?; + } + Ok(()) + } +} + +impl Display for ConnectBy<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + ConnectBy::ConnectBy { + nocycle, + relationships, + } => { + let nocycle = if *nocycle { "NOCYCLE " } else { "" }; + write!(f, "CONNECT BY {nocycle}{}", comma(relationships)) + } + ConnectBy::StartWith(condition) => write!(f, "START WITH {condition}"), + } + } +} + +impl Display for NamedWindow<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} AS {}", self.name, self.window) + } +} + +impl Display for StatementKind<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + StatementKind::Query(query) => query.fmt(f), + StatementKind::Insert(insert) => insert.fmt(f), + StatementKind::Update(update) => update.fmt(f), + StatementKind::Delete(delete) => delete.fmt(f), + StatementKind::CreateTable(create) => create.fmt(f), + StatementKind::CreateView(create) => create.fmt(f), + StatementKind::CreateIndex(create) => create.fmt(f), + StatementKind::CreateSchema(create) => create.fmt(f), + StatementKind::CreateDatabase(create) => create.fmt(f), + StatementKind::Drop(drop) => drop.fmt(f), + StatementKind::Truncate(truncate) => truncate.fmt(f), + StatementKind::AlterTable(alter) => alter.fmt(f), + StatementKind::Grant(grant) => grant.fmt(f), + StatementKind::Revoke(revoke) => revoke.fmt(f), + StatementKind::Merge(merge) => merge.fmt(f), + StatementKind::DropRoutine(drop) => drop.fmt(f), + StatementKind::Show(show) => show.fmt(f), + StatementKind::CreateSequence(create) => create.fmt(f), + StatementKind::AlterView(alter) => alter.fmt(f), + StatementKind::AlterIndexRename { name, new_name } => { + write!(f, "ALTER INDEX {name} RENAME TO {new_name}") + } + StatementKind::CreateRole(create) => { + f.write_str(if create.or_replace { + "CREATE OR REPLACE ROLE " + } else { + "CREATE ROLE " + })?; + write_if_not_exists(f, create.if_not_exists)?; + comma(&create.names).fmt(f) + } + StatementKind::Analyze(analyze) => { + f.write_str("ANALYZE")?; + if analyze.table_keyword { + f.write_str(" TABLE")?; + } + if !analyze.names.is_empty() { + write!(f, " {}", comma(&analyze.names))?; + } + Ok(()) + } + StatementKind::Transaction(transaction) => transaction.fmt(f), + StatementKind::Use(name) => write!(f, "USE {name}"), + StatementKind::Explain(explain) => explain.fmt(f), + StatementKind::Set(set) => set.fmt(f), + StatementKind::Comment(comment) => comment.fmt(f), + StatementKind::Call(call) => write!(f, "CALL {call}"), + StatementKind::Ext(ext) => ext.fmt(f), + } + } +} + +impl Display for OutputClause<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "OUTPUT {}", comma(&self.items))?; + if let Some(into) = &self.into { + write!(f, " INTO {into}")?; + } + Ok(()) + } +} + +fn write_output( + f: &mut Formatter<'_>, + output: &Option>>, +) -> Result { + match output { + Some(output) => { + SpaceOrNewline.fmt(f)?; + output.fmt(f) + } + None => Ok(()), + } +} + +impl Display for Insert<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("INSERT ")?; + write_insert_body(f, self) + } +} + +/// Writes an `INSERT` from its modifiers onwards. +pub fn write_insert_body(f: &mut Formatter<'_>, insert: &Insert<'_, X>) -> Result { + let into = if insert.into { "INTO " } else { "" }; + write!(f, "{}{into}{}", insert.modifiers, insert.table)?; + if !insert.columns.is_empty() { + write!(f, " ({})", comma(&insert.columns))?; + } + write_output(f, &insert.output)?; + let on_new_line = !insert.columns.is_empty() || insert.output.is_some(); + write_insert_source(f, &insert.source, on_new_line)?; + write_list_clause(f, "RETURNING", &insert.returning) +} + +/// Writes the rows or query of an `INSERT` after a space. With `on_new_line`, +/// `{:#}` starts them on a new line instead, as it does after a column list. +pub fn write_insert_source( + f: &mut Formatter<'_>, + source: &InsertSource<'_, X>, + on_new_line: bool, +) -> Result { + if on_new_line { + SpaceOrNewline.fmt(f)?; + } else { + f.write_str(" ")?; + } + match source { + InsertSource::Values(rows) => write_values(f, rows, ""), + InsertSource::RowValues(rows) => write_values(f, rows, "ROW"), + InsertSource::Set(assignments) => { + f.write_str("SET")?; + indented_list(f, assignments) + } + InsertSource::Query(query) => query.fmt(f), + InsertSource::DefaultValues => f.write_str("DEFAULT VALUES"), + } +} + +impl Display for Assignment<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} = {}", self.target, self.value) + } +} + +impl Display for Update<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("UPDATE ")?; + write_update_body(f, self) + } +} + +/// Writes an `UPDATE` from its table onwards. +pub fn write_update_body(f: &mut Formatter<'_>, update: &Update<'_, X>) -> Result { + update.table.fmt(f)?; + for join in &update.joins { + SpaceOrNewline.fmt(f)?; + join.fmt(f)?; + } + if update.from_before_set { + write_list_clause(f, "FROM", &update.from)?; + } + write_list_clause(f, "SET", &update.assignments)?; + if !update.from_before_set { + write_list_clause(f, "FROM", &update.from)?; + } + write_output(f, &update.output)?; + write_where_clause(f, &update.selection)?; + write_order_by_and_limit(f, &update.order_by, &update.limit)?; + write_list_clause(f, "RETURNING", &update.returning) +} + +impl Display for Delete<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(multi) = &self.multi { + return write_multi_table_delete(f, self, multi); + } + f.write_str("DELETE FROM")?; + write_delete_body(f, self) + } +} + +/// Writes a multi-table `DELETE`, in whichever of its two forms it was read. +fn write_multi_table_delete( + f: &mut Formatter<'_>, + delete: &Delete<'_, X>, + multi: &MultiTableDelete<'_>, +) -> Result { + if multi.from_keyword { + f.write_str("DELETE")?; + indented_list(f, &multi.targets)?; + f.write_str(" FROM")?; + indented_list(f, &delete.using)?; + } else { + f.write_str("DELETE FROM")?; + indented_list(f, &multi.targets)?; + write_list_clause(f, "USING", &delete.using)?; + } + write_where_clause(f, &delete.selection) +} + +/// Writes a `DELETE` from a space or line break before its table onwards. +pub fn write_delete_body(f: &mut Formatter<'_>, delete: &Delete<'_, X>) -> Result { + SpaceOrNewline.fmt(f)?; + Indent(&delete.table).fmt(f)?; + write_list_clause(f, "USING", &delete.using)?; + write_output(f, &delete.output)?; + write_where_clause(f, &delete.selection)?; + write_list_clause(f, "ORDER BY", &delete.order_by)?; + if let Some(limit) = &delete.limit { + match (&limit.count, &limit.offset, limit.all, limit.by.is_empty()) { + (Some(count), None, false, true) => write_indented_clause(f, "LIMIT", count)?, + _ => { + SpaceOrNewline.fmt(f)?; + limit.fmt(f)?; + } + } + } + write_list_clause(f, "RETURNING", &delete.returning) +} + +fn write_order_by_and_limit( + f: &mut Formatter<'_>, + order_by: &[OrderByItem<'_, X>], + limit: &Option>>, +) -> Result { + write_list_clause(f, "ORDER BY", order_by)?; + if let Some(limit) = limit { + SpaceOrNewline.fmt(f)?; + limit.fmt(f)?; + } + Ok(()) +} + +impl Display for AngleArguments<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + Self::Types(types) | Self::ParenTypes(types) => comma(types).fmt(f), + Self::Fields(fields) | Self::ParenFields(fields) => comma(fields).fmt(f), + } + } +} + +impl Display for StructField<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(name) = &self.name { + let separator = if self.colon { ": " } else { " " }; + write!(f, "{name}{separator}")?; + } + self.data_type.fmt(f)?; + if self.not_null { + f.write_str(" NOT NULL")?; + } + if let Some(comment) = &self.comment { + write!(f, " COMMENT {}", comment)?; + } + if !self.options.is_empty() { + write!(f, " OPTIONS({})", comma(&self.options))?; + } + Ok(()) + } +} + +impl Display for StructFieldOption<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} = {}", self.key, self.value) + } +} + +impl Display for ExprOption<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} = {}", self.name, self.value) + } +} + +impl Display for DataType<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + for part in &self.qualifier { + write!(f, "{part}.")?; + } + self.name.fmt(f)?; + match self.angle.as_deref() { + Some(arguments @ (AngleArguments::ParenTypes(_) | AngleArguments::ParenFields(_))) => { + write!(f, "({arguments})")?; + } + Some(arguments) => write!(f, "<{arguments}>")?, + None => {} + } + f.write_str(match self.suffix { + DataTypeSuffix::Precision | DataTypeSuffix::PrecisionUnsigned => " PRECISION", + DataTypeSuffix::Varying => " VARYING", + DataTypeSuffix::IntervalFields(fields) => match fields { + IntervalFields::Year => " YEAR", + IntervalFields::Month => " MONTH", + IntervalFields::Day => " DAY", + IntervalFields::Hour => " HOUR", + IntervalFields::Minute => " MINUTE", + IntervalFields::Second => " SECOND", + IntervalFields::YearToMonth => " YEAR TO MONTH", + IntervalFields::DayToHour => " DAY TO HOUR", + IntervalFields::DayToMinute => " DAY TO MINUTE", + IntervalFields::DayToSecond => " DAY TO SECOND", + IntervalFields::HourToMinute => " HOUR TO MINUTE", + IntervalFields::HourToSecond => " HOUR TO SECOND", + IntervalFields::MinuteToSecond => " MINUTE TO SECOND", + }, + _ => "", + })?; + const PRECISION_AND_SCALE: [&str; 7] = [ + "BIGDECIMAL", + "BIGNUMERIC", + "DEC", + "DECIMAL", + "DOUBLE", + "FLOAT", + "NUMERIC", + ]; + let unspaced = PRECISION_AND_SCALE + .iter() + .any(|name| self.name.to_string().eq_ignore_ascii_case(name)); + match (self.args.as_slice(), self.suffix) { + ([], _) => {} + (args, DataTypeSuffix::SignedArgs(signs)) => { + f.write_str("(")?; + for (i, arg) in args.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + if let Some(&sign) = signs.get(i).filter(|sign| **sign != 0) { + write!(f, "{}", sign as char)?; + } + f.write_str(arg)?; + } + f.write_str(")")?; + } + ([precision, scale], _) if unspaced => write!(f, "({precision},{scale})")?, + (args, _) => write!(f, "({})", comma(args))?, + } + f.write_str(match self.suffix { + DataTypeSuffix::WithTimeZone => " WITH TIME ZONE", + DataTypeSuffix::WithoutTimeZone => " WITHOUT TIME ZONE", + DataTypeSuffix::Unsigned | DataTypeSuffix::PrecisionUnsigned => " UNSIGNED", + DataTypeSuffix::Zerofill => " ZEROFILL", + DataTypeSuffix::UnsignedZerofill => " UNSIGNED ZEROFILL", + DataTypeSuffix::Integer => " INTEGER", + _ => "", + })?; + let write_size = |f: &mut Formatter<'_>, size: &Option>| match size { + Some(size) => write!(f, "[{size}]"), + None => f.write_str("[]"), + }; + match &self.array { + ArrayType::None => Ok(()), + ArrayType::Keyword(None) => f.write_str(" ARRAY"), + ArrayType::Keyword(Some(size)) => write!(f, " ARRAY[{size}]"), + ArrayType::Brackets(dimensions) => { + dimensions.iter().try_for_each(|size| write_size(f, size)) + } + } + } +} + +impl Display for SignedNumber<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{}{}", self.sign, self.digits) + } +} + +impl Display for SequenceOption<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + SequenceOption::Increment { by: true, value } => write!(f, "INCREMENT BY {value}"), + SequenceOption::Increment { by: false, value } => write!(f, "INCREMENT {value}"), + SequenceOption::MinValue(Some(value)) => write!(f, "MINVALUE {value}"), + SequenceOption::MinValue(None) => f.write_str("NO MINVALUE"), + SequenceOption::MaxValue(Some(value)) => write!(f, "MAXVALUE {value}"), + SequenceOption::MaxValue(None) => f.write_str("NO MAXVALUE"), + SequenceOption::Start { with: true, value } => write!(f, "START WITH {value}"), + SequenceOption::Start { with: false, value } => write!(f, "START {value}"), + SequenceOption::Cache(value) => write!(f, "CACHE {value}"), + SequenceOption::Cycle(true) => f.write_str("CYCLE"), + SequenceOption::Cycle(false) => f.write_str("NO CYCLE"), + SequenceOption::OwnedBy(name) => write!(f, "OWNED BY {name}"), + } + } +} + +impl Display for CreateSequence<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write_create_flags(f, false, self.temporary)?; + f.write_str("SEQUENCE ")?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if let Some(data_type) = &self.data_type { + write!(f, " AS {data_type}")?; + } + for option in &self.options { + write!(f, " {option}")?; + } + Ok(()) + } +} + +impl Display for Generated<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self.when { + Some(GeneratedWhen::Always) => "GENERATED ALWAYS AS ", + Some(GeneratedWhen::ByDefault) => "GENERATED BY DEFAULT AS ", + Some(GeneratedWhen::Omitted) => "AS ", + None => "GENERATED AS ", + })?; + match &self.kind { + GeneratedKind::Identity(None) => f.write_str("IDENTITY"), + GeneratedKind::Identity(Some(options)) => { + f.write_str("IDENTITY ( ")?; + for option in options { + write!(f, "{option} ")?; + } + f.write_str(")") + } + GeneratedKind::Expr { expr, storage } => { + write!(f, "({expr})")?; + f.write_str(match storage { + Some(GeneratedStorage::Stored) => " STORED", + Some(GeneratedStorage::Virtual) => " VIRTUAL", + None => "", + }) + } + } + } +} + +impl Display for ConstraintAttribute { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self { + ConstraintAttribute::Deferrable(true) => "DEFERRABLE", + ConstraintAttribute::Deferrable(false) => "NOT DEFERRABLE", + ConstraintAttribute::InitiallyDeferred(true) => "INITIALLY DEFERRED", + ConstraintAttribute::InitiallyDeferred(false) => "INITIALLY IMMEDIATE", + ConstraintAttribute::Enforced(true) => "ENFORCED", + ConstraintAttribute::Enforced(false) => "NOT ENFORCED", + ConstraintAttribute::NotValid => "NOT VALID", + ConstraintAttribute::NoInherit => "NO INHERIT", + }) + } +} + +impl Display for Tag<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{}={}", self.name, self.value) + } +} + +impl Display for ColumnOption<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + ColumnOption::Collate(name) => write!(f, "COLLATE {name}"), + ColumnOption::Identity { + autoincrement, + params, + order, + } => { + f.write_str(if *autoincrement { + "AUTOINCREMENT" + } else { + "IDENTITY" + })?; + match params { + Some(IdentityParams { + seed, + increment, + start_form: true, + }) => write!(f, " START {seed} INCREMENT {increment}")?, + Some(IdentityParams { + seed, increment, .. + }) => write!(f, "({seed}, {increment})")?, + None => {} + } + f.write_str(match order { + Some(true) => " ORDER", + Some(false) => " NOORDER", + None => "", + }) + } + ColumnOption::Policy { + with, + masking, + name, + using, + } => { + let with = if *with { "WITH " } else { "" }; + let kind = if *masking { "MASKING" } else { "PROJECTION" }; + write!(f, "{with}{kind} POLICY {name}")?; + if !using.is_empty() { + write!(f, " USING ({})", comma(using))?; + } + Ok(()) + } + ColumnOption::Tags { with, tags } => { + let with = if *with { "WITH " } else { "" }; + write!(f, "{with}TAG ({})", comma(tags)) + } + ColumnOption::Comment(text) => write!(f, "COMMENT {}", text), + ColumnOption::GenericOptions(options) => { + write!(f, "OPTIONS ({})", comma(options)) + } + ColumnOption::NullsDistinct(true) => f.write_str("NULLS DISTINCT"), + ColumnOption::NullsDistinct(false) => f.write_str("NULLS NOT DISTINCT"), + ColumnOption::Options(options) => write!(f, "OPTIONS({})", comma(options)), + ColumnOption::Generated(generated) => generated.fmt(f), + ColumnOption::Attribute(attribute) => attribute.fmt(f), + ColumnOption::NotNull => f.write_str("NOT NULL"), + ColumnOption::Null => f.write_str("NULL"), + ColumnOption::PrimaryKey => f.write_str("PRIMARY KEY"), + ColumnOption::Unique => f.write_str("UNIQUE"), + ColumnOption::Default(expr) => write!(f, "DEFAULT {expr}"), + ColumnOption::Keyword { keyword, expr } => { + f.write_str(keyword)?; + match expr { + Some(expr) => write!(f, " {expr}"), + None => Ok(()), + } + } + ColumnOption::AutoIncrement => f.write_str("AUTO_INCREMENT"), + ColumnOption::Check(expr) => write!(f, "CHECK ({expr})"), + ColumnOption::References(references) => references.fmt(f), + ColumnOption::Named { name, option } => write!(f, "CONSTRAINT {name} {option}"), + } + } +} + +impl Display for ColumnDef<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.name.fmt(f)?; + if !self.data_type.is_unspecified() { + write!(f, " {}", self.data_type)?; + } + for option in &self.options { + write!(f, " {option}")?; + } + Ok(()) + } +} + +impl Display for ExcludeElement<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "{} WITH {}", self.column, self.operator) + } +} + +impl Display for ExcludeOperator<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + ExcludeOperator::Plain(operator) => f.write_str(operator), + ExcludeOperator::Qualified(operator) => write!(f, "OPERATOR({operator})"), + } + } +} + +impl Display for OperatorName<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + for part in &self.schema { + write!(f, "{part}.")?; + } + f.write_str(&self.operator) + } +} + +impl Display for PartitionBound<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + PartitionBound::Default => f.write_str("DEFAULT"), + PartitionBound::In(values) => write!(f, "FOR VALUES IN ({})", comma(values)), + PartitionBound::Range { from, to } => { + write!(f, "FOR VALUES FROM ({}) TO ({})", comma(from), comma(to)) + } + PartitionBound::Hash { modulus, remainder } => { + write!( + f, + "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})" + ) + } + } + } +} + +impl Display for RangeBound<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + RangeBound::MinValue => f.write_str("MINVALUE"), + RangeBound::MaxValue => f.write_str("MAXVALUE"), + RangeBound::Value(value) => value.fmt(f), + } + } +} + +impl Display for GenericOption<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(ref action) = self.action { + write!(f, "{action} ")?; + } + self.name.fmt(f)?; + if let Some(ref value) = self.value { + write!(f, " {}", value)?; + } + Ok(()) + } +} + +impl Display for TableConstraint<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(name) = &self.name { + write!(f, "CONSTRAINT {name} ")?; + } + let nulls = match self.nulls_distinct { + Some(true) => "NULLS DISTINCT ", + Some(false) => "NULLS NOT DISTINCT ", + None => "", + }; + match &self.kind { + TableConstraintKind::PrimaryKey(columns) => { + write!(f, "PRIMARY KEY ({})", comma(columns))?; + } + TableConstraintKind::PrimaryKeyUsingIndex(index) => { + write!(f, "PRIMARY KEY USING INDEX {index}")?; + } + TableConstraintKind::Unique(columns) => { + write!(f, "UNIQUE {nulls}({})", comma(columns))?; + } + TableConstraintKind::UniqueUsingIndex(index) => { + write!(f, "UNIQUE {nulls}USING INDEX {index}")?; + } + TableConstraintKind::Check(expr) => write!(f, "CHECK ({expr})")?, + TableConstraintKind::ForeignKey { + index_name, + columns, + references, + } => { + f.write_str("FOREIGN KEY ")?; + if let Some(index_name) = index_name { + write!(f, "{index_name} ")?; + } + write!(f, "({}) {references}", comma(columns))?; + } + TableConstraintKind::Key { + keyword, + name, + using, + columns, + options, + } => { + f.write_str(keyword)?; + if let Some(name) = name { + write!(f, " {name}")?; + } + if let Some(using) = using { + write!(f, " USING {using}")?; + } + write!(f, " ({})", comma(columns))?; + for option in options { + write!(f, " {option}")?; + } + } + TableConstraintKind::NotNull(column) => write!(f, "NOT NULL {column}")?, + TableConstraintKind::Exclude(exclude) => { + f.write_str("EXCLUDE ")?; + if let Some(using) = &exclude.using { + write!(f, "USING {using} ")?; + } + write!(f, "({})", comma(&exclude.elements))?; + } + } + if !self.include.is_empty() { + write!(f, " INCLUDE ({})", comma(&self.include))?; + } + if let TableConstraintKind::Exclude(exclude) = &self.kind + && let Some(predicate) = &exclude.predicate + { + write!(f, " WHERE ({predicate})")?; + } + for attribute in &self.attributes { + write!(f, " {attribute}")?; + } + Ok(()) + } +} + +/// Renders ` (columns, constraints)`. +pub fn write_columns( + f: &mut Formatter<'_>, + columns: &[ColumnDef<'_, X>], + constraints: &[TableConstraint<'_, X>], +) -> Result { + if columns.is_empty() && constraints.is_empty() { + return f.write_str(" ()"); + } + f.write_str(" (")?; + NewLine.fmt(f)?; + if !columns.is_empty() { + Indent(CommaLines(columns)).fmt(f)?; + } + if !constraints.is_empty() { + if !columns.is_empty() { + f.write_str(",")?; + SpaceOrNewline.fmt(f)?; + } + Indent(CommaLines(constraints)).fmt(f)?; + } + NewLine.fmt(f)?; + f.write_str(")") +} + +impl Display for CreateTable<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write_create_flags(f, self.or_replace, self.temporary)?; + f.write_str("TABLE ")?; + if self.if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + self.name.fmt(f)?; + if !self.columns.is_empty() || !self.constraints.is_empty() { + write_columns(f, &self.columns, &self.constraints)?; + } + match &self.query { + Some(query) => write!(f, " AS {query}"), + None => Ok(()), + } + } +} + +fn write_is(f: &mut Formatter<'_>, test: &IsTest<'_, X>, negated: bool) -> Result { + write!(f, " IS {}", not(negated))?; + match test { + IsTest::Null => f.write_str("NULL"), + IsTest::True => f.write_str("TRUE"), + IsTest::False => f.write_str("FALSE"), + IsTest::Unknown => f.write_str("UNKNOWN"), + IsTest::DistinctFrom(other) => write!(f, "DISTINCT FROM {other}"), + IsTest::Json { kind, unique_keys } => { + f.write_str("JSON")?; + f.write_str(match kind { + None => "", + Some(JsonPredicateType::Value) => " VALUE", + Some(JsonPredicateType::Array) => " ARRAY", + Some(JsonPredicateType::Object) => " OBJECT", + Some(JsonPredicateType::Scalar) => " SCALAR", + })?; + if let Some(unique) = unique_keys { + f.write_str(if unique.with { + " WITH UNIQUE" + } else { + " WITHOUT UNIQUE" + })?; + if unique.keys { + f.write_str(" KEYS")?; + } + } + Ok(()) + } + IsTest::Normalized(form) => f.write_str(match form { + None => "NORMALIZED", + Some(NormalForm::Nfc) => "NFC NORMALIZED", + Some(NormalForm::Nfd) => "NFD NORMALIZED", + Some(NormalForm::Nfkc) => "NFKC NORMALIZED", + Some(NormalForm::Nfkd) => "NFKD NORMALIZED", + }), + } +} + +fn write_like( + f: &mut Formatter<'_>, + pattern: &Expr<'_, X>, + negated: bool, + kind: &LikeKind<'_>, + escape: Option<&Expr<'_, X>>, +) -> Result { + let keyword = match kind { + LikeKind::Like => "LIKE", + LikeKind::ILike => "ILIKE", + LikeKind::SimilarTo => "SIMILAR TO", + LikeKind::Named(name) => name.as_ref(), + }; + write!(f, " {}{keyword} {pattern}", not(negated))?; + match escape { + Some(escape) => write!(f, " ESCAPE {escape}"), + None => Ok(()), + } +} + +fn write_between( + f: &mut Formatter<'_>, + low: &Expr<'_, X>, + high: &Expr<'_, X>, + negated: bool, +) -> Result { + write!(f, " {}BETWEEN {low} AND {high}", not(negated)) +} + +impl Display for CaseWhen<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("WHEN ")?; + self.condition.fmt(f)?; + f.write_str(" THEN")?; + SpaceOrNewline.fmt(f)?; + Indent(&self.result).fmt(f) + } +} + +fn write_case(f: &mut Formatter<'_>, case: &CaseExpr<'_, X>) -> Result { + f.write_str("CASE")?; + if let Some(operand) = &case.operand { + f.write_str(" ")?; + operand.fmt(f)?; + } + for branch in &case.branches { + SpaceOrNewline.fmt(f)?; + Indent(branch).fmt(f)?; + } + if let Some(result) = &case.else_result { + SpaceOrNewline.fmt(f)?; + Indent("ELSE").fmt(f)?; + SpaceOrNewline.fmt(f)?; + Indent(Indent(result)).fmt(f)?; + } + SpaceOrNewline.fmt(f)?; + f.write_str("END") +} + +fn quantifier_prefix(quantifier: SetQuantifier) -> &'static str { + match quantifier { + SetQuantifier::None => "", + SetQuantifier::All => "ALL ", + SetQuantifier::Distinct => "DISTINCT ", + } +} + +fn write_function( + f: &mut Formatter<'_>, + name: &ObjectName<'_>, + args: &[FunctionArg<'_, X>], + options: Option<&FunctionOptions<'_, X>>, +) -> Result { + let Some(options) = options else { + return write!(f, "{name}({})", comma(args)); + }; + let prefix = quantifier_prefix(options.quantifier); + if options.parameters.is_empty() { + write!(f, "{name}({prefix}{}", comma(args))?; + } else { + write!( + f, + "{name}({})({prefix}{}", + comma(&options.parameters), + comma(args) + )?; + } + write_null_treatment(f, options.inner_null_treatment)?; + if args.is_empty() && !options.order_by.is_empty() { + write!(f, "ORDER BY {}", comma(&options.order_by))?; + } else { + write_list(f, "ORDER BY", &options.order_by)?; + } + if let Some(on_overflow) = &options.on_overflow { + write!(f, " {on_overflow}")?; + } + if let Some(ref separator) = options.separator { + write!(f, " SEPARATOR {}", separator)?; + } + f.write_str(")")?; + if !options.within_group.is_empty() { + write!( + f, + " WITHIN GROUP (ORDER BY {})", + comma(&options.within_group) + )?; + } + if let Some(filter) = &options.filter { + write!(f, " FILTER (WHERE {filter})")?; + } + write_null_treatment(f, options.null_treatment)?; + match &options.over { + Some(over) => { + f.write_str(" OVER ")?; + over.fmt(f) + } + None => Ok(()), + } +} + +fn write_null_treatment(f: &mut Formatter<'_>, treatment: Option) -> Result { + match treatment { + Some(NullTreatment::Ignore) => f.write_str(" IGNORE NULLS"), + Some(NullTreatment::Respect) => f.write_str(" RESPECT NULLS"), + None => Ok(()), + } +} + +impl Display for WindowOver<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + WindowOver::Named(name) => name.fmt(f), + WindowOver::Spec(spec) if spec.is_empty() => f.write_str("()"), + WindowOver::Spec(spec) => { + f.write_str("(")?; + NewLine.fmt(f)?; + Indent(spec).fmt(f)?; + NewLine.fmt(f)?; + f.write_str(")") + } + } + } +} + +impl WindowSpec<'_, X> { + fn is_empty(&self) -> bool { + self.base.is_none() + && self.partition_by.is_empty() + && self.order_by.is_empty() + && self.frame.is_none() + } +} + +impl Display for WindowSpec<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let mut first = true; + let mut separate = |f: &mut Formatter<'_>| -> Result { + if !std::mem::take(&mut first) { + SpaceOrNewline.fmt(f)?; + } + Ok(()) + }; + if let Some(base) = &self.base { + separate(f)?; + write!(f, "{base}")?; + } + if !self.partition_by.is_empty() { + separate(f)?; + write!(f, "PARTITION BY {}", comma(&self.partition_by))?; + } + if !self.order_by.is_empty() { + separate(f)?; + write!(f, "ORDER BY {}", comma(&self.order_by))?; + } + if let Some(frame) = &self.frame { + separate(f)?; + write!(f, "{frame}")?; + } + Ok(()) + } +} + +impl Display for WindowFrame<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self.units { + FrameUnits::Rows => "ROWS ", + FrameUnits::Range => "RANGE ", + FrameUnits::Groups => "GROUPS ", + })?; + match &self.end { + Some(end) => write!(f, "BETWEEN {} AND {end}", self.start), + None => self.start.fmt(f), + } + } +} + +impl Display for FrameBound<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + FrameBound::CurrentRow => f.write_str("CURRENT ROW"), + FrameBound::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"), + FrameBound::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"), + FrameBound::Preceding(offset) => write!(f, "{offset} PRECEDING"), + FrameBound::Following(offset) => write!(f, "{offset} FOLLOWING"), + } + } +} + +pub fn write_if_exists(f: &mut Formatter<'_>, if_exists: bool) -> Result { + if if_exists { + f.write_str("IF EXISTS ")?; + } + Ok(()) +} + +pub fn write_if_not_exists(f: &mut Formatter<'_>, if_not_exists: bool) -> Result { + if if_not_exists { + f.write_str("IF NOT EXISTS ")?; + } + Ok(()) +} + +fn write_behavior(f: &mut Formatter<'_>, behavior: Option) -> Result { + match behavior { + Some(DropBehavior::Cascade) => f.write_str(" CASCADE"), + Some(DropBehavior::Restrict) => f.write_str(" RESTRICT"), + None => Ok(()), + } +} + +fn column_word(column_keyword: bool) -> &'static str { + if column_keyword { "COLUMN " } else { "" } +} + +impl Display for ReferentialAction { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self { + ReferentialAction::Cascade => "CASCADE", + ReferentialAction::Restrict => "RESTRICT", + ReferentialAction::SetNull => "SET NULL", + ReferentialAction::SetDefault => "SET DEFAULT", + ReferentialAction::NoAction => "NO ACTION", + }) + } +} + +impl Display for KeyOption<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + KeyOption::Using(method) => write!(f, "USING {method}"), + KeyOption::Comment(text) => write!(f, "COMMENT {}", text), + } + } +} + +impl Display for ForeignKeyRef<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "REFERENCES {}", self.table)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + if let Some(ref kind) = self.match_kind { + write!(f, " MATCH {kind}")?; + } + if let Some(action) = self.on_delete { + write!(f, " ON DELETE {action}")?; + } + if let Some(action) = self.on_update { + write!(f, " ON UPDATE {action}")?; + } + Ok(()) + } +} + +impl Display for DropObject<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let object_type = match self.object_type { + ObjectType::Table => "TABLE", + ObjectType::View => "VIEW", + ObjectType::MaterializedView => "MATERIALIZED VIEW", + ObjectType::Index => "INDEX", + ObjectType::Schema => "SCHEMA", + ObjectType::Database => "DATABASE", + ObjectType::Sequence => "SEQUENCE", + ObjectType::Named(ref name) => name, + }; + let temporary = if self.temporary { "TEMPORARY " } else { "" }; + write!(f, "DROP {temporary}{object_type} ")?; + write_if_exists(f, self.if_exists)?; + comma(&self.names).fmt(f)?; + if let Some(on) = &self.on { + write!(f, " ON {on}")?; + } + write_behavior(f, self.behavior)?; + f.write_str(if self.purge { " PURGE" } else { "" }) + } +} + +/// Renders source words in upper case, separated by spaces. +fn write_words(f: &mut Formatter<'_>, words: &[Cow<'_, str>]) -> Result { + for (i, word) in words.iter().enumerate() { + if i > 0 { + f.write_str(" ")?; + } + f.write_str(&word.to_ascii_uppercase())?; + } + Ok(()) +} + +impl Display for Privilege<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write_words(f, &self.words)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + Ok(()) + } +} + +impl Display for Privileges<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + Privileges::All { privileges: false } => f.write_str("ALL"), + Privileges::All { privileges: true } => f.write_str("ALL PRIVILEGES"), + Privileges::List(privileges) => comma(privileges).fmt(f), + Privileges::Role { + database: true, + name, + } => write!(f, "DATABASE ROLE {name}"), + Privileges::Role { + database: false, + name, + } => write!(f, "ROLE {name}"), + } + } +} + +impl Display for GrantName<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.name.fmt(f)?; + if let Some(args) = &self.args { + write!(f, "({})", comma(args))?; + } + Ok(()) + } +} + +impl Display for GrantObjects<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if !self.kind.is_empty() { + write_words(f, &self.kind)?; + f.write_str(" ")?; + } + comma(&self.names).fmt(f) + } +} + +impl Display for Grantee<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if !self.kind.is_empty() { + write_words(f, &self.kind)?; + f.write_str(" ")?; + } + self.name.fmt(f)?; + match &self.host { + Some(host) => write!(f, "@{host}"), + None => Ok(()), + } + } +} + +impl Display for Grant<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "GRANT {}", self.privileges)?; + if let Some(objects) = &self.objects { + write!(f, " ON {objects}")?; + } + write!(f, " TO {}", comma(&self.grantees))?; + if self.with_grant_option { + f.write_str(" WITH GRANT OPTION")?; + } + f.write_str(match self.current_grants { + Some(CurrentGrants::Copy) => " COPY CURRENT GRANTS", + Some(CurrentGrants::Revoke) => " REVOKE CURRENT GRANTS", + None => "", + })?; + if let Some(grantor) = &self.as_grantor { + write!(f, " AS {grantor}")?; + } + if let Some(granted_by) = &self.granted_by { + write!(f, " GRANTED BY {granted_by}")?; + } + Ok(()) + } +} + +impl Display for Revoke<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("REVOKE ")?; + if self.grant_option_for { + f.write_str("GRANT OPTION FOR ")?; + } + write!( + f, + "{} ON {} FROM {}", + self.privileges, + self.objects, + comma(&self.grantees) + )?; + if let Some(granted_by) = &self.granted_by { + write!(f, " GRANTED BY {granted_by}")?; + } + write_behavior(f, self.behavior) + } +} + +impl Display for Merge<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("MERGE ")?; + write_merge_body(f, self) + } +} + +/// Writes a `MERGE` from any `INTO` onwards. +pub fn write_merge_body(f: &mut Formatter<'_>, merge: &Merge<'_, X>) -> Result { + if merge.into { + f.write_str("INTO ")?; + } + write!(f, "{}", merge.table)?; + SpaceOrNewline.fmt(f)?; + write!(f, "USING {} ON {}", merge.source, merge.on)?; + for clause in &merge.clauses { + SpaceOrNewline.fmt(f)?; + clause.fmt(f)?; + } + write_output(f, &merge.output)?; + write_list_clause(f, "RETURNING", &merge.returning) +} + +impl Display for MergeClause<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self.kind { + MergeClauseKind::Matched => "WHEN MATCHED", + MergeClauseKind::NotMatched => "WHEN NOT MATCHED", + MergeClauseKind::NotMatchedBySource => "WHEN NOT MATCHED BY SOURCE", + MergeClauseKind::NotMatchedByTarget => "WHEN NOT MATCHED BY TARGET", + })?; + if let Some(predicate) = &self.predicate { + write!(f, " AND {predicate}")?; + } + f.write_str(" THEN")?; + SpaceOrNewline.fmt(f)?; + Indent(&self.action).fmt(f) + } +} + +impl Display for MergeAction<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + MergeAction::Delete => f.write_str("DELETE"), + MergeAction::DoNothing => f.write_str("DO NOTHING"), + MergeAction::InsertAll => f.write_str("INSERT *"), + MergeAction::Update { + assignments, + predicate, + delete_predicate, + } => { + f.write_str("UPDATE SET ")?; + match assignments { + Some(assignments) => comma(assignments).fmt(f)?, + None => f.write_str("*")?, + } + write_where(f, predicate)?; + if let Some(predicate) = delete_predicate { + write!(f, " DELETE WHERE {predicate}")?; + } + Ok(()) + } + MergeAction::InsertRow { columns, predicate } => { + f.write_str("INSERT ")?; + if !columns.is_empty() { + write!(f, "({}) ", comma(columns))?; + } + f.write_str("ROW")?; + write_where(f, predicate) + } + MergeAction::Insert { + columns, + rows, + predicate, + } => { + f.write_str("INSERT ")?; + if !columns.is_empty() { + write!(f, "({}) ", comma(columns))?; + } + f.write_str("VALUES ")?; + write_rows(f, rows)?; + write_where(f, predicate) + } + } + } +} + +impl Display for RoutineArg<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + if let Some(ref mode) = self.mode { + write!(f, "{mode} ")?; + } + if let Some(name) = &self.name { + write!(f, "{name} ")?; + } + self.data_type.fmt(f)?; + match &self.default { + Some((true, value)) => write!(f, " = {value}"), + Some((false, value)) => write!(f, " DEFAULT {value}"), + None => Ok(()), + } + } +} + +impl Display for RoutineSignature<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.name.fmt(f)?; + if let Some(args) = &self.args { + write!(f, "({})", comma(args))?; + } + Ok(()) + } +} + +impl Display for DropRoutine<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(if self.procedure { + "DROP PROCEDURE " + } else { + "DROP FUNCTION " + })?; + write_if_exists(f, self.if_exists)?; + comma(&self.routines).fmt(f)?; + write_behavior(f, self.behavior) + } +} + +impl Display for ShowClause<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + ShowClause::History => f.write_str("HISTORY"), + ShowClause::Like(text) => write!(f, "LIKE {}", text), + ShowClause::Where(expr) => write!(f, "WHERE {expr}"), + ShowClause::StartsWith(text) => write!(f, "STARTS WITH {}", text), + ShowClause::Limit(expr) => write!(f, "LIMIT {expr}"), + ShowClause::Pattern(text) => text.fmt(f), + ShowClause::FromValue(text) => write!(f, "FROM {}", text), + ShowClause::Location { from, scope, name } => { + f.write_str(if *from { "FROM" } else { "IN" })?; + if let Some(scope) = scope { + write!(f, " {scope}")?; + } + if let Some(name) = name { + write!(f, " {name}")?; + } + Ok(()) + } + } + } +} + +impl Display for Show<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("SHOW")?; + for word in self.modifiers.iter().chain(&self.object) { + write!(f, " {word}")?; + } + if let Some(name) = &self.name { + write!(f, " {name}")?; + } + for clause in &self.clauses { + write!(f, " {clause}")?; + } + Ok(()) + } +} + +impl Display for TransactionMode { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(match self { + TransactionMode::ReadOnly => "READ ONLY", + TransactionMode::ReadWrite => "READ WRITE", + TransactionMode::IsolationLevel(IsolationLevel::ReadUncommitted) => { + "ISOLATION LEVEL READ UNCOMMITTED" + } + TransactionMode::IsolationLevel(IsolationLevel::ReadCommitted) => { + "ISOLATION LEVEL READ COMMITTED" + } + TransactionMode::IsolationLevel(IsolationLevel::RepeatableRead) => { + "ISOLATION LEVEL REPEATABLE READ" + } + TransactionMode::IsolationLevel(IsolationLevel::Serializable) => { + "ISOLATION LEVEL SERIALIZABLE" + } + TransactionMode::IsolationLevel(IsolationLevel::Snapshot) => "ISOLATION LEVEL SNAPSHOT", + }) + } +} + +impl Display for Transaction<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + Transaction::Start(modes) if modes.is_empty() => f.write_str("START TRANSACTION"), + Transaction::Start(modes) => write!(f, "START TRANSACTION {}", comma(modes)), + Transaction::Begin(None) => f.write_str("BEGIN"), + Transaction::Begin(Some(word)) => write!(f, "BEGIN {word}"), + Transaction::Finish { + kind, + chain, + savepoint, + } => { + f.write_str(match kind { + FinishKind::Commit => "COMMIT", + FinishKind::End => "END", + FinishKind::Rollback => "ROLLBACK", + FinishKind::Abort => "ABORT", + })?; + if *chain { + f.write_str(" AND CHAIN")?; + } + match savepoint { + Some(savepoint) => write!(f, " TO SAVEPOINT {savepoint}"), + None => Ok(()), + } + } + Transaction::Savepoint(name) => write!(f, "SAVEPOINT {name}"), + Transaction::Release(name) => write!(f, "RELEASE SAVEPOINT {name}"), + } + } +} + +impl Display for ExplainOption<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.name.fmt(f)?; + match self.value { + Some(ref value) => write!(f, " {}{value}", self.sign), + None => Ok(()), + } + } +} + +impl Display for Explain<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(&self.keyword)?; + if !self.options.is_empty() { + write!(f, " ({})", comma(&self.options))?; + } + if let Some(ref detail) = self.detail { + write!(f, " {detail}")?; + } + for (set, word) in [ + (self.analyze, " ANALYZE"), + (self.verbose, " VERBOSE"), + (self.estimate, " ESTIMATE"), + (self.query_plan, " QUERY PLAN"), + ] { + if set { + f.write_str(word)?; + } + } + if let Some(format) = &self.format { + let separator = if format.equals { "=" } else { " " }; + write!(f, " FORMAT{separator}{}", format.name)?; + } + match &self.target { + ExplainTarget::Statement(statement) => { + SpaceOrNewline.fmt(f)?; + statement.fmt(f) + } + ExplainTarget::Table { + table_keyword, + name, + } => { + if *table_keyword { + f.write_str(" TABLE")?; + } + write!(f, " {name}") + } + } + } +} + +fn write_scope(f: &mut Formatter<'_>, scope: Option<&str>) -> Result { + match scope { + Some(scope) => write!(f, "{scope} "), + None => Ok(()), + } +} + +impl Display for SetAssignment<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write_scope(f, self.scope.as_deref())?; + write!(f, "{} = {}", self.name, self.value) + } +} + +impl Display for SetStatement<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("SET ")?; + match self { + SetStatement::Variable { + scope, + name, + values, + } => { + write_scope(f, scope.as_deref())?; + write!(f, "{name} = {}", comma(values)) + } + SetStatement::Assignments(assignments) => comma(assignments).fmt(f), + SetStatement::Role { scope, role } => { + write_scope(f, scope.as_deref())?; + write!(f, "ROLE {role}") + } + SetStatement::Authorization { scope, user } => { + write_scope(f, scope.as_deref())?; + write!(f, "AUTHORIZATION {user}") + } + SetStatement::TimeZone { scope, value } => { + write_scope(f, scope.as_deref())?; + write!(f, "TIME ZONE {value}") + } + SetStatement::Transaction { + characteristics, + modes, + snapshot, + } => { + f.write_str(if *characteristics { + "SESSION CHARACTERISTICS AS TRANSACTION" + } else { + "TRANSACTION" + })?; + if let Some(snapshot) = snapshot { + write!(f, " SNAPSHOT {}", snapshot)?; + } + if !modes.is_empty() { + write!(f, " {}", comma(modes))?; + } + Ok(()) + } + SetStatement::Names { charset, collate } => { + write!(f, "NAMES {charset}")?; + match collate { + Some(collate) => write!(f, " COLLATE {collate}"), + None => Ok(()), + } + } + } + } +} + +impl Display for CommentOn<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("COMMENT ")?; + write_if_exists(f, self.if_exists)?; + f.write_str("ON ")?; + write_words(f, &self.kind)?; + write!(f, " {} IS ", self.name)?; + match &self.comment { + Some(text) => text.fmt(f), + None => f.write_str("NULL"), + } + } +} + +impl Display for Truncate<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(if self.table_keyword { + "TRUNCATE TABLE " + } else { + "TRUNCATE " + })?; + write_if_exists(f, self.if_exists)?; + comma(&self.names).fmt(f) + } +} + +impl Display for AlterColumnAction<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + AlterColumnAction::SetNotNull => f.write_str("SET NOT NULL"), + AlterColumnAction::DropNotNull => f.write_str("DROP NOT NULL"), + AlterColumnAction::SetDefault(expr) => write!(f, "SET DEFAULT {expr}"), + AlterColumnAction::DropDefault => f.write_str("DROP DEFAULT"), + AlterColumnAction::SetType { + data_type, + set_data, + using, + } => { + f.write_str(if *set_data { "SET DATA TYPE " } else { "TYPE " })?; + data_type.fmt(f)?; + match using { + Some(using) => write!(f, " USING {using}"), + None => Ok(()), + } + } + AlterColumnAction::AddGenerated(generated) => write!(f, "ADD {generated}"), + AlterColumnAction::GenericOptions(options) => { + write!(f, "OPTIONS ({})", comma(options)) + } + } + } +} + +fn write_position(f: &mut Formatter<'_>, position: &Option>) -> Result { + match position { + Some(ColumnPosition::First) => f.write_str(" FIRST"), + Some(ColumnPosition::After(name)) => write!(f, " AFTER {name}"), + None => Ok(()), + } +} + +impl Display for AlterTableOp<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + match self { + AlterTableOp::SetTblProperties(properties) => { + f.write_str("SET TBLPROPERTIES(")?; + for (i, (key, value)) in properties.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{key} = {value}")?; + } + f.write_str(")") + } + AlterTableOp::AddColumn { + column_keyword, + if_not_exists, + column, + position, + } => { + write!(f, "ADD {}", column_word(*column_keyword))?; + write_if_not_exists(f, *if_not_exists)?; + column.fmt(f)?; + write_position(f, position) + } + AlterTableOp::Phrase(phrase) => f.write_str(phrase), + AlterTableOp::PhraseName { phrase, name } => write!(f, "{phrase} {name}"), + AlterTableOp::Setting { + name, + equals, + value, + } => { + let separator = if *equals { " = " } else { " " }; + write!(f, "{name}{separator}{value}") + } + AlterTableOp::RenameConstraint { old, new } => { + write!(f, "RENAME CONSTRAINT {old} TO {new}") + } + AlterTableOp::RenameAs(name) => write!(f, "RENAME AS {name}"), + AlterTableOp::ChangeColumn { + old, + column, + position, + } => { + write!(f, "CHANGE COLUMN {old} {column}")?; + write_position(f, position) + } + AlterTableOp::ModifyColumn { column, position } => { + write!(f, "MODIFY COLUMN {column}")?; + write_position(f, position) + } + AlterTableOp::SwapWith(name) => write!(f, "SWAP WITH {name}"), + AlterTableOp::PhraseObject { phrase, name } => write!(f, "{phrase} {name}"), + AlterTableOp::AttachPartition { name, bound } => { + write!(f, "ATTACH PARTITION {name} {bound}") + } + AlterTableOp::DetachPartition { name, mode } => { + write!(f, "DETACH PARTITION {name}")?; + match mode { + Some(mode) => write!(f, " {mode}"), + None => Ok(()), + } + } + AlterTableOp::GenericOptions(options) => write!(f, "OPTIONS ({})", comma(options)), + AlterTableOp::ResetOptions(names) => write!(f, "RESET ({})", comma(names)), + AlterTableOp::ClusterBy(exprs) => write!(f, "CLUSTER BY ({})", comma(exprs)), + AlterTableOp::AlterSortKey(columns) => { + write!(f, "ALTER SORTKEY({})", comma(columns)) + } + AlterTableOp::SetOptions(options) => { + f.write_str("SET ")?; + write_storage(f, options) + } + AlterTableOp::DropColumn { + column_keyword, + if_exists, + name, + behavior, + } => { + write!(f, "DROP {}", column_word(*column_keyword))?; + write_if_exists(f, *if_exists)?; + name.fmt(f)?; + write_behavior(f, *behavior) + } + AlterTableOp::DropColumns { + column_keyword, + if_exists, + names, + behavior, + } => { + write!(f, "DROP {}", column_word(*column_keyword))?; + write_if_exists(f, *if_exists)?; + comma(names).fmt(f)?; + write_behavior(f, *behavior) + } + AlterTableOp::DropForeignKey { name, behavior } => { + write!(f, "DROP FOREIGN KEY {name}")?; + write_behavior(f, *behavior) + } + AlterTableOp::RenameColumn { old, new } => write!(f, "RENAME COLUMN {old} TO {new}"), + AlterTableOp::RenameTable(name) => write!(f, "RENAME TO {name}"), + AlterTableOp::AddPartitions { + if_not_exists, + partitions, + } => { + f.write_str("ADD")?; + if *if_not_exists { + f.write_str(" IF NOT EXISTS")?; + } + for partition in partitions { + write!(f, " PARTITION ({})", comma(partition))?; + } + Ok(()) + } + AlterTableOp::DropPartition { + if_exists, + partition, + } => { + let if_exists = if *if_exists { "IF EXISTS " } else { "" }; + write!(f, "DROP {if_exists}PARTITION ({})", comma(partition)) + } + AlterTableOp::RenamePartition { old, new, location } => { + write!( + f, + "PARTITION ({}) RENAME TO PARTITION ({})", + comma(old), + comma(new) + )?; + if let Some((set, path)) = location { + let set = if *set { "SET " } else { "" }; + write!(f, " {set}LOCATION {}", path)?; + } + Ok(()) + } + AlterTableOp::AlterColumn { + column_keyword, + name, + action, + } => write!(f, "ALTER {}{name} {action}", column_word(*column_keyword)), + AlterTableOp::AddConstraint(constraint) => write!(f, "ADD {constraint}"), + AlterTableOp::DropConstraint { + if_exists, + name, + behavior, + } => { + f.write_str("DROP CONSTRAINT ")?; + write_if_exists(f, *if_exists)?; + name.fmt(f)?; + write_behavior(f, *behavior) + } + } + } +} + +impl Display for AlterTable<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("ALTER TABLE ")?; + write_if_exists(f, self.if_exists)?; + if self.only { + f.write_str("ONLY ")?; + } + write!(f, "{} {}", self.name, comma(&self.operations)) + } +} + +/// Writes ` AS` and a view's query, which starts on a new line in `{:#}`. +pub fn write_view_query(f: &mut Formatter<'_>, query: &Query<'_, X>) -> Result { + f.write_str(" AS")?; + SpaceOrNewline.fmt(f)?; + query.fmt(f) +} + +pub fn write_create_flags(f: &mut Formatter<'_>, or_replace: bool, temporary: bool) -> Result { + f.write_str("CREATE ")?; + if or_replace { + f.write_str("OR REPLACE ")?; + } + if temporary { + f.write_str("TEMPORARY ")?; + } + Ok(()) +} + +impl Display for CreateView<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write_create_flags(f, self.or_replace, self.temporary)?; + if self.materialized { + f.write_str("MATERIALIZED ")?; + } + f.write_str("VIEW ")?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + if !self.with.is_empty() { + f.write_str(" WITH ")?; + write_storage(f, &self.with)?; + } + write_view_query(f, &self.query)?; + if self.no_schema_binding { + f.write_str(" WITH NO SCHEMA BINDING")?; + } + Ok(()) + } +} + +impl Display for CreateIndex<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(if self.unique { + "CREATE UNIQUE INDEX " + } else { + "CREATE INDEX " + })?; + if self.concurrently { + f.write_str("CONCURRENTLY ")?; + } + if self.asynchronous { + f.write_str("ASYNC ")?; + } + write_if_not_exists(f, self.if_not_exists)?; + if let Some(name) = &self.name { + name.fmt(f)?; + if self.using_before_on.is_some() { + f.write_str(" ")?; + } + } + if let Some(using) = &self.using_before_on { + write!(f, "USING {using}")?; + } + if self.name.is_some() || self.using_before_on.is_some() { + SpaceOrNewline.fmt(f)?; + } + write!(f, "ON {}", self.table)?; + if let Some(using) = &self.using { + write!(f, " USING {using}")?; + } + write!(f, " ({})", comma(&self.columns))?; + if let Some(using) = &self.trailing_using { + write!(f, " USING {using}")?; + } + if !self.include.is_empty() { + write!(f, " INCLUDE ({})", comma(&self.include))?; + } + f.write_str(match self.nulls_distinct { + Some(true) => " NULLS DISTINCT", + Some(false) => " NULLS NOT DISTINCT", + None => "", + })?; + if !self.with.is_empty() { + f.write_str(" WITH ")?; + write_storage(f, &self.with)?; + } + write_where(f, &self.predicate)?; + for (name, value) in &self.settings { + write!(f, " {name} = {value}")?; + } + Ok(()) + } +} + +fn write_table_values(f: &mut Formatter<'_>, rows: &[Vec>]) -> Result { + f.write_str("VALUES ")?; + write_rows(f, rows) +} + +pub fn write_storage(f: &mut Formatter<'_>, parameters: &IndexStorage<'_, X>) -> Result { + f.write_str("(")?; + for (i, (name, value)) in parameters.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + name.fmt(f)?; + if let Some(value) = value { + write!(f, " = {value}")?; + } + } + f.write_str(")") +} + +impl Display for IndexColumn<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + self.item.expr.fmt(f)?; + if let Some(class) = &self.operator_class { + write!(f, " {class}")?; + } + write_order_modifiers(f, &self.item) + } +} + +impl Display for CreateSchema<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str(if self.or_replace { + "CREATE OR REPLACE SCHEMA " + } else { + "CREATE SCHEMA " + })?; + write_if_not_exists(f, self.if_not_exists)?; + if let Some(name) = &self.name { + name.fmt(f)?; + } + if let Some(owner) = &self.authorization { + let space = if self.name.is_some() { " " } else { "" }; + write!(f, "{space}AUTHORIZATION {owner}")?; + } + if let Some(source) = &self.clone { + write!(f, " CLONE {source}")?; + } + Ok(()) + } +} + +impl Display for AlterView<'_, X> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + write!(f, "ALTER VIEW {}", self.name)?; + if !self.columns.is_empty() { + write!(f, " ({})", comma(&self.columns))?; + } + write!(f, " AS {}", self.query) + } +} + +impl Display for CreateDatabase<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.write_str("CREATE DATABASE ")?; + write_if_not_exists(f, self.if_not_exists)?; + self.name.fmt(f) + } +} + +impl Display for crate::ast::Expr<'_, X> { + #[inline(always)] + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + Display::fmt(&self.kind, f) + } +} + +impl Display for crate::ast::Statement<'_, X> { + #[inline(always)] + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + Display::fmt(&self.kind, f) + } +} + +impl Display for crate::ast::SelectItem<'_, X> { + #[inline(always)] + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + Display::fmt(&self.kind, f) + } +} diff --git a/sqlparser_v2/src/grammar.rs b/sqlparser_v2/src/grammar.rs new file mode 100644 index 0000000000..b4948243ba --- /dev/null +++ b/sqlparser_v2/src/grammar.rs @@ -0,0 +1,271 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The core grammar. +//! +//! Each rule is the default implementation of a [`Dialect`] method, and a +//! rule always reaches other rules through `D::`, so an override applies +//! everywhere. Dialects call these functions to fall back to core behavior. +//! Nothing here may depend on which dialect is running. + +use crate::PResult; +use crate::ast::StatementKind; +use crate::ast::*; +use crate::dialect::Dialect; +use crate::lexer::{Token, TokenKind}; +use crate::parser::{InfixParseFn, InfixRule, Parser, SetOperatorRule}; +use std::borrow::Cow; + +mod admin; +mod ddl; +mod dml; +mod expr; +mod pattern; +mod pipe; +mod pivot; +mod query; +mod session; +mod xml; + +pub use admin::*; +pub use ddl::*; +pub use dml::*; +pub use expr::*; +pub use pattern::*; +pub use pipe::*; +pub use pivot::*; +pub use query::*; +pub use session::*; +pub use xml::*; + +/// Binding powers of the core operators. Dialects choose theirs relative to +/// these. +pub mod prec { + pub const OR: u8 = 10; + pub const AND: u8 = 20; + pub const NOT: u8 = 30; + pub const IS: u8 = 35; + pub const COMPARE: u8 = 40; + pub const BIT_OR: u8 = 42; + /// `^`, `<<` and `>>`. + pub const BIT_XOR: u8 = 44; + pub const BIT_AND: u8 = 46; + /// Below `+` and above comparison, for operators without a standard rank. + pub const OTHER: u8 = 48; + pub const ADD: u8 = 50; + pub const MUL: u8 = 60; + /// Exponentiation, in dialects where `^` means that. + pub const EXP: u8 = 65; + pub const AT_TIME_ZONE: u8 = 67; + pub const UNARY: u8 = 70; + /// Tighter than every core operator, for postfix-style syntax. + pub const POSTFIX: u8 = 80; + + /// Binding powers of the set operators, which only compare with each other. + pub const UNION: u8 = 10; + pub const INTERSECT: u8 = 20; +} + +/// The length of the longest word matched by [`is_reserved`]. +const MAX_RESERVED_LEN: usize = 9; + +/// Called for most identifiers, so it avoids scanning a list: longer words +/// return at once, and `matches!` compiles to a decision tree on the bytes. +#[inline] +pub fn is_reserved(word: &str) -> bool { + if word.len() > MAX_RESERVED_LEN { + return false; + } + let mut buffer = [0; MAX_RESERVED_LEN]; + let upper = &mut buffer[..word.len()]; + upper.copy_from_slice(word.as_bytes()); + upper.make_ascii_uppercase(); + matches!( + &*upper, + b"SELECT" + | b"FROM" + | b"WHERE" + | b"GROUP" + | b"ORDER" + | b"BY" + | b"LIMIT" + | b"OFFSET" + | b"AS" + | b"AND" + | b"OR" + | b"NOT" + | b"ASC" + | b"DESC" + | b"WITH" + | b"JOIN" + | b"INNER" + | b"LEFT" + | b"RIGHT" + | b"FULL" + | b"OUTER" + | b"CROSS" + | b"ON" + | b"USING" + | b"HAVING" + | b"UNION" + | b"INTERSECT" + | b"EXCEPT" + | b"IN" + | b"SET" + | b"DISTINCT" + | b"ALL" + | b"NATURAL" + | b"NULL" + | b"TRUE" + | b"FALSE" + | b"CASE" + ) +} + +/// Words that begin a clause, so cannot be an alias without `AS`, but are +/// otherwise usable as names. +#[inline] +pub fn is_reserved_for_alias(word: &str) -> bool { + ["FOR", "FETCH", "WINDOW", "INTO", "ARRAY", "PARTITION"] + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(word)) +} + +/// Builds a string literal from its token, including the quotes. +#[inline] +pub fn string_literal(token: Token<'_>) -> StringLiteral<'_> { + StringLiteral { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: char::from(token.text.as_bytes()[0]), + backslash_escapes: false, + national: false, + prefix: StringPrefix::None, + triple: false, + } +} + +/// Like [`string_literal`], for dialects that lex `N'text'` as one token. +pub fn national_string_literal(token: Token<'_>) -> StringLiteral<'_> { + if matches!(token.text.as_bytes()[0], b'N' | b'n') { + StringLiteral { + prefix: Default::default(), + triple: false, + text: Cow::Borrowed(&token.text[2..token.text.len() - 1]), + quote: '\'', + backslash_escapes: false, + national: true, + } + } else { + string_literal(token) + } +} + +pub fn parse_statement<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if at_query_start(p) || p.at_op("(") { + return D::parse_query(p).map(|query| StatementKind::Query(Box::new(query)).into()); + } + if p.at_keyword("INSERT") { + return D::parse_insert_statement(p); + } + if p.at_keyword("UPDATE") { + return D::parse_update(p).map(|update| StatementKind::Update(Box::new(update)).into()); + } + if p.at_keyword("DELETE") { + return D::parse_delete(p).map(|delete| StatementKind::Delete(Box::new(delete)).into()); + } + if p.at_keyword("CREATE") { + return D::parse_create(p); + } + if p.at_keyword("SHOW") { + return D::parse_show(p).map(|show| StatementKind::Show(Box::new(show)).into()); + } + if at_transaction(p) { + return D::parse_transaction(p).map(|t| StatementKind::Transaction(Box::new(t)).into()); + } + if p.at_keyword("USE") { + return D::parse_use(p).map(|name| StatementKind::Use(Box::new(name)).into()); + } + if p.at_keyword("EXPLAIN") || p.at_keyword("DESCRIBE") || p.at_keyword("DESC") { + return D::parse_explain(p).map(|explain| StatementKind::Explain(Box::new(explain)).into()); + } + if p.at_keyword("SET") { + return D::parse_set(p).map(|set| StatementKind::Set(Box::new(set)).into()); + } + if p.at_keyword("CALL") { + return D::parse_call(p).map(|call| StatementKind::Call(Box::new(call)).into()); + } + if p.at_keyword("GRANT") { + return D::parse_grant(p).map(|grant| StatementKind::Grant(Box::new(grant)).into()); + } + if p.at_keyword("REVOKE") { + return D::parse_revoke(p).map(|revoke| StatementKind::Revoke(Box::new(revoke)).into()); + } + if p.at_keyword("MERGE") { + return D::parse_merge(p).map(|merge| StatementKind::Merge(Box::new(merge)).into()); + } + if at_drop_function(p) { + return D::parse_drop_routine(p) + .map(|drop| StatementKind::DropRoutine(Box::new(drop)).into()); + } + if p.at_keyword("DROP") { + return D::parse_drop(p).map(|drop| StatementKind::Drop(Box::new(drop)).into()); + } + if p.at_keyword("TRUNCATE") { + return D::parse_truncate(p) + .map(|truncate| StatementKind::Truncate(Box::new(truncate)).into()); + } + if p.at_keyword("ALTER") { + return D::parse_alter_table(p) + .map(|alter| StatementKind::AlterTable(Box::new(alter)).into()); + } + Err(p.expected("a statement")) +} + +pub fn parse_optional_where<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("WHERE") { + p.parse_expr().map(Some) + } else { + Ok(None) + } +} + +/// Parses a name after a dot, where reserved words are allowed. +pub fn parse_name_part<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::Word => { + p.advance(); + Ok(Ident { + text: token.text.into(), + quote: None, + span: token.span, + }) + } + TokenKind::QuotedIdent => p.parse_ident(), + _ => Err(p.expected("identifier")), + } +} + +/// Parses `(a, b, ...)`. +pub fn parse_ident_list<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + p.expect_op("(")?; + let idents = p.parse_comma_separated(Parser::parse_ident)?; + p.expect_op(")")?; + Ok(idents) +} diff --git a/sqlparser_v2/src/grammar/admin.rs b/sqlparser_v2/src/grammar/admin.rs new file mode 100644 index 0000000000..1872f7aa4d --- /dev/null +++ b/sqlparser_v2/src/grammar/admin.rs @@ -0,0 +1,440 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Rules for `GRANT`, `REVOKE`, `MERGE` and `DROP FUNCTION`. + +use super::*; +use crate::PResult; +use crate::dialect::Dialect; +use crate::lexer::{Token, TokenKind}; +use crate::parser::Parser; +use std::borrow::Cow; + +fn is_name_token(token: Token<'_>) -> bool { + matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) +} + +/// Reads the words of one privilege, up to what ends it. +fn parse_privilege<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut words = Vec::new(); + while p.peek().kind == TokenKind::Word && !p.at_keyword("ON") { + words.push(p.peek().text); + p.advance(); + } + if words.is_empty() { + return Err(p.expected("a privilege")); + } + let columns = if p.at_op("(") { + parse_ident_list(p)? + } else { + Vec::new() + }; + Ok(Privilege { + words: words.into_iter().map(Cow::Borrowed).collect(), + columns, + }) +} + +pub fn parse_privileges<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let next = p.peek_nth(1); + if p.at_keyword("ALL") && (next.is_word("ON") || next.is_word("PRIVILEGES")) { + p.advance(); + let privileges = p.eat_keyword("PRIVILEGES"); + return Ok(Privileges::All { privileges }); + } + p.parse_comma_separated(parse_privilege) + .map(Privileges::List) +} + +/// Reads the words that say what kind of thing a name is, as in +/// `COMPUTE POOL p`. The last word before the end of the name is the name. +pub(super) fn parse_kind_words<'a, D: Dialect>( + p: &mut Parser<'a, D>, + stops: &[&str], +) -> Vec<&'a str> { + let mut words = Vec::new(); + while p.peek().kind == TokenKind::Word { + let next = p.peek_nth(1); + if !is_name_token(next) || stops.iter().any(|stop| next.is_word(stop)) { + break; + } + words.push(p.peek().text); + p.advance(); + } + words +} + +pub fn parse_grant_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = parse_object_name(p)?; + let args = if p.eat_op("(") { + let args = p.parse_comma_separated(D::parse_data_type)?; + p.expect_op(")")?; + Some(args) + } else { + None + }; + Ok(GrantName { name, args }) +} + +pub fn parse_grant_objects<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let kind = parse_kind_words(p, &["TO", "FROM"]); + let names = p.parse_comma_separated(D::parse_grant_name)?; + Ok(GrantObjects { + kind: kind.into_iter().map(Cow::Borrowed).collect(), + names, + }) +} + +const GRANTEE_STOPS: [&str; 7] = [ + "WITH", "COPY", "REVOKE", "AS", "GRANTED", "CASCADE", "RESTRICT", +]; + +const GRANTEE_KINDS: [&[&str]; 8] = [ + &[], + &["ROLE"], + &["USER"], + &["GROUP"], + &["SHARE"], + &["APPLICATION"], + &["DATABASE", "ROLE"], + &["APPLICATION", "ROLE"], +]; + +pub fn parse_grantee<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let kind = parse_kind_words(p, &GRANTEE_STOPS); + if !GRANTEE_KINDS.iter().any(|known| { + known.len() == kind.len() + && known + .iter() + .zip(&kind) + .all(|(word, text)| word.eq_ignore_ascii_case(text)) + }) { + return Err(p.expected("a role, user or other kind of grantee")); + } + let name = parse_object_name(p)?; + Ok(Grantee { + kind: kind.into_iter().map(Cow::Borrowed).collect(), + name, + host: None, + }) +} + +/// Parses the list of grantees. `PUBLIC` must be the only one. +pub fn parse_grantees<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let grantees = p.parse_comma_separated(D::parse_grantee)?; + let public = grantees.iter().any(|grantee| { + matches!(grantee.name.parts.as_slice(), [only] + if only.quote.is_none() && only.text.eq_ignore_ascii_case("PUBLIC")) + }); + if public && grantees.len() > 1 { + return Err(p.expected("PUBLIC on its own")); + } + Ok(grantees) +} + +/// True at `[DATABASE] ROLE name TO`, which grants a role rather than a +/// privilege on an object. +fn at_role_grant<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let offset = usize::from(p.at_keyword("DATABASE")); + p.peek_nth(offset).is_word("ROLE") + && is_name_token(p.peek_nth(offset + 1)) + && !p.peek_nth(offset + 1).is_word("ON") +} + +pub fn parse_grant<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("GRANT")?; + let (privileges, objects) = if at_role_grant(p) { + let database = p.eat_keyword("DATABASE"); + p.expect_keyword("ROLE")?; + let name = parse_object_name(p)?; + (Privileges::Role { database, name }, None) + } else { + let privileges = parse_privileges(p)?; + p.expect_keyword("ON")?; + (privileges, Some(parse_grant_objects(p)?)) + }; + p.expect_keyword("TO")?; + let grantees = D::parse_grantees(p)?; + + let with_grant_option = p.eat_keyword("WITH"); + if with_grant_option { + p.expect_keywords(&["GRANT", "OPTION"])?; + } + let current_grants = if p.eat_keyword("COPY") { + p.expect_keywords(&["CURRENT", "GRANTS"])?; + Some(CurrentGrants::Copy) + } else if p.eat_keyword("REVOKE") { + p.expect_keywords(&["CURRENT", "GRANTS"])?; + Some(CurrentGrants::Revoke) + } else { + None + }; + let as_grantor = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + let granted_by = parse_granted_by(p)?; + Ok(Grant { + privileges, + objects, + grantees, + with_grant_option, + current_grants, + as_grantor, + granted_by, + }) +} + +fn parse_granted_by<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if !p.eat_keyword("GRANTED") { + return Ok(None); + } + p.expect_keyword("BY")?; + p.parse_ident().map(Some) +} + +pub fn parse_revoke<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("REVOKE")?; + let grant_option_for = p.at_keyword("GRANT") && p.peek_nth(1).is_word("OPTION"); + if grant_option_for { + p.advance(); + p.advance(); + p.expect_keyword("FOR")?; + } + let privileges = parse_privileges(p)?; + p.expect_keyword("ON")?; + let objects = parse_grant_objects(p)?; + p.expect_keyword("FROM")?; + let grantees = D::parse_grantees(p)?; + let granted_by = parse_granted_by(p)?; + let behavior = if p.eat_keyword("CASCADE") { + Some(DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(DropBehavior::Restrict) + } else { + None + }; + Ok(Revoke { + grant_option_for, + privileges, + objects, + grantees, + granted_by, + behavior, + }) +} + +pub fn parse_merge<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("MERGE")?; + let into = p.eat_keyword("INTO"); + let table = p.parse_table_ref()?; + p.expect_keyword("USING")?; + let source = p.parse_table_ref()?; + p.expect_keyword("ON")?; + let on = p.parse_expr()?; + let mut clauses = Vec::new(); + while p.eat_keyword("WHEN") { + clauses.push(parse_merge_clause(p)?); + } + let output = D::parse_output_clause(p)?; + let returning = D::parse_returning(p)?; + Ok(Merge { + into, + table, + source, + on, + clauses, + output, + returning, + }) +} + +fn parse_merge_clause_kind<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + if !p.eat_keyword("NOT") { + p.expect_keyword("MATCHED")?; + return Ok(MergeClauseKind::Matched); + } + p.expect_keyword("MATCHED")?; + if !p.eat_keyword("BY") { + return Ok(MergeClauseKind::NotMatched); + } + if p.eat_keyword("SOURCE") { + return Ok(MergeClauseKind::NotMatchedBySource); + } + p.expect_keyword("TARGET")?; + Ok(MergeClauseKind::NotMatchedByTarget) +} + +fn parse_merge_clause<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let kind = parse_merge_clause_kind(p)?; + let predicate = if p.eat_keyword("AND") { + Some(p.parse_expr()?) + } else { + None + }; + p.expect_keyword("THEN")?; + let inserts = matches!( + kind, + MergeClauseKind::NotMatched | MergeClauseKind::NotMatchedByTarget + ); + let action = if p.eat_keyword("DO") { + p.expect_keyword("NOTHING")?; + MergeAction::DoNothing + } else if inserts { + p.expect_keyword("INSERT")?; + parse_merge_insert(p)? + } else if p.eat_keyword("DELETE") { + MergeAction::Delete + } else { + p.expect_keyword("UPDATE")?; + parse_merge_update(p)? + }; + Ok(MergeClause { + kind, + predicate, + action, + }) +} + +fn parse_merge_update<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("SET")?; + let assignments = if p.eat_op("*") { + None + } else { + Some(p.parse_comma_separated(D::parse_assignment)?) + }; + let predicate = super::parse_optional_where(p)?; + let delete_predicate = if p.eat_keyword("DELETE") { + p.expect_keyword("WHERE")?; + Some(p.parse_expr()?) + } else { + None + }; + Ok(MergeAction::Update { + assignments, + predicate, + delete_predicate, + }) +} + +fn parse_merge_insert<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_op("*") { + return Ok(MergeAction::InsertAll); + } + let columns = if p.eat_op("(") { + let columns = p.parse_comma_separated(parse_object_name)?; + p.expect_op(")")?; + columns + } else { + Vec::new() + }; + if D::eat_merge_insert_row(p) { + let predicate = super::parse_optional_where(p)?; + return Ok(MergeAction::InsertRow { columns, predicate }); + } + p.expect_keyword("VALUES")?; + let rows = p.parse_comma_separated(super::parse_values_row)?; + let predicate = super::parse_optional_where(p)?; + Ok(MergeAction::Insert { + columns, + rows, + predicate, + }) +} + +/// True at `DROP FUNCTION` or `DROP PROCEDURE`. +pub fn at_drop_function<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_keyword("DROP") && (next.is_word("FUNCTION") || next.is_word("PROCEDURE")) +} + +pub fn parse_routine_arg<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mode = ["IN", "OUT", "INOUT", "VARIADIC"] + .into_iter() + .find(|mode| p.eat_keyword(mode)); + // A name is only present when a type follows it, and these words continue + // a multi-word type instead. + let next = p.peek_nth(1); + let continues_type = ["PRECISION", "VARYING", "WITH", "WITHOUT"] + .iter() + .any(|word| next.is_word(word)); + let name = if p.at_ident() && is_name_token(next) && !continues_type { + Some(p.parse_ident()?) + } else { + None + }; + let data_type = D::parse_data_type(p)?; + let default = if p.eat_op("=") { + Some((true, p.parse_expr()?)) + } else if p.eat_keyword("DEFAULT") { + Some((false, p.parse_expr()?)) + } else { + None + }; + Ok(RoutineArg { + mode: mode.map(Cow::Borrowed), + name, + data_type, + default, + }) +} + +fn parse_routine_signature<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = parse_object_name(p)?; + let args = if !p.eat_op("(") { + None + } else if p.eat_op(")") { + Some(Vec::new()) + } else { + let args = p.parse_comma_separated(parse_routine_arg)?; + p.expect_op(")")?; + Some(args) + }; + Ok(RoutineSignature { name, args }) +} + +/// Parses `DROP {FUNCTION | PROCEDURE} [IF EXISTS] signature, ...`. +pub fn parse_drop_routine<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("DROP")?; + let procedure = p.at_keyword("PROCEDURE"); + p.advance(); + let if_exists = super::parse_if_exists(p); + let routines = p.parse_comma_separated(parse_routine_signature)?; + let behavior = super::parse_drop_behavior(p); + Ok(DropRoutine { + procedure, + if_exists, + routines, + behavior, + }) +} + +/// Consumes one of `kinds` as the object type of a `DROP`. +pub fn eat_drop_object_type<'a, D: Dialect>( + p: &mut Parser<'a, D>, + kinds: &[&'static str], +) -> Option> { + kinds + .iter() + .find(|kind| p.eat_keyword(kind)) + .map(|kind| ObjectType::Named((*kind).into())) +} diff --git a/sqlparser_v2/src/grammar/ddl.rs b/sqlparser_v2/src/grammar/ddl.rs new file mode 100644 index 0000000000..c0a165fd51 --- /dev/null +++ b/sqlparser_v2/src/grammar/ddl.rs @@ -0,0 +1,1145 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `CREATE`, `DROP` and `ALTER`: tables, views, indexes, sequences and columns. + +use super::*; +use crate::PResult; +use crate::ast::StatementKind; +use crate::dialect::Dialect; +use crate::lexer::TokenKind; +use crate::parser::Parser; +use std::borrow::Cow; + +fn parse_signed_number<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let sign = if p.eat_op("-") { + "-" + } else if p.eat_op("+") { + "+" + } else { + "" + }; + let token = p.expect_kind(TokenKind::Number, "a number")?; + Ok(SignedNumber { + sign: sign.into(), + digits: token.text.into(), + }) +} + +/// Parses one sequence option, or returns `None` at something else. +fn parse_sequence_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let option = if p.eat_keyword("INCREMENT") { + let by = p.eat_keyword("BY"); + SequenceOption::Increment { + by, + value: parse_signed_number(p)?, + } + } else if p.eat_keyword("MINVALUE") { + SequenceOption::MinValue(Some(parse_signed_number(p)?)) + } else if p.eat_keyword("MAXVALUE") { + SequenceOption::MaxValue(Some(parse_signed_number(p)?)) + } else if p.eat_keyword("START") { + let with = p.eat_keyword("WITH"); + SequenceOption::Start { + with, + value: parse_signed_number(p)?, + } + } else if p.eat_keyword("CACHE") { + SequenceOption::Cache(parse_signed_number(p)?) + } else if p.eat_keyword("CYCLE") { + SequenceOption::Cycle(true) + } else if p.at_keyword("NO") { + p.advance(); + if p.eat_keyword("MINVALUE") { + SequenceOption::MinValue(None) + } else if p.eat_keyword("MAXVALUE") { + SequenceOption::MaxValue(None) + } else { + p.expect_keyword("CYCLE")?; + SequenceOption::Cycle(false) + } + } else if p.eat_keyword("OWNED") { + p.expect_keyword("BY")?; + SequenceOption::OwnedBy(parse_object_name(p)?) + } else { + return Ok(None); + }; + Ok(Some(option)) +} + +fn parse_sequence_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut options = Vec::new(); + while let Some(option) = parse_sequence_option(p)? { + options.push(option); + } + Ok(options) +} + +/// Parses what follows `CREATE [TEMPORARY] SEQUENCE`. +pub fn parse_create_sequence<'a, D: Dialect>( + p: &mut Parser<'a, D>, + temporary: bool, +) -> PResult> { + let if_not_exists = super::parse_if_not_exists(p)?; + let name = parse_object_name(p)?; + let data_type = if p.eat_keyword("AS") { + Some(D::parse_data_type(p)?) + } else { + None + }; + let options = parse_sequence_options(p)?; + Ok(CreateSequence { + temporary, + if_not_exists, + name, + data_type, + options, + }) +} + +/// Parses what follows `GENERATED`. +pub fn parse_generated<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let when = if p.eat_keyword("ALWAYS") { + Some(GeneratedWhen::Always) + } else if p.eat_keyword("BY") { + p.expect_keyword("DEFAULT")?; + Some(GeneratedWhen::ByDefault) + } else { + None + }; + p.expect_keyword("AS")?; + let kind = if p.eat_keyword("IDENTITY") { + let options = if p.eat_op("(") { + let options = parse_sequence_options(p)?; + p.expect_op(")")?; + Some(options) + } else { + None + }; + GeneratedKind::Identity(options) + } else { + p.expect_op("(")?; + let expr = p.parse_expr()?; + p.expect_op(")")?; + let storage = if p.eat_keyword("STORED") { + Some(GeneratedStorage::Stored) + } else if p.eat_keyword("VIRTUAL") { + Some(GeneratedStorage::Virtual) + } else { + None + }; + GeneratedKind::Expr { expr, storage } + }; + Ok(Generated { when, kind }) +} + +/// Rejects a list that sets the same kind of attribute twice. +pub fn check_constraint_attributes<'a, D: Dialect>( + p: &Parser<'a, D>, + attributes: impl Iterator, +) -> PResult<()> { + let mut seen = Vec::new(); + for attribute in attributes { + let kind = std::mem::discriminant(&attribute); + if seen.contains(&kind) { + return Err(p.expected("each constraint attribute at most once")); + } + seen.push(kind); + } + Ok(()) +} + +/// Parses a constraint attribute, or returns `None` at something else. +pub fn parse_constraint_attribute<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let next = p.peek_nth(1); + let attribute = if p.eat_keyword("DEFERRABLE") { + ConstraintAttribute::Deferrable(true) + } else if p.at_keyword("NOT") && next.is_word("DEFERRABLE") { + p.advance(); + p.advance(); + ConstraintAttribute::Deferrable(false) + } else if p.eat_keyword("INITIALLY") { + if p.eat_keyword("DEFERRED") { + ConstraintAttribute::InitiallyDeferred(true) + } else { + p.expect_keyword("IMMEDIATE")?; + ConstraintAttribute::InitiallyDeferred(false) + } + } else if p.eat_keyword("ENFORCED") { + ConstraintAttribute::Enforced(true) + } else if p.at_keyword("NOT") && next.is_word("ENFORCED") { + p.advance(); + p.advance(); + ConstraintAttribute::Enforced(false) + } else if p.at_keyword("NOT") && next.is_word("VALID") { + p.advance(); + p.advance(); + ConstraintAttribute::NotValid + } else if p.at_keyword("NO") && next.is_word("INHERIT") { + p.advance(); + p.advance(); + ConstraintAttribute::NoInherit + } else { + return Ok(None); + }; + Ok(Some(attribute)) +} + +/// Parses what follows `CREATE ... TABLE`. +pub fn parse_create_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + let if_not_exists = parse_if_not_exists(p)?; + let name = parse_object_name(p)?; + parse_create_table_after_name(p, flags, if_not_exists, name) +} + +/// Parses what follows the table's name in `CREATE ... TABLE`. +pub fn parse_create_table_after_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, + if_not_exists: bool, + name: ObjectName<'a>, +) -> PResult> { + let (columns, constraints) = if p.at_op("(") { + parse_columns(p)? + } else { + (Vec::new(), Vec::new()) + }; + + let query = if p.eat_keyword("AS") { + Some(Box::new(D::parse_create_table_query(p)?)) + } else { + None + }; + if columns.is_empty() && query.is_none() { + return Err(p.expected("column definitions or AS")); + } + + Ok(CreateTable { + or_replace: flags.or_replace, + temporary: flags.temporary, + name, + if_not_exists, + columns, + constraints, + query, + }) +} + +/// The columns and constraints in `(...)`, which is at the cursor. +pub type ColumnList<'a, X> = (Vec>, Vec>); + +/// Parses a parenthesized list of column definitions and constraints. +pub fn parse_columns<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("(")?; + let mut columns = Vec::new(); + let mut constraints = Vec::new(); + loop { + if let Some(constraint) = D::parse_table_constraint(p)? { + constraints.push(constraint); + } else { + columns.push(D::parse_column_def(p)?); + } + if !p.eat_op(",") { + break; + } + } + p.expect_op(")")?; + Ok((columns, constraints)) +} + +/// Parses a table constraint, or returns `None` if this element is a column. +/// The words that start constraints are not reserved, so they are only read +/// as keywords when what follows confirms it. +pub fn parse_table_constraint<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let third = p.peek_nth(2); + let named = p.at_keyword("CONSTRAINT") + && (third.is_word("PRIMARY") + || third.is_word("UNIQUE") + || third.is_word("CHECK") + || third.is_word("FOREIGN")); + let name = if named { + p.advance(); + Some(p.parse_ident()?) + } else { + None + }; + + let mut nulls_distinct = None; + let next = p.peek_nth(1); + let kind = if p.at_keyword("PRIMARY") && next.is_word("KEY") { + p.advance(); + p.advance(); + match parse_using_index(p)? { + Some(index) => TableConstraintKind::PrimaryKeyUsingIndex(index), + None => TableConstraintKind::PrimaryKey(parse_ident_list(p)?), + } + } else if p.at_keyword("UNIQUE") + && (next.is_op("(") || next.is_word("NULLS") || next.is_word("USING")) + { + p.advance(); + nulls_distinct = parse_nulls_distinct(p)?; + match parse_using_index(p)? { + Some(index) => TableConstraintKind::UniqueUsingIndex(index), + None => TableConstraintKind::Unique(parse_ident_list(p)?), + } + } else if p.at_keyword("CHECK") && p.peek_nth(1).is_op("(") { + p.advance(); + TableConstraintKind::Check(parse_parenthesized_expr(p)?) + } else if p.at_keyword("FOREIGN") && p.peek_nth(1).is_word("KEY") { + p.advance(); + p.advance(); + let columns = parse_ident_list(p)?; + p.expect_keyword("REFERENCES")?; + let references = parse_foreign_key_ref(p)?; + TableConstraintKind::ForeignKey { + index_name: None, + columns, + references, + } + } else if named { + return Err(p.expected("a table constraint")); + } else { + return Ok(None); + }; + let include = if p.eat_keyword("INCLUDE") { + parse_ident_list(p)? + } else { + Vec::new() + }; + let mut attributes = Vec::new(); + while let Some(attribute) = parse_constraint_attribute(p)? { + attributes.push(attribute); + } + check_constraint_attributes(p, attributes.iter().copied())?; + Ok(Some(TableConstraint { + name, + kind, + include, + nulls_distinct, + attributes, + })) +} + +/// Parses `USING INDEX name` if present. +fn parse_using_index<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if !(p.at_keyword("USING") && p.peek_nth(1).is_word("INDEX")) { + return Ok(None); + } + p.advance(); + p.advance(); + p.parse_ident().map(Some) +} + +/// Parses `NULLS [NOT] DISTINCT` if present. +pub fn parse_nulls_distinct<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.eat_keyword("NULLS") { + return Ok(None); + } + let negated = p.eat_keyword("NOT"); + p.expect_keyword("DISTINCT")?; + Ok(Some(!negated)) +} + +fn parse_parenthesized_expr<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("(")?; + let expr = p.parse_expr()?; + p.expect_op(")")?; + Ok(expr) +} + +/// Parses what follows `REFERENCES`. +pub fn parse_foreign_key_ref<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let table = parse_object_name(p)?; + let columns = if p.at_op("(") { + parse_ident_list(p)? + } else { + Vec::new() + }; + let match_kind = if p.eat_keyword("MATCH") { + let kind = ["FULL", "PARTIAL", "SIMPLE"] + .into_iter() + .find(|kind| p.eat_keyword(kind)); + Some(kind.ok_or_else(|| p.expected("FULL, PARTIAL or SIMPLE"))?) + } else { + None + }; + let (mut on_delete, mut on_update) = (None, None); + while p.at_keyword("ON") { + p.advance(); + if on_delete.is_none() && p.eat_keyword("DELETE") { + on_delete = Some(parse_referential_action(p)?); + } else if on_update.is_none() { + p.expect_keyword("UPDATE")?; + on_update = Some(parse_referential_action(p)?); + } else { + return Err(p.expected("at most one ON DELETE and one ON UPDATE")); + } + } + Ok(ForeignKeyRef { + table, + columns, + match_kind: match_kind.map(Cow::Borrowed), + on_delete, + on_update, + }) +} + +fn parse_referential_action<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + if p.eat_keyword("CASCADE") { + Ok(ReferentialAction::Cascade) + } else if p.eat_keyword("RESTRICT") { + Ok(ReferentialAction::Restrict) + } else if p.eat_keyword("NO") { + p.expect_keyword("ACTION")?; + Ok(ReferentialAction::NoAction) + } else { + p.expect_keyword("SET")?; + if p.eat_keyword("DEFAULT") { + Ok(ReferentialAction::SetDefault) + } else { + p.expect_keyword("NULL")?; + Ok(ReferentialAction::SetNull) + } + } +} + +pub fn parse_column_def<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + parse_column_def_after_name(p, name) +} + +/// Parses a column definition's type and options. +pub fn parse_column_def_after_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Ident<'a>, +) -> PResult> { + let data_type = D::parse_data_type(p)?; + let mut options = Vec::new(); + while let Some(option) = D::parse_column_option(p)? { + options.push(option); + } + check_column_attributes(p, &options)?; + Ok(ColumnDef { + name, + data_type, + options, + }) +} + +/// Checks that no constraint in a column's options repeats an attribute. +pub fn check_column_attributes<'a, D: Dialect>( + p: &Parser<'a, D>, + options: &[ColumnOption<'a, D::Ext>], +) -> PResult<()> { + // Attributes belong to the constraint before them, so each run is separate. + for run in options.split(|option| !matches!(option, ColumnOption::Attribute(_))) { + check_constraint_attributes( + p, + run.iter().filter_map(|option| match option { + ColumnOption::Attribute(attribute) => Some(*attribute), + _ => None, + }), + )?; + } + Ok(()) +} + +pub fn parse_column_option<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if let Some(attribute) = parse_constraint_attribute(p)? { + return Ok(Some(ColumnOption::Attribute(attribute))); + } + let option = if p.eat_keyword("COLLATE") { + ColumnOption::Collate(parse_object_name(p)?) + } else if p.eat_keyword("GENERATED") { + ColumnOption::Generated(Box::new(parse_generated(p)?)) + } else if p.eat_keyword("NOT") { + p.expect_keyword("NULL")?; + ColumnOption::NotNull + } else if p.eat_keyword("NULL") { + ColumnOption::Null + } else if p.eat_keyword("PRIMARY") { + p.expect_keyword("KEY")?; + ColumnOption::PrimaryKey + } else if p.eat_keyword("UNIQUE") { + ColumnOption::Unique + } else if p.at_keyword("CHECK") && p.peek_nth(1).is_op("(") { + p.advance(); + ColumnOption::Check(parse_parenthesized_expr(p)?) + } else if p.eat_keyword("REFERENCES") { + ColumnOption::References(parse_foreign_key_ref(p)?) + } else if p.eat_keyword("DEFAULT") { + ColumnOption::Default(p.parse_expr()?) + } else { + return Ok(None); + }; + Ok(Some(option)) +} + +pub fn parse_data_type<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + parse_data_type_after_name(p, name) +} + +/// Parses the rest of a data type, with its name already read. +pub fn parse_data_type_after_name<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: Ident<'a>, +) -> PResult> { + if name.quote.is_none() && name.text.eq_ignore_ascii_case("INTERVAL") && p.at_op("(") { + return Err(p.expected("a plain INTERVAL type")); + } + let mut suffix = DataTypeSuffix::None; + if p.eat_keyword("PRECISION") { + suffix = DataTypeSuffix::Precision; + } else if p.eat_keyword("VARYING") { + suffix = DataTypeSuffix::Varying; + } + let args = if p.eat_op("(") { + let args = p.parse_comma_separated(|p| parse_number_text(p).map(Cow::Borrowed))?; + p.expect_op(")")?; + args + } else { + Vec::new() + }; + if suffix == DataTypeSuffix::None && p.peek_nth(1).is_word("TIME") { + if p.eat_keyword("WITH") { + suffix = DataTypeSuffix::WithTimeZone; + } else if p.eat_keyword("WITHOUT") { + suffix = DataTypeSuffix::WithoutTimeZone; + } + if suffix != DataTypeSuffix::None { + p.expect_keyword("TIME")?; + p.expect_keyword("ZONE")?; + } + } + let array = parse_array_suffix(p)?; + Ok(DataType { + qualifier: Vec::new(), + name, + angle: None, + args, + suffix, + array, + }) +} + +/// Parses `[n]` or `[]`, with the cursor on the `[`. +fn parse_array_dimension<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("[")?; + if p.eat_op("]") { + return Ok(None); + } + let size = parse_number_text(p)?; + p.expect_op("]")?; + Ok(Some(size)) +} + +pub fn parse_array_suffix<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("ARRAY") { + let size = if p.at_op("[") { + parse_array_dimension(p)? + } else { + None + }; + return Ok(ArrayType::Keyword(size.map(Cow::Borrowed))); + } + Ok(ArrayType::None) +} + +/// Parses `[]`, `[3][4]` and so on, for dialects whose array types use them. +pub fn parse_array_brackets<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut dimensions = Vec::new(); + while p.at_op("[") { + dimensions.push(parse_array_dimension(p)?); + } + Ok(ArrayType::Brackets( + dimensions + .into_iter() + .map(|size| size.map(Cow::Borrowed)) + .collect(), + )) +} + +pub fn parse_number_text<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.expect_kind(TokenKind::Number, "a number")?; + Ok(token.text) +} + +/// Consumes `IF NOT EXISTS` and returns whether it was present. +pub fn parse_if_not_exists<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + let found = p.at_keyword("IF") && p.peek_nth(1).is_word("NOT"); + if found { + p.advance(); + p.advance(); + p.expect_keyword("EXISTS")?; + } + Ok(found) +} + +pub fn parse_or_replace<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + let or_replace = p.eat_keyword("OR"); + if or_replace { + p.expect_keyword("REPLACE")?; + } + Ok(or_replace) +} + +pub fn parse_if_exists<'a, D: Dialect>(p: &mut Parser<'a, D>) -> bool { + let found = p.at_keyword("IF") && p.peek_nth(1).is_word("EXISTS"); + if found { + p.advance(); + p.advance(); + } + found +} + +pub fn parse_drop_behavior<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option { + if p.eat_keyword("CASCADE") { + Some(DropBehavior::Cascade) + } else if p.eat_keyword("RESTRICT") { + Some(DropBehavior::Restrict) + } else { + None + } +} + +/// Reads the modifiers after `CREATE` and dispatches on the object type. +pub fn parse_create<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("CREATE")?; + let or_replace = parse_or_replace(p)?; + let temporary = p.eat_keyword("TEMPORARY") || p.eat_keyword("TEMP"); + let flags = CreateFlags { + or_replace, + temporary, + }; + + if p.eat_keyword("TABLE") { + return D::parse_create_table(p, flags) + .map(|s| StatementKind::CreateTable(Box::new(s)).into()); + } + if p.at_keyword("VIEW") || p.at_keyword("MATERIALIZED") { + return D::parse_create_view(p, flags) + .map(|s| StatementKind::CreateView(Box::new(s)).into()); + } + if !flags.or_replace && p.eat_keyword("SEQUENCE") { + return parse_create_sequence(p, flags.temporary) + .map(|s| StatementKind::CreateSequence(Box::new(s)).into()); + } + if p.eat_keyword("SCHEMA") { + return D::parse_create_schema(p, flags) + .map(|s| StatementKind::CreateSchema(Box::new(s)).into()); + } + if let Some(statement) = D::parse_create_extension(p, flags)? { + return Ok(statement); + } + if flags != CreateFlags::default() { + return Err(p.expected("TABLE or VIEW")); + } + if p.at_keyword("INDEX") || p.at_keyword("UNIQUE") { + return D::parse_create_index(p).map(|s| StatementKind::CreateIndex(Box::new(s)).into()); + } + if p.eat_keyword("DATABASE") { + let if_not_exists = parse_if_not_exists(p)?; + let name = parse_object_name(p)?; + return Ok(StatementKind::CreateDatabase(Box::new(CreateDatabase { + if_not_exists, + name, + })) + .into()); + } + Err(p.expected("an object type after CREATE")) +} + +/// Parses what follows `CREATE SCHEMA`, for a dialect with only the plain form. +pub fn parse_create_schema<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + if flags != CreateFlags::default() { + return Err(p.expected("TABLE or VIEW")); + } + parse_create_schema_body(p, flags) +} + +/// Parses `[IF NOT EXISTS] name`, the part of `CREATE SCHEMA` every dialect has. +pub fn parse_create_schema_body<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + let if_not_exists = parse_if_not_exists(p)?; + let name = parse_object_name(p)?; + Ok(CreateSchema { + or_replace: flags.or_replace, + if_not_exists, + name: Some(name), + authorization: None, + clone: None, + }) +} + +/// Parses `CREATE SCHEMA` with `AUTHORIZATION`. If `named`, the owner can also +/// follow a schema name; otherwise only the form with no name is allowed. +pub fn parse_create_schema_authorization<'a, D: Dialect>( + p: &mut Parser<'a, D>, + named: bool, +) -> PResult> { + if p.at_keyword("AUTHORIZATION") && !p.peek_nth(1).is_op(".") { + p.advance(); + let owner = p.parse_ident()?; + return Ok(CreateSchema { + or_replace: false, + if_not_exists: false, + name: None, + authorization: Some(owner), + clone: None, + }); + } + let mut schema = parse_create_schema_body(p, CreateFlags::default())?; + if named && p.eat_keyword("AUTHORIZATION") { + schema.authorization = Some(p.parse_ident()?); + } + Ok(schema) +} + +/// Parses `ALTER VIEW name [(columns)] AS query`. +pub fn parse_alter_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, + allow_columns: bool, +) -> PResult> { + p.expect_keyword("ALTER")?; + p.expect_keyword("VIEW")?; + let name = parse_object_name(p)?; + let columns = if allow_columns && p.at_op("(") { + parse_ident_list(p)? + } else { + Vec::new() + }; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + Ok(AlterView { + name, + columns, + query, + }) +} + +/// Parses `CREATE [OR REPLACE] ROLE [IF NOT EXISTS] name, ...`. A list of names +/// is only read if `many`; `CREATE` has been consumed. Returns `None` at +/// anything other than `ROLE`. +pub fn parse_create_role<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, + many: bool, +) -> PResult>> { + if flags.temporary || !p.eat_keyword("ROLE") { + return Ok(None); + } + let if_not_exists = parse_if_not_exists(p)?; + let names = if many { + p.parse_comma_separated(parse_object_name)? + } else { + vec![parse_object_name(p)?] + }; + Ok(Some( + StatementKind::CreateRole(Box::new(CreateRole { + or_replace: flags.or_replace, + if_not_exists, + names, + })) + .into(), + )) +} + +/// Parses `ANALYZE [TABLE] [names]`. +pub fn parse_analyze<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("ANALYZE")?; + let table_keyword = p.eat_keyword("TABLE"); + let names = if p.at_ident() { + p.parse_comma_separated(parse_object_name)? + } else { + Vec::new() + }; + Ok(StatementKind::Analyze(Box::new(Analyze { + table_keyword, + names, + })) + .into()) +} + +/// Parses `ALTER INDEX name RENAME TO new_name`, the one form several dialects share. +pub fn parse_alter_index_rename<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("ALTER")?; + p.expect_keyword("INDEX")?; + let name = parse_object_name(p)?; + p.expect_keyword("RENAME")?; + p.expect_keyword("TO")?; + let new_name = parse_object_name(p)?; + Ok(StatementKind::AlterIndexRename { name, new_name }.into()) +} + +pub fn at_alter_view<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("ALTER") && p.peek_nth(1).is_word("VIEW") +} + +pub fn parse_create_view<'a, D: Dialect>( + p: &mut Parser<'a, D>, + flags: CreateFlags, +) -> PResult> { + let materialized = p.eat_keyword("MATERIALIZED"); + p.expect_keyword("VIEW")?; + let if_not_exists = parse_if_not_exists(p)?; + let name = parse_object_name(p)?; + let columns = if p.at_op("(") { + parse_ident_list(p)? + } else { + Vec::new() + }; + p.expect_keyword("AS")?; + let query = Box::new(D::parse_query(p)?); + Ok(CreateView { + or_replace: flags.or_replace, + temporary: flags.temporary, + materialized, + if_not_exists, + name, + columns, + with: Vec::new(), + query, + no_schema_binding: false, + }) +} + +pub fn parse_create_index<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let unique = p.eat_keyword("UNIQUE"); + p.expect_keyword("INDEX")?; + let IndexFlags { + concurrently, + asynchronous, + } = D::parse_index_flags(p); + let if_not_exists = parse_if_not_exists(p)?; + let name = if p.at_keyword("ON") { + None + } else { + Some(parse_object_name(p)?) + }; + let using_before_on = parse_optional_using(p)?; + p.expect_keyword("ON")?; + let table = parse_object_name(p)?; + if using_before_on.is_some() && p.at_keyword("USING") { + return Err(p.expected("one USING before the column list")); + } + let using = parse_optional_using(p)?; + p.expect_op("(")?; + let columns = p.parse_comma_separated(D::parse_index_column)?; + p.expect_op(")")?; + let trailing_using = parse_optional_using(p)?; + let include = if p.eat_keyword("INCLUDE") { + parse_ident_list(p)? + } else { + Vec::new() + }; + let nulls_distinct = parse_nulls_distinct(p)?; + let with = D::parse_index_storage(p)?; + let predicate = parse_optional_where(p)?; + let settings = D::parse_index_settings(p)?; + Ok(CreateIndex { + unique, + concurrently, + asynchronous, + if_not_exists, + name, + using_before_on, + table, + using, + columns, + trailing_using, + include, + nulls_distinct, + with, + predicate, + settings: settings + .into_iter() + .map(|(k, v)| (k.into(), v.into())) + .collect(), + }) +} + +pub fn parse_optional_using<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.eat_keyword("USING") { + p.parse_ident().map(Some) + } else { + Ok(None) + } +} + +pub fn parse_index_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let expr = p.parse_expr()?; + let operator_class = if p.at_ident() && !p.at_keyword("NULLS") { + Some(parse_object_name(p)?) + } else { + None + }; + let (asc, nulls_first) = parse_order_by_modifiers(p)?; + Ok(IndexColumn { + item: OrderByItem { + using: None, + expr, + asc, + nulls_first, + ext: Default::default(), + }, + operator_class, + }) +} + +/// Parses `WITH (name = value, name)`, for dialects with storage parameters. +pub fn parse_index_storage_parameters<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if !p.eat_keyword("WITH") { + return Ok(Vec::new()); + } + parse_storage_parameter_list(p) +} + +/// Parses `(name = value, name)`, in which a name can be qualified. +pub fn parse_storage_parameter_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_op("(")?; + let parameters = p.parse_comma_separated(|p| { + let mut parts = vec![p.parse_name_part()?]; + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + let value = if p.eat_op("=") { + Some(p.parse_expr()?) + } else { + None + }; + Ok((ObjectName { parts }, value)) + })?; + p.expect_op(")")?; + Ok(parameters) +} + +pub fn parse_drop<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("DROP")?; + let temporary = D::eat_drop_temporary(p); + let object_type = if p.eat_keyword("TABLE") { + ObjectType::Table + } else if p.eat_keyword("VIEW") { + ObjectType::View + } else if p.eat_keyword("MATERIALIZED") { + p.expect_keyword("VIEW")?; + ObjectType::MaterializedView + } else if p.eat_keyword("INDEX") { + ObjectType::Index + } else if p.eat_keyword("SCHEMA") { + ObjectType::Schema + } else if p.eat_keyword("DATABASE") { + ObjectType::Database + } else if p.eat_keyword("SEQUENCE") { + ObjectType::Sequence + } else if let Some(object_type) = eat_drop_object_type(p, &["ROLE", "USER"]) { + object_type + } else if let Some(object_type) = D::parse_drop_object_type(p) { + object_type + } else { + return Err(p.expected("an object type after DROP")); + }; + let if_exists = parse_if_exists(p); + let names = p.parse_comma_separated(parse_object_name)?; + let on = if (matches!(object_type, ObjectType::Index) + || matches!(&object_type, ObjectType::Named(name) if name == "TRIGGER" || name == "POLICY")) + && p.eat_keyword("ON") + { + Some(parse_object_name(p)?) + } else { + None + }; + if object_type == ObjectType::Named("POLICY".into()) && on.is_none() { + return Err(p.expected("ON and the policy's table")); + } + let behavior = parse_drop_behavior(p); + let purge = D::eat_drop_purge(p); + Ok(DropObject { + temporary, + object_type, + if_exists, + names, + on, + behavior, + purge, + }) +} + +pub fn parse_truncate<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("TRUNCATE")?; + let table_keyword = p.eat_keyword("TABLE"); + let if_exists = parse_if_exists(p); + let names = p.parse_comma_separated(parse_object_name)?; + Ok(Truncate { + table_keyword, + if_exists, + names, + }) +} + +pub fn parse_alter_table<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("ALTER")?; + p.expect_keyword("TABLE")?; + let if_exists = parse_if_exists(p); + let only = D::parse_alter_table_only(p); + let name = parse_object_name(p)?; + let operations = p.parse_comma_separated(D::parse_alter_table_op)?; + Ok(AlterTable { + if_exists, + only, + name, + operations, + }) +} + +pub fn parse_alter_table_op<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("ADD") { + if let Some(constraint) = D::parse_table_constraint(p)? { + return Ok(AlterTableOp::AddConstraint(constraint)); + } + let column_keyword = p.eat_keyword("COLUMN"); + let if_not_exists = D::parse_add_column_if_not_exists(p)?; + let column = D::parse_column_def(p)?; + return Ok(AlterTableOp::AddColumn { + column_keyword, + if_not_exists, + column, + position: None, + }); + } + if p.eat_keyword("DROP") { + if p.eat_keyword("CONSTRAINT") { + let if_exists = parse_if_exists(p); + let name = p.parse_ident()?; + let behavior = parse_drop_behavior(p); + return Ok(AlterTableOp::DropConstraint { + if_exists, + name, + behavior, + }); + } + let column_keyword = p.eat_keyword("COLUMN"); + let if_exists = parse_if_exists(p); + let name = p.parse_ident()?; + let behavior = parse_drop_behavior(p); + return Ok(AlterTableOp::DropColumn { + column_keyword, + if_exists, + name, + behavior, + }); + } + if p.eat_keyword("RENAME") { + if p.eat_keyword("TO") { + return parse_object_name(p).map(AlterTableOp::RenameTable); + } + p.eat_keyword("COLUMN"); + let old = p.parse_ident()?; + p.expect_keyword("TO")?; + let new = p.parse_ident()?; + return Ok(AlterTableOp::RenameColumn { old, new }); + } + if p.eat_keyword("ALTER") { + let column_keyword = p.eat_keyword("COLUMN"); + let name = p.parse_ident()?; + let action = parse_alter_column_action(p)?; + return Ok(AlterTableOp::AlterColumn { + column_keyword, + name, + action, + }); + } + Err(p.expected("an ALTER TABLE operation")) +} + +fn parse_alter_column_action<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("ADD") && p.peek_nth(1).is_word("GENERATED") { + p.advance(); + p.advance(); + let generated = parse_generated(p)?; + if !matches!(generated.kind, GeneratedKind::Identity(_)) { + return Err(p.expected("AS IDENTITY")); + } + return Ok(AlterColumnAction::AddGenerated(Box::new(generated))); + } + if p.eat_keyword("TYPE") { + let data_type = D::parse_data_type(p)?; + let using = D::parse_alter_type_using(p)?; + return Ok(AlterColumnAction::SetType { + data_type, + set_data: false, + using, + }); + } + if p.eat_keyword("DROP") { + if p.eat_keyword("DEFAULT") { + return Ok(AlterColumnAction::DropDefault); + } + p.expect_keyword("NOT")?; + p.expect_keyword("NULL")?; + return Ok(AlterColumnAction::DropNotNull); + } + p.expect_keyword("SET")?; + if p.eat_keyword("DEFAULT") { + return p.parse_expr().map(AlterColumnAction::SetDefault); + } + if p.eat_keyword("DATA") { + p.expect_keyword("TYPE")?; + let data_type = D::parse_data_type(p)?; + let using = D::parse_alter_type_using(p)?; + return Ok(AlterColumnAction::SetType { + data_type, + set_data: true, + using, + }); + } + p.expect_keyword("NOT")?; + p.expect_keyword("NULL")?; + Ok(AlterColumnAction::SetNotNull) +} diff --git a/sqlparser_v2/src/grammar/dml.rs b/sqlparser_v2/src/grammar/dml.rs new file mode 100644 index 0000000000..c08a598d3b --- /dev/null +++ b/sqlparser_v2/src/grammar/dml.rs @@ -0,0 +1,203 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `INSERT`, `UPDATE` and `DELETE`. + +use super::*; + +/// True at a `(` that starts a column list rather than a parenthesized query. +pub fn at_column_list<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_op("(") && !next.is_op("(") && !next.is_word("SELECT") && !next.is_word("WITH") +} + +pub fn parse_insert<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("INSERT")?; + parse_insert_after_verb(p) +} + +/// Parses an `INSERT` once its opening keyword has been read. +pub fn parse_insert_after_verb<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let modifiers = D::parse_insert_modifiers(p)?; + let into = D::parse_insert_into(p)?; + let table = parse_object_name(p)?; + let columns = D::parse_insert_columns(p)?; + let output = D::parse_output_clause(p)?; + let source = D::parse_insert_source(p)?; + check_default_values(p, &columns, &source)?; + let returning = D::parse_returning(p)?; + Ok(Insert { + modifiers, + into, + table, + columns, + output, + source, + returning, + }) +} + +/// Parses the optional column list of an `INSERT`. +pub fn parse_insert_columns<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if at_column_list(p) { + parse_ident_list(p) + } else { + Ok(Vec::new()) + } +} + +/// Parses `VALUES` rows or a query. +pub fn parse_insert_source<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("VALUES") { + return Ok(InsertSource::Values(parse_values_rows(p)?)); + } + Ok(InsertSource::Query(Box::new(D::parse_query(p)?))) +} + +/// Rejects `DEFAULT VALUES` after a column list. +pub fn check_default_values<'a, D: Dialect>( + p: &Parser<'a, D>, + columns: &[Ident<'a>], + source: &InsertSource<'a, D::Ext>, +) -> PResult<()> { + if !columns.is_empty() && matches!(source, InsertSource::DefaultValues) { + return Err(p.expected("no column list before DEFAULT VALUES")); + } + Ok(()) +} + +/// Parses `DEFAULT VALUES` or the usual source, for dialects that have it. +pub fn parse_insert_source_with_default<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("DEFAULT") && p.peek_nth(1).is_word("VALUES") { + p.advance(); + p.advance(); + return Ok(InsertSource::DefaultValues); + } + parse_insert_source(p) +} + +/// Parses `FROM` tables, for an `UPDATE` that has them. +pub fn parse_optional_update_from<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("FROM") { + D::parse_from_list(p) + } else { + Ok(Vec::new()) + } +} + +/// Parses `USING` tables, for a `DELETE` that has them. +pub fn parse_optional_delete_using<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("USING") { + D::parse_from_list(p) + } else { + Ok(Vec::new()) + } +} + +/// Parses rows, reserving each one's space from the width of the one before. +fn parse_values_rows<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>>> { + let mut width = 1; + p.parse_comma_separated(|p| { + let row = parse_row_of_width(p, width)?; + width = row.len(); + Ok(row) + }) +} + +pub fn parse_values_row<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + parse_row_of_width(p, 1) +} + +fn parse_row_of_width<'a, D: Dialect>( + p: &mut Parser<'a, D>, + width: usize, +) -> PResult>> { + p.expect_op("(")?; + let mut row = Vec::with_capacity(width); + row.push(p.parse_expr()?); + while p.eat_op(",") { + row.push(p.parse_expr()?); + } + p.expect_op(")")?; + Ok(row) +} + +pub fn parse_update<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("UPDATE")?; + let table = p.parse_table_ref()?; + let before_set = D::parse_update_from_before_set(p)?; + p.expect_keyword("SET")?; + let assignments = p.parse_comma_separated(D::parse_assignment)?; + let from_before_set = !before_set.is_empty(); + let from = if from_before_set { + before_set + } else { + D::parse_update_from_after_set(p)? + }; + let output = D::parse_output_clause(p)?; + let selection = parse_optional_where(p)?; + let returning = D::parse_returning(p)?; + Ok(Update { + table, + joins: Vec::new(), + assignments, + from, + from_before_set, + output, + selection, + order_by: Vec::new(), + limit: None, + returning, + }) +} + +pub fn parse_assignment<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let target = parse_object_name(p)?; + p.expect_op("=")?; + let value = p.parse_expr()?; + Ok(Assignment { target, value }) +} + +pub fn parse_delete<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("DELETE")?; + p.expect_keyword("FROM")?; + let table = p.parse_table_ref()?; + let using = D::parse_delete_using(p)?; + let output = D::parse_output_clause(p)?; + let selection = parse_optional_where(p)?; + let returning = D::parse_returning(p)?; + Ok(Delete { + table, + multi: None, + using, + output, + selection, + order_by: Vec::new(), + limit: None, + returning, + }) +} diff --git a/sqlparser_v2/src/grammar/expr.rs b/sqlparser_v2/src/grammar/expr.rs new file mode 100644 index 0000000000..95bb1839c0 --- /dev/null +++ b/sqlparser_v2/src/grammar/expr.rs @@ -0,0 +1,1435 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Expressions: function calls, windows, prefix and infix rules. + +use super::*; +use crate::ast::ExprKind; +use std::borrow::Cow; + +/// Parses an optional `FILTER (WHERE condition)` after a call. +pub fn parse_function_filter<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !(p.at_keyword("FILTER") && p.peek_nth(1).is_op("(") && p.peek_nth(2).is_word("WHERE")) { + return Ok(None); + } + p.advance(); + p.advance(); + p.advance(); + let condition = p.parse_expr()?; + p.expect_op(")")?; + Ok(Some(condition)) +} + +/// Parses an optional `IGNORE NULLS` or `RESPECT NULLS`. +pub fn parse_null_treatment<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option { + if !p.peek_nth(1).is_word("NULLS") { + return None; + } + let treatment = if p.eat_keyword("IGNORE") { + NullTreatment::Ignore + } else if p.eat_keyword("RESPECT") { + NullTreatment::Respect + } else { + return None; + }; + p.advance(); + Some(treatment) +} + +pub fn parse_function_call<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: ObjectName<'a>, +) -> PResult> { + p.expect_op("(")?; + let quantifier = parse_quantifier(p); + let args = D::parse_function_args(p, quantifier)?; + let on_overflow = D::parse_function_on_overflow(p)?; + let inner_null_treatment = D::parse_function_arg_null_treatment(p)?; + let order_by = parse_optional_order_by(p)?; + let separator = D::parse_function_separator(p)?; + p.expect_op(")")?; + + let within_group = if p.at_keyword("WITHIN") && p.peek_nth(1).is_word("GROUP") { + p.advance(); + p.advance(); + p.expect_op("(")?; + let items = parse_optional_order_by(p)?; + p.expect_op(")")?; + items + } else { + Vec::new() + }; + + let filter = D::parse_function_filter(p)?; + + let null_treatment = if inner_null_treatment.is_none() { + parse_null_treatment(p) + } else { + None + }; + + let over = D::parse_function_over(p)?; + + let is_plain = quantifier == SetQuantifier::None + && order_by.is_empty() + && within_group.is_empty() + && filter.is_none() + && null_treatment.is_none() + && inner_null_treatment.is_none() + && separator.is_none() + && on_overflow.is_none() + && over.is_none(); + let options = (!is_plain).then(|| { + Box::new(FunctionOptions { + parameters: Vec::new(), + quantifier, + order_by, + within_group, + filter, + null_treatment, + inner_null_treatment, + separator, + on_overflow, + over, + }) + }); + Ok(ExprKind::Function { + name, + args, + options, + } + .into()) +} + +/// Parses a call's arguments, after any quantifier. The list can be empty +/// only if there is no quantifier. +pub fn parse_function_args<'a, D: Dialect>( + p: &mut Parser<'a, D>, + quantifier: SetQuantifier, +) -> PResult>> { + if quantifier == SetQuantifier::None && D::at_empty_function_args(p) { + Ok(Vec::new()) + } else { + p.parse_comma_separated(D::parse_function_arg) + } +} + +/// Parses one argument of a function call. +pub fn parse_function_arg<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_op("*") { + Ok(FunctionArg::Wildcard) + } else if at_qualified_wildcard(p) { + parse_qualified_wildcard(p).map(FunctionArg::QualifiedWildcard) + } else if matches!(p.peek().kind, TokenKind::Word | TokenKind::QuotedIdent) + && p.peek_nth(1).is_op("=>") + { + let name = p.parse_name_part()?; + p.advance(); + let value = p.parse_expr()?; + Ok(FunctionArg::Named { name, value }) + } else { + p.parse_expr().map(FunctionArg::Expr) + } +} + +/// Parses `ORDER BY ...` if it is here. +pub fn parse_optional_order_by<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + p.parse_comma_separated(D::parse_order_by_item) + } else { + Ok(Vec::new()) + } +} + +/// Parses what follows `OVER`. +pub fn parse_window_over<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.eat_op("(") { + return p.parse_ident().map(WindowOver::Named); + } + let starts_spec = ["PARTITION", "ROWS", "RANGE", "GROUPS"] + .iter() + .any(|word| p.at_keyword(word)); + let base = if p.at_ident() && !starts_spec { + Some(p.parse_ident()?) + } else { + None + }; + let partition_by = if p.eat_keyword("PARTITION") { + p.expect_keyword("BY")?; + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + let order_by = parse_optional_order_by(p)?; + let frame = parse_window_frame(p)?; + p.expect_op(")")?; + Ok(WindowOver::Spec(WindowSpec { + base, + partition_by, + order_by, + frame, + })) +} + +fn parse_window_frame<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let units = if p.eat_keyword("ROWS") { + FrameUnits::Rows + } else if p.eat_keyword("RANGE") { + FrameUnits::Range + } else if p.eat_keyword("GROUPS") { + FrameUnits::Groups + } else { + return Ok(None); + }; + let (start, end) = if p.eat_keyword("BETWEEN") { + let start = parse_frame_bound(p)?; + p.expect_keyword("AND")?; + (start, Some(parse_frame_bound(p)?)) + } else { + (parse_frame_bound(p)?, None) + }; + Ok(Some(WindowFrame { units, start, end })) +} + +fn parse_frame_bound<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("CURRENT") { + p.expect_keyword("ROW")?; + return Ok(FrameBound::CurrentRow); + } + if p.eat_keyword("UNBOUNDED") { + if p.eat_keyword("PRECEDING") { + return Ok(FrameBound::UnboundedPreceding); + } + p.expect_keyword("FOLLOWING")?; + return Ok(FrameBound::UnboundedFollowing); + } + let offset = D::parse_frame_offset(p)?; + if p.eat_keyword("PRECEDING") { + return Ok(FrameBound::Preceding(offset)); + } + p.expect_keyword("FOLLOWING")?; + Ok(FrameBound::Following(offset)) +} + +/// True for the types that can introduce a string literal, as in +/// `DATE '2020-01-01'`. +pub fn is_typed_string_type(name: &str) -> bool { + ["DATE", "TIME", "TIMESTAMP", "TIMESTAMPTZ", "DATETIME"] + .iter() + .any(|type_name| name.eq_ignore_ascii_case(type_name)) +} + +/// True for the standard functions written without parentheses, such as +/// `CURRENT_DATE`. +pub fn is_niladic_function(word: &str) -> bool { + const NAMES: [&str; 8] = [ + "CURRENT_DATE", + "CURRENT_TIME", + "CURRENT_TIMESTAMP", + "LOCALTIME", + "LOCALTIMESTAMP", + "CURRENT_USER", + "SESSION_USER", + "CURRENT_ROLE", + ]; + NAMES.iter().any(|name| word.eq_ignore_ascii_case(name)) +} + +/// Parses a column, a qualified name, or a function call. A plain column is +/// returned without allocating. +pub fn parse_name_expr<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let first = p.parse_ident()?; + if first.quote.is_none() + && let Some(expr) = parse_keyword_expr(p, first.clone())? + { + return Ok(expr); + } + if !p.at_op(".") && !D::at_function_call(p) { + if first.quote.is_none() && D::is_niladic_function(&first.text) { + return Ok(special(SpecialExpr::Niladic(first))); + } + return Ok(ExprKind::Ident(first).into()); + } + + let mut parts = Vec::with_capacity(if p.at_op(".") { 2 } else { 1 }); + parts.push(first); + while p.eat_op(".") { + parts.push(p.parse_name_part()?); + } + let name = ObjectName { parts }; + if D::at_function_call(p) { + if let [only] = name.parts.as_slice() + && only.quote.is_none() + && let Some(expr) = parse_special_function(p, &only.text)? + { + return Ok(expr); + } + p.parse_function_call(name) + } else { + Ok(ExprKind::Compound(name).into()) + } +} + +pub fn parse_prefix<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + match token.kind { + TokenKind::Number => { + p.advance(); + Ok(ExprKind::Literal(Literal::Number(token.text.into())).into()) + } + TokenKind::String => { + p.advance(); + Ok(ExprKind::Literal(Literal::String(D::string_literal(token))).into()) + } + TokenKind::Word if p.eat_keyword("NOT") => parse_unary(p, UnaryOp::Not, prec::NOT), + TokenKind::Word if p.eat_keyword("NULL") => Ok(ExprKind::Literal(Literal::Null).into()), + TokenKind::Word if p.eat_keyword("TRUE") => { + Ok(ExprKind::Literal(Literal::Boolean(true)).into()) + } + TokenKind::Word if p.eat_keyword("FALSE") => { + Ok(ExprKind::Literal(Literal::Boolean(false)).into()) + } + TokenKind::Word if p.eat_keyword("CASE") => parse_case(p), + TokenKind::HexString => { + p.advance(); + let digits = match token.text.strip_prefix("0x") { + Some(digits) => digits, + None => &token.text[2..token.text.len() - 1], + }; + Ok(ExprKind::Literal(Literal::HexString(digits.into())).into()) + } + TokenKind::DollarString => { + p.advance(); + let body = &token.text[1..]; + let tag_len = body.find('$').unwrap_or(0); + let tag = &body[..tag_len]; + let text = &body[tag_len + 1..body.len() - tag_len - 2]; + Ok(ExprKind::Literal(Literal::DollarQuoted { + tag: tag.into(), + text: text.into(), + }) + .into()) + } + TokenKind::Placeholder => { + p.advance(); + Ok(ExprKind::Placeholder(token.text.into()).into()) + } + TokenKind::Word if p.at_keyword("CAST") && p.peek_nth(1).text == "(" => { + p.advance(); + parse_cast_arguments(p, CastStyle::Function) + } + TokenKind::Word if p.at_keyword("EXISTS") && p.peek_nth(1).is_op("(") => { + p.advance(); + p.advance(); + let query = parse_subquery_body(p)?; + Ok(ExprKind::Exists(Box::new(query)).into()) + } + TokenKind::Word + if (p.at_keyword("LEFT") || p.at_keyword("RIGHT")) && p.peek_nth(1).is_op("(") => + { + let name = ObjectName { + parts: vec![p.parse_name_part()?], + }; + p.parse_function_call(name) + } + TokenKind::Word | TokenKind::QuotedIdent => parse_name_expr(p), + TokenKind::Op if p.eat_op("-") => parse_unary(p, UnaryOp::Neg, prec::UNARY), + TokenKind::Op if p.eat_op("+") => parse_unary(p, UnaryOp::Plus, prec::UNARY), + TokenKind::Op if p.eat_op("(") => { + if at_query_start(p) || at_set_operand_group(p) { + let query = parse_subquery_body(p)?; + return Ok(ExprKind::Subquery(Box::new(query)).into()); + } + let expr = p.parse_expr()?; + if p.at_op(",") { + let mut items = vec![expr]; + while p.eat_op(",") { + items.push(p.parse_expr()?); + } + p.expect_op(")")?; + return Ok(special(SpecialExpr::Tuple(items))); + } + p.expect_op(")")?; + Ok(ExprKind::Nested(Box::new(expr)).into()) + } + TokenKind::Op | TokenKind::Eof | TokenKind::DialectLiteral => Err(p.expected("expression")), + } +} + +/// Parses `(expr AS ty)`. +fn parse_cast_arguments<'a, D: Dialect>( + p: &mut Parser<'a, D>, + style: CastStyle, +) -> PResult> { + p.expect_op("(")?; + let expr = p.parse_expr()?; + p.expect_keyword("AS")?; + let ty = Box::new(D::parse_data_type(p)?); + p.expect_op(")")?; + Ok(ExprKind::Cast { + expr: Box::new(expr), + ty, + style, + } + .into()) +} + +/// True if a signed number or a parenthesized expression at the cursor is +/// followed by an interval unit. Without the unit, `interval - 1` is a column. +fn unit_follows_interval_value(p: &Parser<'_, D>) -> bool { + let is_unit = |token: Token<'_>| token.kind == TokenKind::Word && is_interval_unit(token.text); + if !p.at_op("(") { + return p.peek_nth(1).kind == TokenKind::Number && is_unit(p.peek_nth(2)); + } + let mut depth = 0usize; + let mut n = 0; + loop { + let token = p.peek_nth(n); + n += 1; + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + depth -= 1; + if depth == 0 { + return is_unit(p.peek_nth(n)); + } + } + _ => {} + } + } +} + +/// True at `WITH TIME ZONE 'text'` or `WITHOUT TIME ZONE 'text'` after the +/// unquoted word `first`, if that is `TIMESTAMP` or `TIME`. +fn at_time_zone_literal<'a, D: Dialect>(p: &Parser<'a, D>, first: &Ident<'a>) -> bool { + let next = p.peek(); + (next.is_word("WITH") || next.is_word("WITHOUT")) + && p.peek_nth(1).is_word("TIME") + && p.peek_nth(2).is_word("ZONE") + && p.peek_nth(3).kind == TokenKind::String + && ["TIMESTAMP", "TIME"] + .iter() + .any(|name| first.text.eq_ignore_ascii_case(name)) +} + +/// Parses what a keyword introduces after the unquoted word `first` was read: +/// an interval, a typed literal or an array. Only runs its comparisons when +/// the next token could continue such an expression, so that plain columns +/// do not pay for them. +fn parse_keyword_expr<'a, D: Dialect>( + p: &mut Parser<'a, D>, + first: Ident<'a>, +) -> PResult>> { + let next = p.peek(); + match next.kind { + TokenKind::String | TokenKind::Number | TokenKind::Placeholder => { + if first.text.eq_ignore_ascii_case("INTERVAL") { + return D::parse_interval(p).map(Some); + } + let is_type = next.kind == TokenKind::String && D::is_typed_string_type(&first.text); + if !is_type { + return Ok(None); + } + p.advance(); + Ok(Some( + ExprKind::TypedString(Box::new(TypedString { + ty: DataType { + qualifier: Vec::new(), + angle: None, + name: first, + args: Vec::new(), + suffix: DataTypeSuffix::None, + array: ArrayType::None, + }, + value: D::string_literal(next), + })) + .into(), + )) + } + TokenKind::Word if at_time_zone_literal(p, &first) => { + let suffix = if p.advance().is_word("WITH") { + DataTypeSuffix::WithTimeZone + } else { + DataTypeSuffix::WithoutTimeZone + }; + p.advance(); + p.advance(); + let value = D::string_literal(p.advance()); + Ok(Some( + ExprKind::TypedString(Box::new(TypedString { + ty: DataType { + qualifier: Vec::new(), + angle: None, + name: first, + args: Vec::new(), + suffix, + array: ArrayType::None, + }, + value, + })) + .into(), + )) + } + TokenKind::Op + if matches!(next.text, "+" | "-" | "(") + && first.text.eq_ignore_ascii_case("INTERVAL") + && unit_follows_interval_value(p) => + { + D::parse_interval(p).map(Some) + } + TokenKind::Op if next.text == "[" && first.text.eq_ignore_ascii_case("ARRAY") => { + p.advance(); + let items = if p.at_op("]") { + Vec::new() + } else { + p.parse_comma_separated(Parser::parse_expr)? + }; + p.expect_op("]")?; + Ok(Some(special(SpecialExpr::Array(items)))) + } + _ => Ok(None), + } +} + +/// True if `word` names a unit an interval can be measured in. +fn is_interval_unit(word: &str) -> bool { + [ + "YEAR", + "YEARS", + "MONTH", + "MONTHS", + "WEEK", + "WEEKS", + "DAY", + "DAYS", + "HOUR", + "HOURS", + "MINUTE", + "MINUTES", + "SECOND", + "SECONDS", + "CENTURY", + "DECADE", + "DOW", + "DOY", + "EPOCH", + "ISODOW", + "ISOYEAR", + "JULIAN", + "MICROSECOND", + "MICROSECONDS", + "MILLENIUM", + "MILLENNIUM", + "MILLISECOND", + "MILLISECONDS", + "NANOSECOND", + "NANOSECONDS", + "QUARTER", + "TIMEZONE", + "TIMEZONE_HOUR", + "TIMEZONE_MINUTE", + ] + .iter() + .any(|unit| unit.eq_ignore_ascii_case(word)) +} + +/// True if `word` names a part that can be taken from a date or time. +pub fn is_date_time_field(word: &str) -> bool { + is_interval_unit(word) + || [ + "DATE", + "DATETIME", + "DAYOFWEEK", + "DAYOFYEAR", + "ISOWEEK", + "TIME", + "TIMEZONE_ABBR", + "TIMEZONE_REGION", + ] + .iter() + .any(|field| field.eq_ignore_ascii_case(word)) +} + +pub fn parse_date_time_field<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.peek(); + if token.kind != TokenKind::Word || !is_date_time_field(token.text) { + return Err(p.expected("a date or time field")); + } + p.advance(); + Ok(token.text) +} + +/// Parses `(precision)` if present. +pub fn parse_optional_precision<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.eat_op("(") { + return Ok(None); + } + let precision = parse_number_text(p)?; + p.expect_op(")")?; + Ok(Some(precision)) +} + +/// Parses what follows `INTERVAL`. If `require_unit`, the value is a whole +/// expression that must be followed by a unit. Otherwise it is a single term +/// with an optional unit, so that `INTERVAL '5 days' > x` compares the interval. +pub fn parse_interval<'a, D: Dialect>( + p: &mut Parser<'a, D>, + require_unit: bool, +) -> PResult> { + parse_interval_with(p, require_unit, is_interval_unit) +} + +/// Like [`parse_interval`], with the words that count as interval units given +/// by `is_unit`. +pub fn parse_interval_with<'a, D: Dialect>( + p: &mut Parser<'a, D>, + require_unit: bool, + is_unit: fn(&str) -> bool, +) -> PResult> { + let value = if require_unit { + p.parse_expr()? + } else { + p.nested(Parser::parse_prefix)? + }; + + let token = p.peek(); + let leading_field = if token.kind == TokenKind::Word && is_unit(token.text) { + p.advance(); + Some(token.text) + } else if require_unit { + return Err(p.expected("an interval unit")); + } else { + None + }; + + let mut leading_precision = None; + let mut last_field = None; + let mut fractional_seconds_precision = None; + if leading_field.is_some_and(|field| field.eq_ignore_ascii_case("SECOND")) { + // `SECOND (leading, fractional)` replaces `SECOND TO SECOND`. + if p.eat_op("(") { + leading_precision = Some(parse_number_text(p)?); + if p.eat_op(",") { + fractional_seconds_precision = Some(parse_number_text(p)?); + } + p.expect_op(")")?; + } + } else if leading_field.is_some() { + leading_precision = parse_optional_precision(p)?; + if p.eat_keyword("TO") { + let last = parse_date_time_field(p)?; + if last.eq_ignore_ascii_case("SECOND") { + fractional_seconds_precision = parse_optional_precision(p)?; + } + last_field = Some(last); + } + } + + Ok(ExprKind::Interval(Box::new(Interval { + value, + leading_field: leading_field.map(Cow::Borrowed), + leading_precision: leading_precision.map(Cow::Borrowed), + last_field: last_field.map(Cow::Borrowed), + fractional_seconds_precision: fractional_seconds_precision.map(Cow::Borrowed), + })) + .into()) +} + +/// True if a word in `words` appears directly inside the `(` at the cursor. +fn call_has_keyword<'a, D: Dialect>(p: &Parser<'a, D>, words: &[&str]) -> bool { + let mut depth = 0usize; + let mut n = 0; + loop { + let token = p.peek_nth(n); + match token.kind { + TokenKind::Eof => return false, + TokenKind::Op if token.text == "(" => depth += 1, + TokenKind::Op if token.text == ")" => { + depth -= 1; + if depth == 0 { + return false; + } + } + TokenKind::Word if depth == 1 && words.iter().any(|w| token.is_word(w)) => { + return true; + } + _ => {} + } + n += 1; + } +} + +/// Parses a call that has its own syntax, with the cursor on the `(`. Returns +/// `None`, consuming nothing, if the call is an ordinary one: these are plain +/// functions unless their keywords are present. +fn parse_special_function<'a, D: Dialect>( + p: &mut Parser<'a, D>, + name: &str, +) -> PResult>> { + let eq = |word: &str| name.eq_ignore_ascii_case(word); + let special = if eq("EXTRACT") && call_has_keyword(p, &["FROM"]) { + p.advance(); + let field = D::parse_extract_field(p)?; + p.expect_keyword("FROM")?; + let expr = p.parse_expr()?; + SpecialExpr::Extract { + field: field.into(), + expr, + } + } else if (eq("CEIL") || eq("FLOOR")) && call_has_keyword(p, &["TO"]) { + p.advance(); + let expr = p.parse_expr()?; + p.expect_keyword("TO")?; + let field = parse_date_time_field(p)?; + SpecialExpr::Round { + ceil: eq("CEIL"), + expr, + field: field.into(), + } + } else if eq("POSITION") && call_has_keyword(p, &["IN"]) { + p.advance(); + let needle = p.parse_expr_bp(prec::COMPARE)?; + p.expect_keyword("IN")?; + let haystack = p.parse_expr()?; + SpecialExpr::Position { needle, haystack } + } else if (eq("SUBSTRING") || eq("SUBSTR")) && call_has_keyword(p, &["FROM", "FOR"]) { + p.advance(); + let expr = p.parse_expr()?; + let from = if p.eat_keyword("FROM") { + Some(p.parse_expr()?) + } else { + None + }; + let length = if p.eat_keyword("FOR") { + Some(p.parse_expr()?) + } else { + None + }; + SpecialExpr::Substring { + shorthand: eq("SUBSTR"), + expr, + from, + length, + } + } else if eq("TRIM") && at_special_trim(p) { + p.advance(); + parse_trim_arguments(p)? + } else if eq("OVERLAY") && call_has_keyword(p, &["PLACING"]) { + p.advance(); + let expr = p.parse_expr()?; + p.expect_keyword("PLACING")?; + let what = p.parse_expr()?; + p.expect_keyword("FROM")?; + let from = p.parse_expr()?; + let length = if p.eat_keyword("FOR") { + Some(p.parse_expr()?) + } else { + None + }; + SpecialExpr::Overlay { + expr, + what, + from, + length, + } + } else if eq("TRY_CAST") { + return parse_cast_arguments(p, CastStyle::TryFunction).map(Some); + } else { + return Ok(None); + }; + p.expect_op(")")?; + Ok(Some(ExprKind::Special(Box::new(special)).into())) +} + +fn at_special_trim<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let first = p.peek_nth(1); + ["BOTH", "LEADING", "TRAILING"] + .iter() + .any(|side| first.is_word(side)) + || call_has_keyword(p, &["FROM"]) +} + +fn parse_trim_arguments<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let side = if p.eat_keyword("BOTH") { + Some(TrimSide::Both) + } else if p.eat_keyword("LEADING") { + Some(TrimSide::Leading) + } else if p.eat_keyword("TRAILING") { + Some(TrimSide::Trailing) + } else { + None + }; + let first = p.parse_expr()?; + if p.eat_keyword("FROM") { + let expr = p.parse_expr()?; + Ok(SpecialExpr::Trim { + side, + what: Some(first), + expr, + }) + } else { + Ok(SpecialExpr::Trim { + side, + what: None, + expr: first, + }) + } +} + +/// Levels of tree height added for a [`SpecialExpr`] that wraps the expression +/// before it, on top of those the Pratt loop counts for a custom operator. Going +/// through the box and the larger enum takes about four times the stack of an +/// ordinary level when cloning or rendering. +const SPECIAL_LEVELS: usize = 2; + +/// Parses the right side of a binary operator, which has been consumed. A +/// comparison can be quantified: `a = ANY (b)`. +pub fn parse_binary_right<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + op: BinaryOp<'a>, + bp: u8, +) -> PResult> { + if bp == prec::COMPARE && p.peek_nth(1).is_op("(") { + let token = p.peek(); + let quantifier = if token.is_word("ANY") { + Some(Quantifier::Any) + } else if token.is_word("SOME") { + Some(Quantifier::Some) + } else if token.is_word("ALL") { + Some(Quantifier::All) + } else { + None + }; + if let Some(quantifier) = quantifier { + p.advance(); + let open_paren = p.advance().span.start; + let right = if at_query_start(p) { + let query = Box::new(parse_subquery_body(p)?); + Expr::new(ExprKind::Subquery(query), p.span_since(open_paren)) + } else { + let right = p.parse_expr()?; + p.expect_op(")")?; + right + }; + p.deepen_by(SPECIAL_LEVELS + 1)?; + return Ok(special(SpecialExpr::Quantified { + left, + op, + quantifier, + right, + })); + } + } + let right = p.parse_expr_bp(bp)?; + Ok(ExprKind::Binary { + left: Box::new(left), + op, + right: Box::new(right), + } + .into()) +} + +fn parse_unary<'a, D: Dialect>( + p: &mut Parser<'a, D>, + op: UnaryOp, + bp: u8, +) -> PResult> { + let expr = p.parse_expr_bp(bp)?; + Ok(ExprKind::Unary { + op, + expr: Box::new(expr), + } + .into()) +} + +fn parse_in<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + parse_in_operand(p, left, false) +} + +fn parse_not_in<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + parse_in_operand(p, left, true) +} + +/// Parses the parenthesized list or subquery after `IN`. +fn parse_in_operand<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + negated: bool, +) -> PResult> { + p.expect_op("(")?; + let expr = Box::new(left); + if at_query_start(p) || at_set_operand_group(p) { + let subquery = Box::new(parse_subquery_body(p)?); + return Ok(ExprKind::InSubquery { + expr, + subquery, + negated, + } + .into()); + } + let list = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(ExprKind::InList { + expr, + list, + negated, + } + .into()) +} + +pub fn parse_is<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + let negated = p.eat_keyword("NOT"); + let test = if p.eat_keyword("NULL") { + IsTest::Null + } else if p.eat_keyword("TRUE") { + IsTest::True + } else if p.eat_keyword("FALSE") { + IsTest::False + } else if p.eat_keyword("UNKNOWN") { + IsTest::Unknown + } else if p.eat_keyword("DISTINCT") { + p.expect_keyword("FROM")?; + IsTest::DistinctFrom(Box::new(p.parse_expr_bp(prec::IS)?)) + } else if let Some(test) = D::parse_is_test(p)? { + test + } else { + return Err(p.expected("NULL, TRUE, FALSE, UNKNOWN or DISTINCT FROM")); + }; + Ok(ExprKind::Is { + expr: Box::new(left), + test, + negated, + } + .into()) +} + +fn parse_like<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + parse_like_operand(p, left, false, LikeKind::Like) +} + +fn parse_not_like<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + parse_like_operand(p, left, true, LikeKind::Like) +} + +fn parse_similar<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + parse_like_operand(p, left, false, LikeKind::SimilarTo) +} + +fn parse_not_similar<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + p.advance(); + parse_like_operand(p, left, true, LikeKind::SimilarTo) +} + +pub(super) fn special<'a, X: crate::dialect::AstExt>(expr: SpecialExpr<'a, X>) -> Expr<'a, X> { + ExprKind::Special(Box::new(expr)).into() +} + +fn parse_field_access<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + let composite = match &left.kind { + ExprKind::Nested(_) | ExprKind::Function { .. } => true, + ExprKind::Special(special) => matches!( + **special, + SpecialExpr::Subscript { .. } | SpecialExpr::FieldAccess { .. } + ), + _ => false, + }; + if !composite { + return Err(p.expected("a composite value before the field name")); + } + p.advance(); + let field = p.parse_name_part()?; + p.deepen_by(SPECIAL_LEVELS)?; + Ok(special(SpecialExpr::FieldAccess { expr: left, field })) +} + +fn parse_at_time_zone<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + p.advance(); + let zone = p.parse_expr_bp(bp)?; + p.deepen_by(SPECIAL_LEVELS)?; + Ok(special(SpecialExpr::AtTimeZone { expr: left, zone })) +} + +fn parse_collate<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + let collation = parse_object_name(p)?; + p.deepen_by(SPECIAL_LEVELS)?; + Ok(special(SpecialExpr::Collate { + expr: left, + collation, + })) +} + +fn parse_subscript<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + let index = p.parse_expr()?; + p.expect_op("]")?; + p.deepen_by(SPECIAL_LEVELS)?; + Ok(special(SpecialExpr::Subscript { expr: left, index })) +} + +/// Parses a bound of a slice, which ends at `:` or `]`. +/// Set while parsing an expression that a `:` ends, such as a slice bound, so +/// that a dialect whose `:` is also an operator leaves it alone. +pub const CONTEXT_COLON_SEPARATES: u32 = 1 << 30; + +fn parse_slice_bound<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.at_op(":") || p.at_op("]") { + Ok(None) + } else { + p.with_context(CONTEXT_COLON_SEPARATES, Parser::parse_expr) + .map(Some) + } +} + +/// Parses `[index]`, or `[lower:upper]`, or `[lower:upper:step]` if `step`. +fn parse_subscript_slice<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + allow_step: bool, +) -> PResult> { + p.advance(); + let lower = parse_slice_bound(p)?; + if !p.eat_op(":") { + let Some(index) = lower else { + return Err(p.expected("an index")); + }; + p.expect_op("]")?; + p.deepen_by(SPECIAL_LEVELS)?; + return Ok(special(SpecialExpr::Subscript { expr: left, index })); + } + let upper = parse_slice_bound(p)?; + let step = if allow_step && p.eat_op(":") { + parse_slice_bound(p)? + } else { + None + }; + p.expect_op("]")?; + p.deepen_by(SPECIAL_LEVELS)?; + Ok(special(SpecialExpr::Slice { + expr: left, + lower, + upper, + step, + })) +} + +/// An infix rule for `[`, reading a subscript or a slice without a step. +pub fn parse_subscript_or_slice<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + parse_subscript_slice(p, left, false) +} + +/// An infix rule for `[`, reading a subscript or a slice with an optional step. +pub fn parse_subscript_or_slice_with_step<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + parse_subscript_slice(p, left, true) +} + +/// Parses `IS JSON` after `IS` and any `NOT`, or returns `None` at something else. +pub fn parse_is_json<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if !p.eat_keyword("JSON") { + return Ok(None); + } + let kind = if p.eat_keyword("VALUE") { + Some(JsonPredicateType::Value) + } else if p.eat_keyword("ARRAY") { + Some(JsonPredicateType::Array) + } else if p.eat_keyword("OBJECT") { + Some(JsonPredicateType::Object) + } else if p.eat_keyword("SCALAR") { + Some(JsonPredicateType::Scalar) + } else { + None + }; + let unique_keys = if p.eat_keyword("WITH") { + Some(true) + } else if p.eat_keyword("WITHOUT") { + Some(false) + } else { + None + }; + let unique_keys = match unique_keys { + Some(with) => { + p.expect_keyword("UNIQUE")?; + let keys = p.eat_keyword("KEYS"); + Some(JsonUniqueKeys { with, keys }) + } + None => None, + }; + Ok(Some(IsTest::Json { kind, unique_keys })) +} + +/// Parses `IS NORMALIZED`, with an optional form, after `IS` and any `NOT`. +pub fn parse_is_normalized<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if p.eat_keyword("NORMALIZED") { + return Ok(Some(IsTest::Normalized(None))); + } + let form = if p.at_keyword("NFC") { + NormalForm::Nfc + } else if p.at_keyword("NFD") { + NormalForm::Nfd + } else if p.at_keyword("NFKC") { + NormalForm::Nfkc + } else if p.at_keyword("NFKD") { + NormalForm::Nfkd + } else { + return Ok(None); + }; + p.advance(); + p.expect_keyword("NORMALIZED")?; + Ok(Some(IsTest::Normalized(Some(form)))) +} + +/// Parses `ON OVERFLOW ...` inside a `LISTAGG`-style call. +pub fn parse_on_overflow<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if !(p.at_keyword("ON") && p.peek_nth(1).is_word("OVERFLOW")) { + return Ok(None); + } + p.advance(); + p.advance(); + if p.eat_keyword("ERROR") { + return Ok(Some(Box::new(ListAggOnOverflow::Error))); + } + p.expect_keyword("TRUNCATE")?; + let filler = if p.at_keyword("WITH") || p.at_keyword("WITHOUT") { + None + } else { + Some(p.parse_expr()?) + }; + let with_count = if p.eat_keyword("WITH") { + true + } else { + p.expect_keyword("WITHOUT")?; + false + }; + p.expect_keyword("COUNT")?; + Ok(Some(Box::new(ListAggOnOverflow::Truncate { + filler, + with_count, + }))) +} + +/// Consumes `ANY`, `SOME` or `ALL` directly before a `(`, for a `LIKE` over a +/// list of patterns. +pub fn parse_like_any<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option { + if !p.peek_nth(1).is_op("(") { + return None; + } + let quantifier = if p.at_keyword("ANY") { + Quantifier::Any + } else if p.at_keyword("SOME") { + Quantifier::Some + } else if p.at_keyword("ALL") { + Quantifier::All + } else { + return None; + }; + p.advance(); + Some(quantifier) +} + +/// True at an ODBC escape sequence: `{d 'x'}`, `{t 'x'}`, `{ts 'x'}` or `{fn f()}`. +pub fn at_odbc_escape<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + p.at_op("{") && ["d", "t", "ts", "fn"].iter().any(|kind| next.is_word(kind)) +} + +/// Parses an ODBC escape sequence, with the cursor on its `{`. +pub fn parse_odbc_escape<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("{")?; + let token = p.advance(); + let expr = p.parse_expr()?; + p.expect_op("}")?; + Ok(special(SpecialExpr::OdbcEscape { + kind: token.text.into(), + expr, + })) +} + +/// Parses the pattern and optional escape after a `LIKE`-style keyword. +pub fn parse_like_operand<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + negated: bool, + kind: LikeKind<'a>, +) -> PResult> { + let start = p.peek().span.start; + let pattern = match D::parse_like_quantifier(p)? { + Some(quantifier) => { + p.expect_op("(")?; + let items = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + p.deepen_by(SPECIAL_LEVELS)?; + let mut list = special(SpecialExpr::QuantifiedList { quantifier, items }); + list.span = p.span_since(start); + Box::new(list) + } + None => Box::new(p.parse_expr_bp(prec::COMPARE)?), + }; + let escape = if p.eat_keyword("ESCAPE") { + Some(Box::new(p.parse_expr_bp(prec::COMPARE)?)) + } else { + None + }; + Ok(ExprKind::Like { + expr: Box::new(left), + pattern, + negated, + kind, + escape, + } + .into()) +} + +fn parse_between<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + parse_between_operands(p, left, false) +} + +/// Parses the lower bound of `BETWEEN`. +pub fn parse_between_low<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.parse_expr_bp(prec::COMPARE) +} + +fn parse_not_between<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + _bp: u8, +) -> PResult> { + p.advance(); + p.advance(); + parse_between_operands(p, left, true) +} + +/// Parses the upper bound of `BETWEEN`. +pub fn parse_between_high<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.parse_expr_bp(prec::COMPARE) +} + +/// The bounds bind tighter than `AND`, which separates them here. +fn parse_between_operands<'a, D: Dialect>( + p: &mut Parser<'a, D>, + left: Expr<'a, D::Ext>, + negated: bool, +) -> PResult> { + let low = Box::new(D::parse_between_low(p)?); + p.expect_keyword("AND")?; + let high = Box::new(D::parse_between_high(p)?); + Ok(ExprKind::Between { + expr: Box::new(left), + low, + high, + negated, + } + .into()) +} + +/// The rule for `NOT` in infix position, which only negates certain operators. +fn negated_infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + let next = p.peek_nth(1); + let parse: InfixParseFn<'a, D> = if next.is_word("IN") { + parse_not_in + } else if next.is_word("LIKE") { + parse_not_like + } else if next.is_word("SIMILAR") && p.peek_nth(2).is_word("TO") { + parse_not_similar + } else if next.is_word("BETWEEN") { + parse_not_between + } else { + return None; + }; + Some(InfixRule::custom(prec::COMPARE, parse)) +} + +/// Parses `CASE ... END` with `CASE` already consumed. +fn parse_case<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let operand = if p.at_keyword("WHEN") { + None + } else { + Some(p.parse_expr()?) + }; + let mut branches = Vec::new(); + while p.eat_keyword("WHEN") { + let condition = p.parse_expr()?; + p.expect_keyword("THEN")?; + let result = p.parse_expr()?; + branches.push(CaseWhen { condition, result }); + } + if branches.is_empty() { + return Err(p.expected("WHEN")); + } + let else_result = if p.eat_keyword("ELSE") { + Some(p.parse_expr()?) + } else { + None + }; + p.expect_keyword("END")?; + Ok(ExprKind::Case(Box::new(CaseExpr { + operand, + branches, + else_result, + })) + .into()) +} + +pub fn infix_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option> { + let token = p.peek(); + let (bp, op) = match token.kind { + TokenKind::Op => match token.text { + "=" => (prec::COMPARE, BinaryOp::Eq), + "<>" | "!=" => (prec::COMPARE, BinaryOp::NotEq), + "<" => (prec::COMPARE, BinaryOp::Lt), + "<=" => (prec::COMPARE, BinaryOp::LtEq), + ">" => (prec::COMPARE, BinaryOp::Gt), + ">=" => (prec::COMPARE, BinaryOp::GtEq), + "+" => (prec::ADD, BinaryOp::Add), + "-" => (prec::ADD, BinaryOp::Sub), + "*" => (prec::MUL, BinaryOp::Mul), + "/" => (prec::MUL, BinaryOp::Div), + "%" => (prec::MUL, BinaryOp::Mod), + "||" => (prec::MUL, BinaryOp::StringConcat), + "|" => (prec::BIT_OR, BinaryOp::BitOr), + "&" => (prec::BIT_AND, BinaryOp::BitAnd), + "^" => (prec::BIT_XOR, BinaryOp::BitXor), + "[" => return Some(InfixRule::custom(prec::POSTFIX, parse_subscript)), + "." => return Some(InfixRule::custom(prec::POSTFIX, parse_field_access)), + _ => return None, + }, + TokenKind::Word if token.text.eq_ignore_ascii_case("IN") => { + return Some(InfixRule::custom(prec::COMPARE, parse_in)); + } + TokenKind::Word if token.text.eq_ignore_ascii_case("NOT") => { + return negated_infix_rule(p); + } + TokenKind::Word if token.text.eq_ignore_ascii_case("IS") => { + return Some(InfixRule::custom(prec::IS, parse_is)); + } + TokenKind::Word if token.text.eq_ignore_ascii_case("LIKE") => { + return Some(InfixRule::custom(prec::COMPARE, parse_like)); + } + TokenKind::Word if token.text.eq_ignore_ascii_case("BETWEEN") => { + return Some(InfixRule::custom(prec::COMPARE, parse_between)); + } + TokenKind::Word + if token.text.eq_ignore_ascii_case("SIMILAR") && p.peek_nth(1).is_word("TO") => + { + return Some(InfixRule::custom(prec::COMPARE, parse_similar)); + } + TokenKind::Word if token.text.eq_ignore_ascii_case("OVERLAPS") => { + (prec::COMPARE, BinaryOp::Named("OVERLAPS".into())) + } + TokenKind::Word + if token.text.eq_ignore_ascii_case("AT") + && p.peek_nth(1).is_word("TIME") + && p.peek_nth(2).is_word("ZONE") => + { + return Some(InfixRule::custom(prec::AT_TIME_ZONE, parse_at_time_zone)); + } + TokenKind::Word + if token.text.eq_ignore_ascii_case("COLLATE") + && matches!(p.peek_nth(1).kind, TokenKind::Word | TokenKind::QuotedIdent) => + { + return Some(InfixRule::custom(prec::POSTFIX, parse_collate)); + } + TokenKind::Word if token.text.eq_ignore_ascii_case("OR") => (prec::OR, BinaryOp::Or), + TokenKind::Word if token.text.eq_ignore_ascii_case("AND") => (prec::AND, BinaryOp::And), + _ => return None, + }; + Some(InfixRule::binary(bp, op)) +} diff --git a/sqlparser_v2/src/grammar/pattern.rs b/sqlparser_v2/src/grammar/pattern.rs new file mode 100644 index 0000000000..4a5c837f0e --- /dev/null +++ b/sqlparser_v2/src/grammar/pattern.rs @@ -0,0 +1,241 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `CONNECT BY` and `MATCH_RECOGNIZE`. + +use super::*; + +/// Set while parsing a `CONNECT BY` clause, where `PRIOR` is an operator. +pub const CONTEXT_CONNECT_BY: u32 = 1; + +/// Parses any `CONNECT BY` and `START WITH` clauses, in either order. +pub fn parse_connect_by_clauses<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut clauses = Vec::new(); + loop { + if p.at_keyword("START") && p.peek_nth(1).is_word("WITH") { + p.advance(); + p.advance(); + clauses.push(ConnectBy::StartWith(p.parse_expr()?)); + } else if p.at_keyword("CONNECT") && p.peek_nth(1).is_word("BY") { + p.advance(); + p.advance(); + let nocycle = p.eat_keyword("NOCYCLE"); + let relationships = p.with_context(CONTEXT_CONNECT_BY, |p| { + p.parse_comma_separated(Parser::parse_expr) + })?; + clauses.push(ConnectBy::ConnectBy { + nocycle, + relationships, + }); + } else { + return Ok(clauses); + } + } +} + +/// Parses what follows `MATCH_RECOGNIZE`. +pub fn parse_match_recognize<'a, D: Dialect>( + p: &mut Parser<'a, D>, + table: TableRef<'a, D::Ext>, +) -> PResult> { + p.expect_op("(")?; + let partition_by = if p.eat_keyword("PARTITION") { + p.expect_keyword("BY")?; + p.parse_comma_separated(Parser::parse_expr)? + } else { + Vec::new() + }; + let order_by = parse_optional_order_by(p)?; + let measures = if p.eat_keyword("MEASURES") { + p.parse_comma_separated(|p| { + let expr = p.parse_expr()?; + p.eat_keyword("AS"); + Ok((expr, p.parse_ident()?)) + })? + } else { + Vec::new() + }; + let rows_per_match = parse_rows_per_match(p)?; + let after_match_skip = parse_after_match_skip(p)?; + p.expect_keyword("PATTERN")?; + p.expect_op("(")?; + let pattern = parse_match_pattern(p)?; + p.expect_op(")")?; + p.expect_keyword("DEFINE")?; + let symbols = p.parse_comma_separated(|p| { + let symbol = p.parse_ident()?; + p.expect_keyword("AS")?; + Ok((symbol, p.parse_expr()?)) + })?; + p.expect_op(")")?; + Ok(TableFactor::MatchRecognize(Box::new(MatchRecognize { + table, + partition_by, + order_by, + measures, + rows_per_match, + after_match_skip, + pattern, + symbols, + }))) +} + +fn parse_rows_per_match<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("ONE") { + p.expect_keywords(&["ROW", "PER", "MATCH"])?; + return Ok(Some(RowsPerMatch::OneRow)); + } + if !p.eat_keyword("ALL") { + return Ok(None); + } + p.expect_keywords(&["ROWS", "PER", "MATCH"])?; + let empty = if p.eat_keyword("SHOW") { + p.expect_keywords(&["EMPTY", "MATCHES"])?; + Some(EmptyMatches::Show) + } else if p.eat_keyword("OMIT") { + p.expect_keywords(&["EMPTY", "MATCHES"])?; + Some(EmptyMatches::Omit) + } else if p.eat_keyword("WITH") { + p.expect_keywords(&["UNMATCHED", "ROWS"])?; + Some(EmptyMatches::WithUnmatchedRows) + } else { + None + }; + Ok(Some(RowsPerMatch::AllRows(empty))) +} + +fn parse_after_match_skip<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !p.eat_keyword("AFTER") { + return Ok(None); + } + p.expect_keywords(&["MATCH", "SKIP"])?; + if p.eat_keyword("PAST") { + p.expect_keywords(&["LAST", "ROW"])?; + return Ok(Some(AfterMatchSkip::PastLastRow)); + } + p.expect_keyword("TO")?; + Ok(Some(if p.eat_keyword("NEXT") { + p.expect_keyword("ROW")?; + AfterMatchSkip::ToNextRow + } else if p.eat_keyword("FIRST") { + AfterMatchSkip::ToFirst(p.parse_ident()?) + } else { + p.expect_keyword("LAST")?; + AfterMatchSkip::ToLast(p.parse_ident()?) + })) +} + +fn parse_match_pattern<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let first = parse_pattern_sequence(p)?; + if !p.at_op("|") { + return Ok(first); + } + let mut branches = vec![first]; + while p.eat_op("|") { + branches.push(parse_pattern_sequence(p)?); + } + Ok(MatchPattern::Alternation(branches)) +} + +fn parse_pattern_sequence<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut patterns = vec![parse_pattern_repetition(p)?]; + while !p.at_op(")") && !p.at_op("|") { + patterns.push(parse_pattern_repetition(p)?); + } + if patterns.len() == 1 { + return Ok(patterns.remove(0)); + } + Ok(MatchPattern::Concat(patterns)) +} + +fn at_question_mark<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let token = p.peek(); + token.kind == TokenKind::Placeholder && token.text == "?" +} + +fn parse_pattern_repetition<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let pattern = parse_pattern_atom(p)?; + let quantifier = if p.eat_op("*") { + PatternQuantifier::ZeroOrMore + } else if p.eat_op("+") { + PatternQuantifier::OneOrMore + } else if at_question_mark(p) { + p.advance(); + PatternQuantifier::AtMostOne + } else if p.eat_op("{") { + parse_pattern_bounds(p)? + } else { + return Ok(pattern); + }; + let reluctant = at_question_mark(p); + if reluctant { + p.advance(); + } + Ok(MatchPattern::Repetition { + pattern: Box::new(pattern), + quantifier, + reluctant, + }) +} + +/// Parses `n}`, `n,}`, `,m}` or `n,m}`, with the `{` consumed. +fn parse_pattern_bounds<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let quantifier = if p.eat_op(",") { + PatternQuantifier::AtMost(parse_number_text(p)?.into()) + } else { + let low = parse_number_text(p)?; + if !p.eat_op(",") { + PatternQuantifier::Exactly(low.into()) + } else if p.at_op("}") { + PatternQuantifier::AtLeast(low.into()) + } else { + PatternQuantifier::Range(low.into(), parse_number_text(p)?.into()) + } + }; + p.expect_op("}")?; + Ok(quantifier) +} + +fn parse_pattern_atom<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_op("^") { + return Ok(MatchPattern::Start); + } + if p.eat_op("$") { + return Ok(MatchPattern::End); + } + if p.eat_op("(") { + let pattern = p.nested(parse_match_pattern)?; + p.expect_op(")")?; + return Ok(MatchPattern::Group(Box::new(pattern))); + } + if p.eat_op("{") { + p.expect_op("-")?; + let symbol = p.parse_ident()?; + p.expect_op("-")?; + p.expect_op("}")?; + return Ok(MatchPattern::Exclude(symbol)); + } + if p.at_keyword("PERMUTE") && p.peek_nth(1).is_op("(") { + p.advance(); + return parse_ident_list(p).map(MatchPattern::Permute); + } + p.parse_ident().map(MatchPattern::Symbol) +} diff --git a/sqlparser_v2/src/grammar/pipe.rs b/sqlparser_v2/src/grammar/pipe.rs new file mode 100644 index 0000000000..f42855b5f2 --- /dev/null +++ b/sqlparser_v2/src/grammar/pipe.rs @@ -0,0 +1,249 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Pipe syntax, for the dialects that have it: `SELECT * FROM t |> WHERE x |> SELECT y`. + +use super::*; + +/// Parses every `|> ...` step at the current position. +pub fn parse_pipe_operators<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut operators = Vec::new(); + while p.eat_op("|>") { + operators.push(parse_pipe_operator(p)?); + } + Ok(operators) +} + +/// Parses one step, after its `|>`. +/// +/// Each step has its own function because queries can nest through any of +/// them, and one function holding them all would need a very large stack frame +/// in debug builds at every level. +pub fn parse_pipe_operator<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("SELECT") { + return pipe_select(p); + } + if p.eat_keyword("EXTEND") { + return pipe_extend(p); + } + if p.eat_keyword("SET") { + return pipe_set(p); + } + if p.eat_keyword("DROP") { + return pipe_drop(p); + } + if p.eat_keyword("AS") { + return pipe_as(p); + } + if p.eat_keyword("WHERE") { + return pipe_where(p); + } + if p.eat_keyword("LIMIT") { + return pipe_limit(p); + } + if p.eat_keyword("ORDER") { + return pipe_order_by(p); + } + if p.eat_keyword("AGGREGATE") { + return parse_aggregate(p); + } + if p.eat_keyword("TABLESAMPLE") { + return pipe_sample(p); + } + if p.eat_keyword("RENAME") { + return pipe_rename(p); + } + if p.eat_keyword("UNION") { + return parse_set_operation(p, SetOperator::Union); + } + if p.eat_keyword("INTERSECT") { + return parse_set_operation(p, SetOperator::Intersect); + } + if p.eat_keyword("EXCEPT") { + return parse_set_operation(p, SetOperator::Except); + } + if p.eat_keyword("CALL") { + return pipe_call(p); + } + if p.eat_keyword("PIVOT") { + return pipe_pivot(p); + } + if p.eat_keyword("UNPIVOT") { + return pipe_unpivot(p); + } + pipe_join(p) +} + +fn pipe_select<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::Select( + p.parse_comma_separated(Parser::parse_select_item)?, + )) +} + +fn pipe_extend<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::Extend( + p.parse_comma_separated(Parser::parse_select_item)?, + )) +} + +fn pipe_set<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::Set( + p.parse_comma_separated(D::parse_assignment)?, + )) +} + +fn pipe_drop<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::Drop( + p.parse_comma_separated(Parser::parse_ident)?, + )) +} + +fn pipe_as<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::As(p.parse_ident()?)) +} + +fn pipe_where<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::Where(p.parse_expr()?)) +} + +fn pipe_limit<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let count = p.parse_expr()?; + let offset = if p.eat_keyword("OFFSET") { + Some(p.parse_expr()?) + } else { + None + }; + Ok(PipeOperator::Limit { count, offset }) +} + +fn pipe_order_by<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("BY")?; + Ok(PipeOperator::OrderBy( + p.parse_comma_separated(D::parse_order_by_item)?, + )) +} + +fn pipe_sample<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::TableSample(Box::new(D::parse_sample_clause( + p, true, + )?))) +} + +fn pipe_rename<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(PipeOperator::Rename(p.parse_comma_separated(parse_rename)?)) +} + +fn pipe_call<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = parse_object_name(p)?; + let function = p.parse_function_call(name)?; + let alias = parse_optional_alias(p)?; + Ok(PipeOperator::Call { function, alias }) +} + +fn pipe_pivot<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let clause = Box::new(parse_pivot_head(p)?); + p.expect_op(")")?; + let alias = parse_optional_alias(p)?; + Ok(PipeOperator::Pivot { clause, alias }) +} + +fn pipe_unpivot<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let clause = Box::new(parse_unpivot_clause(p)?); + let alias = parse_optional_alias(p)?; + Ok(PipeOperator::Unpivot { clause, alias }) +} + +fn pipe_join<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + match D::parse_join(p)? { + Some(join) => Ok(PipeOperator::Join(Box::new(join))), + None => Err(p.expected("a pipe operator")), + } +} + +/// Parses what follows `AGGREGATE`: `[items] [GROUP BY items]`. +fn parse_aggregate<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let aggregates = if p.at_keyword("GROUP") { + Vec::new() + } else { + p.parse_comma_separated(parse_aggregate_item)? + }; + let group_by = if p.eat_keyword("GROUP") { + p.expect_keyword("BY")?; + p.parse_comma_separated(parse_aggregate_item)? + } else { + Vec::new() + }; + Ok(PipeOperator::Aggregate { + aggregates, + group_by, + }) +} + +fn parse_aggregate_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let expr = parse_expr_with_alias(p)?; + let asc = if p.eat_keyword("ASC") { + Some(true) + } else if p.eat_keyword("DESC") { + Some(false) + } else { + None + }; + Ok(PipeAggregate { expr, asc }) +} + +/// Parses `name [AS] new_name`. +fn parse_rename<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + p.eat_keyword("AS"); + let new_name = p.parse_ident()?; + Ok(PipeRename { name, new_name }) +} + +/// Parses what follows a set operator. Only `UNION` can omit `DISTINCT`. +fn parse_set_operation<'a, D: Dialect>( + p: &mut Parser<'a, D>, + op: SetOperator, +) -> PResult> { + let quantifier = super::query::parse_quantifier(p); + if op != SetOperator::Union && quantifier != SetQuantifier::Distinct { + return Err(p.expected("DISTINCT")); + } + let by_name = p.eat_keyword("BY"); + if by_name { + p.expect_keyword("NAME")?; + } + let queries = p.parse_comma_separated(parse_parenthesized_query)?; + Ok(PipeOperator::SetOperation { + op, + quantifier, + by_name, + queries, + }) +} + +fn parse_parenthesized_query<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("(")?; + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + Ok(query) +} diff --git a/sqlparser_v2/src/grammar/pivot.rs b/sqlparser_v2/src/grammar/pivot.rs new file mode 100644 index 0000000000..2649fe3fee --- /dev/null +++ b/sqlparser_v2/src/grammar/pivot.rs @@ -0,0 +1,148 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `PIVOT`, `UNPIVOT` and sampling clauses, for the dialects that have them. + +use super::*; + +pub fn parse_expr_with_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let expr = p.parse_expr()?; + let alias = parse_optional_alias(p)?; + Ok(ExprWithAlias { expr, alias }) +} + +/// Parses the values after `IN`, a list of optionally aliased expressions. +pub fn parse_pivot_source<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.parse_comma_separated(parse_expr_with_alias) + .map(PivotSource::List) +} + +/// Parses `(aggregates FOR columns IN (values)`, up to but not including the +/// closing parenthesis, which a dialect can precede with its own options. +pub fn parse_pivot_head<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_op("(")?; + let aggregates = p.parse_comma_separated(parse_expr_with_alias)?; + p.expect_keyword("FOR")?; + let column = |p: &mut Parser<'a, D>| p.parse_expr_bp(prec::COMPARE); + let columns = if p.eat_op("(") { + let columns = p.parse_comma_separated(column)?; + p.expect_op(")")?; + columns + } else { + vec![column(p)?] + }; + p.expect_keyword("IN")?; + p.expect_op("(")?; + let source = D::parse_pivot_source(p)?; + p.expect_op(")")?; + Ok(PivotClause { + aggregates, + columns, + source, + default_on_null: None, + }) +} + +/// Parses what follows `UNPIVOT`. +pub fn parse_unpivot_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let include_nulls = if p.eat_keyword("INCLUDE") { + p.expect_keyword("NULLS")?; + Some(true) + } else if p.eat_keyword("EXCLUDE") { + p.expect_keyword("NULLS")?; + Some(false) + } else { + None + }; + p.expect_op("(")?; + let value = p.parse_expr()?; + p.expect_keyword("FOR")?; + let name = p.parse_ident()?; + p.expect_keyword("IN")?; + p.expect_op("(")?; + let columns = p.parse_comma_separated(parse_expr_with_alias)?; + p.expect_op(")")?; + p.expect_op(")")?; + Ok(UnpivotClause { + include_nulls, + value, + name, + columns, + }) +} + +/// Parses what follows `SAMPLE` or `TABLESAMPLE`: an amount, which can be in +/// parentheses. +pub fn parse_sample_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, + long_form: bool, +) -> PResult> { + let parenthesized = p.eat_op("("); + let amount = parse_sample_amount(p)?; + if parenthesized { + p.expect_op(")")?; + } + Ok(SampleClause { + long_form, + method: None, + amount, + parenthesized, + seed: None, + offset: None, + }) +} + +/// Parses how much of a table to sample. +pub fn parse_sample_amount<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let value = p.parse_expr()?; + let unit = if p.eat_keyword("ROWS") { + Some(SampleUnit::Rows) + } else if p.eat_keyword("PERCENT") { + Some(SampleUnit::Percent) + } else { + None + }; + Ok(SampleAmount::Quantity { value, unit }) +} + +pub fn parse_number<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult<&'a str> { + let token = p.expect_kind(TokenKind::Number, "a number")?; + Ok(token.text) +} + +pub fn parse_sample_seed<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let repeatable = p.at_keyword("REPEATABLE"); + if !repeatable && !p.at_keyword("SEED") { + return Ok(None); + } + p.advance(); + p.expect_op("(")?; + let value = parse_number(p)?; + p.expect_op(")")?; + Ok(Some(SampleSeed { + repeatable, + value: value.into(), + })) +} diff --git a/sqlparser_v2/src/grammar/query.rs b/sqlparser_v2/src/grammar/query.rs new file mode 100644 index 0000000000..1174421430 --- /dev/null +++ b/sqlparser_v2/src/grammar/query.rs @@ -0,0 +1,1226 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Queries: `SELECT`, set operations, tables, joins, and the clauses after them. + +use super::*; +use crate::ast::ExprKind; +use crate::ast::SelectItemKind; +use crate::ast::Span; +use std::borrow::Cow; + +pub fn parse_query<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let with = if p.eat_keyword("WITH") { + let recursive = D::eat_with_recursive(p); + let ctes = p.parse_comma_separated(D::parse_cte)?; + Some(Box::new(With { recursive, ctes })) + } else { + None + }; + parse_query_after_with(p, with) +} + +/// Consumes `RECURSIVE` after `WITH`. It is a CTE's name instead when `AS` or +/// a column list follows it. +pub fn eat_with_recursive<'a, D: Dialect>(p: &mut Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + let names_a_cte = + matches!(next.kind, TokenKind::Word | TokenKind::QuotedIdent) && !next.is_word("AS"); + names_a_cte && p.eat_keyword("RECURSIVE") +} + +/// Parses the rest of a query once its `WITH` clause has been read. +pub fn parse_query_after_with<'a, D: Dialect>( + p: &mut Parser<'a, D>, + with: Option>>, +) -> PResult> { + let statement = if with.is_none() { + None + } else { + D::parse_statement_after_with(p)? + }; + if let Some(statement) = statement { + return Ok(statement_query::(with, statement)); + } + let body = parse_set_expr(p, 0)?; + + let order_by = if p.eat_keyword("ORDER") { + p.expect_keyword("BY")?; + D::parse_query_order_by(p)? + } else { + Vec::new() + }; + + let distribution = D::parse_query_distribution(p)?; + + let limit = if p.eat_keyword("LIMIT") { + Some(Box::new(D::parse_limit(p)?)) + } else if p.at_keyword("OFFSET") { + Some(Box::new(parse_offset_first(p)?)) + } else { + None + }; + + let fetch = if p.eat_keyword("FETCH") { + Some(Box::new(parse_fetch(p)?)) + } else { + None + }; + + let mut locks = Vec::new(); + while p.at_keyword("FOR") && { + let next = p.peek_nth(1); + next.is_word("UPDATE") || next.is_word("SHARE") + } { + p.advance(); + locks.push(parse_lock(p)?); + } + + let limit = match limit { + Some(limit) => Some(limit), + None if !locks.is_empty() => D::parse_limit_after_locks(p)?, + None => None, + }; + + let tail = D::parse_query_tail(p)?; + + let pipes = D::parse_pipe_operators(p)?; + + Ok(Query { + with, + body, + order_by, + distribution, + limit, + fetch, + locks, + tail, + pipes, + }) +} + +/// Wraps a statement that follows a `WITH` clause as a query. +fn statement_query<'a, D: Dialect>( + with: Option>>, + statement: Statement<'a, D::Ext>, +) -> Query<'a, D::Ext> { + Query { + with, + body: SetExpr::Statement(Box::new(statement)), + order_by: Vec::new(), + distribution: None, + limit: None, + fetch: None, + locks: Vec::new(), + tail: Default::default(), + pipes: Vec::new(), + } +} + +/// Parses `INSERT`, `UPDATE` or `DELETE` after a `WITH` clause, each only if +/// its flag is set. Returns `None` at anything else. +pub fn parse_dml_after_with<'a, D: Dialect>( + p: &mut Parser<'a, D>, + insert: bool, + update_or_delete: bool, +) -> PResult>> { + let allowed = (insert && p.at_keyword("INSERT")) + || (update_or_delete && (p.at_keyword("UPDATE") || p.at_keyword("DELETE"))); + if !allowed { + return Ok(None); + } + p.parse_statement().map(Some) +} + +/// Parses `TABLE name` or a query, for a `CREATE TABLE ... AS` that has both. +pub fn parse_table_or_query<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.at_keyword("TABLE") { + return D::parse_query(p); + } + p.advance(); + let name = parse_object_name(p)?; + Ok(Query { + with: None, + body: SetExpr::Table(name), + order_by: Vec::new(), + distribution: None, + limit: None, + fetch: None, + locks: Vec::new(), + tail: Default::default(), + pipes: Vec::new(), + }) +} + +/// Parses `INTO [TEMPORARY | TEMP | UNLOGGED] [TABLE] name`, for a `SELECT` +/// that creates a table. +pub fn parse_select_into_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if !p.eat_keyword("INTO") { + return Ok(None); + } + let token = p.peek(); + let modifier = ["TEMPORARY", "TEMP", "UNLOGGED"] + .iter() + .find(|word| p.eat_keyword(word)) + .map(|_| token.text); + let table_keyword = p.eat_keyword("TABLE"); + let name = parse_object_name(p)?; + Ok(Some(Box::new(SelectInto { + modifier: modifier.map(Cow::Borrowed), + table_keyword, + targets: vec![name_expr(name)], + }))) +} + +/// Parses `INTO a, b, ...`, for a `SELECT` that stores into variables. +pub fn parse_select_into_variables<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if !p.eat_keyword("INTO") { + return Ok(None); + } + let targets = p.parse_comma_separated(|p| p.spanned_expr(parse_into_target))?; + Ok(Some(Box::new(SelectInto { + modifier: None, + table_keyword: false, + targets, + }))) +} + +/// A variable after `INTO`: a name or a placeholder. +fn parse_into_target<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::Placeholder { + p.advance(); + return Ok(ExprKind::Placeholder(token.text.into()).into()); + } + Ok(name_expr(parse_object_name(p)?)) +} + +/// Builds the expression that names `name`. +fn name_expr<'a, X: crate::dialect::AstExt>(mut name: ObjectName<'a>) -> Expr<'a, X> { + let span = crate::ast::Span { + start: name.parts[0].span.start, + end: name.parts[name.parts.len() - 1].span.end, + }; + let kind = if name.parts.len() == 1 { + ExprKind::Ident(name.parts.remove(0)) + } else { + ExprKind::Compound(name) + }; + Expr::new(kind, span) +} + +/// Parses `OFFSET n [ROWS] [LIMIT m]`. +fn parse_offset_first<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("OFFSET")?; + let offset = Some(p.parse_expr()?); + let offset_rows = parse_offset_rows(p); + let mut all = false; + let count = if p.eat_keyword("LIMIT") { + all = D::eat_limit_all(p); + if all { None } else { Some(p.parse_expr()?) } + } else { + None + }; + Ok(Limit { + count, + offset, + offset_rows, + offset_comma: false, + all, + by: Vec::new(), + }) +} + +fn parse_offset_rows<'a, D: Dialect>(p: &mut Parser<'a, D>) -> OffsetRows { + if p.eat_keyword("ROWS") { + OffsetRows::Rows + } else if p.eat_keyword("ROW") { + OffsetRows::Row + } else { + OffsetRows::None + } +} + +/// Parses what follows the `FETCH` keyword. +fn parse_fetch<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if !p.eat_keyword("FIRST") { + p.eat_keyword("NEXT"); + } + let (quantity, percent) = if p.eat_keyword("ROW") || p.eat_keyword("ROWS") { + (None, false) + } else { + if !matches!( + p.peek().kind, + TokenKind::Number | TokenKind::String | TokenKind::Placeholder + ) { + return Err(p.expected("a row count")); + } + let quantity = p.parse_prefix()?; + let percent = p.eat_keyword("PERCENT"); + if !p.eat_keyword("ROW") { + p.eat_keyword("ROWS"); + } + (Some(quantity), percent) + }; + let with_ties = if p.eat_keyword("ONLY") { + false + } else if p.eat_keyword("WITH") { + p.expect_keyword("TIES")?; + true + } else { + false + }; + Ok(Fetch { + quantity, + percent, + with_ties, + }) +} + +/// Parses what follows the `FOR` keyword. +fn parse_lock<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let lock_type = if p.eat_keyword("UPDATE") { + LockType::Update + } else { + p.expect_keyword("SHARE")?; + LockType::Share + }; + let of = if p.eat_keyword("OF") { + Some(parse_object_name(p)?) + } else { + None + }; + let nonblock = if p.eat_keyword("NOWAIT") { + Some(NonBlock::Nowait) + } else if p.eat_keyword("SKIP") { + p.expect_keyword("LOCKED")?; + Some(NonBlock::SkipLocked) + } else { + None + }; + Ok(LockClause { + lock_type, + of, + nonblock, + }) +} + +pub fn parse_select<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let start = p.peek().span.start; + p.expect_keyword("SELECT")?; + let (modifiers, quantifier) = D::parse_select_head(p)?; + let projection = D::parse_projection(p)?; + let into = D::parse_select_into(p)?; + + let from = if p.eat_keyword("FROM") { + D::parse_from_list(p)? + } else { + Vec::new() + }; + + let select = parse_select_tail(p, modifiers, quantifier, projection, into, from, false)?; + Ok(Select { + span: p.span_since(start), + ..select + }) +} + +/// Parses `FROM tables [SELECT items]` and the clauses that follow. +pub fn parse_from_first_select<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let start = p.peek().span.start; + p.expect_keyword("FROM")?; + let from = D::parse_from_list(p)?; + let (modifiers, quantifier, projection) = if p.eat_keyword("SELECT") { + let (modifiers, quantifier) = D::parse_select_head(p)?; + (modifiers, quantifier, D::parse_projection(p)?) + } else { + (Default::default(), SetQuantifier::None, Vec::new()) + }; + let select = parse_select_tail(p, modifiers, quantifier, projection, None, from, true)?; + Ok(Select { + span: p.span_since(start), + ..select + }) +} + +/// Parses the clauses after the projection and `FROM`, whichever came first. +fn parse_select_tail<'a, D: Dialect>( + p: &mut Parser<'a, D>, + modifiers: crate::dialect::SelectExtOf<'a, D>, + quantifier: SetQuantifier, + projection: Vec>, + into: Option>>, + from: Vec>, + from_first: bool, +) -> PResult> { + let lateral_views = D::parse_lateral_views(p)?; + + let prewhere = D::parse_prewhere(p)?; + + let selection = parse_optional_where(p)?; + + let connect_by = D::parse_connect_by(p)?; + + let mut group_by_all = false; + let group_by = if p.eat_keyword("GROUP") { + p.expect_keyword("BY")?; + group_by_all = D::eat_group_by_all(p); + if group_by_all { + Vec::new() + } else { + p.parse_comma_separated(|p| p.spanned_expr(D::parse_group_by_item))? + } + } else { + Vec::new() + }; + let group_by_modifier = if group_by_all || !group_by.is_empty() { + D::parse_group_by_modifier(p) + } else { + None + }; + let grouping_sets = if group_by.is_empty() { + None + } else { + D::parse_group_by_suffix(p)? + }; + + let having = if p.eat_keyword("HAVING") { + Some(p.parse_expr()?) + } else { + None + }; + + let qualify = D::parse_qualify(p)?; + + let windows = if p.eat_keyword("WINDOW") { + p.parse_comma_separated(parse_named_window)? + } else { + Vec::new() + }; + + Ok(Select { + modifiers, + quantifier, + projection, + into, + from, + lateral_views, + prewhere, + selection, + connect_by, + group_by, + group_by_all, + group_by_modifier, + grouping_sets, + having, + qualify, + windows, + from_first, + span: Span::default(), + }) +} + +/// Parses `REPLACE (expr AS name, ...)`. +pub fn parse_wildcard_replace<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult, Ident<'a>)>> { + p.expect_keyword("REPLACE")?; + p.expect_op("(")?; + let replace = p.parse_comma_separated(|p| { + let expr = p.parse_expr()?; + p.expect_keyword("AS")?; + Ok((expr, p.parse_ident()?)) + })?; + p.expect_op(")")?; + Ok(replace) +} + +/// Like [`Parser::parse_comma_separated`], but a comma can end the list. +pub fn parse_list_with_trailing_comma<'a, D: Dialect, T>( + p: &mut Parser<'a, D>, + mut item: impl FnMut(&mut Parser<'a, D>) -> PResult, +) -> PResult> { + let mut items = vec![item(p)?]; + while p.eat_op(",") { + if at_list_end(p) { + break; + } + items.push(item(p)?); + } + Ok(items) +} + +/// True at what can follow a trailing comma: the end of the enclosing list. +pub fn at_list_end<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + const CLAUSES: [&str; 14] = [ + "FROM", + "WHERE", + "GROUP", + "HAVING", + "QUALIFY", + "WINDOW", + "ORDER", + "LIMIT", + "OFFSET", + "UNION", + "EXCEPT", + "MINUS", + "INTERSECT", + "FOR", + ]; + let token = p.peek(); + // A clause word that names an argument, as in `f(a, offset => 1)`. + let names_argument = p.peek_nth(1).is_op("=>") || p.peek_nth(1).is_op(":="); + match token.kind { + TokenKind::Eof => true, + TokenKind::Op => token.text == ")" || token.text == ";", + TokenKind::Word => !names_argument && CLAUSES.iter().any(|word| token.is_word(word)), + _ => false, + } +} + +/// Parses the options after a `*`, returning `None` if there are none. +pub fn parse_wildcard_options<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let mut options = WildcardOptions { + ilike: None, + exclude: Vec::new(), + exclude_parens: false, + except_keyword: false, + replace: Vec::new(), + rename: Vec::new(), + rename_parens: false, + }; + let mut found = false; + if p.eat_keyword("ILIKE") { + let token = p.expect_kind(TokenKind::String, "a string after ILIKE")?; + options.ilike = Some(D::string_literal(token)); + found = true; + } else if p.eat_keyword("EXCLUDE") { + options.exclude_parens = p.at_op("("); + options.exclude = if options.exclude_parens { + parse_ident_list(p)? + } else { + vec![p.parse_ident()?] + }; + found = true; + } + if p.at_keyword("REPLACE") { + options.replace = parse_wildcard_replace(p)?; + found = true; + } + if p.eat_keyword("RENAME") { + options.rename_parens = p.eat_op("("); + let rename_pair = |p: &mut Parser<'a, D>| -> PResult<(Ident<'a>, Ident<'a>)> { + let from = p.parse_ident()?; + p.expect_keyword("AS")?; + Ok((from, p.parse_ident()?)) + }; + if options.rename_parens { + options.rename = p.parse_comma_separated(rename_pair)?; + p.expect_op(")")?; + } else { + options.rename = vec![rename_pair(p)?]; + } + found = true; + } + Ok(found.then_some(options)) +} + +/// Parses the default sequence after `SELECT`: dialect modifiers, then +/// `ALL` or `DISTINCT`. +pub fn parse_select_head<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(crate::dialect::SelectExtOf<'a, D>, SetQuantifier)> { + let modifiers = D::parse_select_modifiers(p)?; + Ok((modifiers, parse_quantifier(p))) +} + +fn parse_named_window<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + p.expect_keyword("AS")?; + if let Some(base) = D::parse_named_window_reference(p)? { + return Ok(NamedWindow { + name, + window: WindowOver::Named(base), + }); + } + if !p.at_op("(") { + return Err(p.expected("a parenthesized window definition")); + } + let window = parse_window_over(p)?; + Ok(NamedWindow { name, window }) +} + +/// Parses `WITH ROLLUP`, and `WITH CUBE` if `cube` is true. +pub fn parse_group_by_with<'a, D: Dialect>( + p: &mut Parser<'a, D>, + cube: bool, +) -> Option { + if !p.at_keyword("WITH") { + return None; + } + let next = p.peek_nth(1); + let modifier = if next.is_word("ROLLUP") { + GroupByModifier::Rollup + } else if cube && next.is_word("CUBE") { + GroupByModifier::Cube + } else { + return None; + }; + p.advance(); + p.advance(); + Some(modifier) +} + +/// Parses `ROLLUP (...)`, `CUBE (...)` or `GROUPING SETS (...)`, or else an +/// ordinary expression. Dialects with these forms use this as their +/// `parse_group_by_item`. +pub fn parse_grouping_item<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let kind = if p.at_keyword("ROLLUP") && p.peek_nth(1).is_op("(") { + p.advance(); + GroupingKind::Rollup + } else if p.at_keyword("CUBE") && p.peek_nth(1).is_op("(") { + p.advance(); + GroupingKind::Cube + } else if p.at_keyword("GROUPING") && p.peek_nth(1).is_word("SETS") { + p.advance(); + p.advance(); + GroupingKind::Sets + } else { + return p.parse_expr(); + }; + p.expect_op("(")?; + let sets = p.parse_comma_separated(parse_grouping_set)?; + p.expect_op(")")?; + Ok(ExprKind::Special(Box::new(SpecialExpr::Grouping { kind, sets })).into()) +} + +/// Like [`parse_grouping_item`], where `()` is an empty grouping set. +pub fn parse_grouping_item_or_empty_set<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_op("(") && p.peek_nth(1).is_op(")") { + p.advance(); + p.advance(); + return Ok(special(SpecialExpr::Tuple(Vec::new()))); + } + parse_grouping_item(p) +} + +/// Parses `GROUPING SETS (...)` written after a `GROUP BY` list. +pub fn parse_group_by_grouping_sets<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>>> { + if p.at_keyword("GROUPING") && p.peek_nth(1).is_word("SETS") { + return p + .spanned_expr(parse_grouping_item) + .map(|item| Some(Box::new(item))); + } + Ok(None) +} + +fn parse_grouping_set<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if !p.eat_op("(") { + return Ok(vec![p.parse_expr()?]); + } + if p.eat_op(")") { + return Ok(Vec::new()); + } + let set = p.parse_comma_separated(Parser::parse_expr)?; + p.expect_op(")")?; + Ok(set) +} + +/// Like [`set_operator_rule`], where `MINUS` means `EXCEPT`. +pub fn set_operator_rule_with_minus<'a, D: Dialect>(p: &Parser<'a, D>) -> Option { + if p.at_keyword("MINUS") { + return Some(SetOperatorRule { + bp: prec::UNION, + op: SetOperator::Minus, + }); + } + set_operator_rule(p) +} + +pub fn set_operator_rule<'a, D: Dialect>(p: &Parser<'a, D>) -> Option { + let (bp, op) = if p.at_keyword("UNION") { + (prec::UNION, SetOperator::Union) + } else if p.at_keyword("EXCEPT") { + (prec::UNION, SetOperator::Except) + } else if p.at_keyword("INTERSECT") { + (prec::INTERSECT, SetOperator::Intersect) + } else { + return None; + }; + Some(SetOperatorRule { bp, op }) +} + +/// The Pratt loop for set operators, parsing those binding tighter than +/// `min_bp`. +fn parse_set_expr<'a, D: Dialect>( + p: &mut Parser<'a, D>, + min_bp: u8, +) -> PResult> { + let mut left = parse_set_operand(p)?; + while let Some(rule) = D::set_operator_rule(p) { + if rule.bp <= min_bp { + break; + } + p.deepen()?; + p.advance(); + let (quantifier, by_name) = D::parse_set_quantifier(p); + let right = p.nested(|p| parse_set_expr(p, rule.bp))?; + left = SetExpr::SetOperation { + left: Box::new(left), + op: rule.op, + quantifier, + by_name, + right: Box::new(right), + }; + } + Ok(left) +} + +/// Parses an optional `ALL` or `DISTINCT`. +pub fn parse_quantifier<'a, D: Dialect>(p: &mut Parser<'a, D>) -> SetQuantifier { + if p.eat_keyword("ALL") { + SetQuantifier::All + } else if p.eat_keyword("DISTINCT") { + SetQuantifier::Distinct + } else { + SetQuantifier::None + } +} + +fn parse_set_operand<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_op("(") { + let query = parse_subquery_body(p)?; + Ok(SetExpr::Query(Box::new(query))) + } else if D::at_query_values(p, 0) { + p.advance(); + D::parse_query_values(p) + } else { + Ok(SetExpr::Select(Box::new(D::parse_select(p)?))) + } +} + +/// True at a parenthesized query that continues with a set operator, which +/// starts a subquery instead of a parenthesized expression. +pub(super) fn at_set_operand_group<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let mut leading = 0; + while p.peek_nth(leading).is_op("(") { + leading += 1; + if leading > p.max_nesting_depth() { + return false; + } + } + if leading == 0 || !query_starts_at(p, leading) { + return false; + } + for close in closing_parens(p, leading) { + let Some(close) = close else { + return false; + }; + let after = p.peek_nth(close + 1); + if !after.is_op(")") { + return ["UNION", "EXCEPT", "INTERSECT", "MINUS"] + .iter() + .any(|word| after.is_word(word)); + } + } + false +} + +/// Parses a query and its closing parenthesis, with the opening one consumed. +pub fn parse_subquery_body<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + Ok(query) +} + +pub(super) fn at_query_start<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + query_starts_at(p, 0) +} + +/// True if the token `n` ahead starts a query. +pub fn query_starts_at<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + let token = p.peek_nth(n); + token.is_word("SELECT") + || token.is_word("WITH") + || D::at_query_values(p, n) + || D::at_from_first(p, n) +} + +/// True at `VALUES (`, since `values` alone can be a column. +pub fn at_query_values<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + p.peek_nth(n).is_word("VALUES") && p.peek_nth(n + 1).is_op("(") +} + +/// Parses the rows of a `VALUES` query, after the keyword. +pub fn parse_query_values<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + Ok(SetExpr::Values(p.parse_comma_separated(parse_values_row)?)) +} + +/// With the opening `(` consumed, decides between a parenthesized join and a +/// subquery. When parentheses lead to a query, the group is a table inside a +/// join only if what follows it continues a table reference, as in +/// `((SELECT 1) AS x JOIN y)`. +fn at_nested_join<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let mut leading = 0; + while p.peek_nth(leading).is_op("(") { + leading += 1; + // The nesting limit rejects anything deeper, however it is read. + if leading > p.max_nesting_depth() { + return true; + } + } + if !query_starts_at(p, leading) { + return true; + } + if leading == 0 { + return false; + } + for close in closing_parens(p, leading) { + let Some(close) = close else { + return false; + }; + let after = p.peek_nth(close + 1); + if !after.is_op(")") { + return ![ + "UNION", + "EXCEPT", + "INTERSECT", + "ORDER", + "LIMIT", + "OFFSET", + "FETCH", + "FOR", + ] + .iter() + .any(|word| after.is_word(word)); + } + } + false +} + +/// The offsets of the `)` closing each of the `leading` parentheses at the +/// cursor, outermost first, found in a single pass. +fn closing_parens<'a, D: Dialect>(p: &Parser<'a, D>, leading: usize) -> Vec> { + let mut closes = vec![None; leading]; + let mut depth = leading; + let mut offset = leading; + while depth > 0 { + let token = p.peek_nth(offset); + if token.kind == TokenKind::Eof { + break; + } + if token.is_op("(") { + depth += 1; + } else if token.is_op(")") { + depth -= 1; + // A later parenthesis can return to this depth; only the first + // close belongs to the leading one. + if depth < leading && closes[depth].is_none() { + closes[depth] = Some(offset); + } + } + offset += 1; + } + closes +} + +pub fn parse_table_factor<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.at_keyword("LATERAL") && at_lateral_operand(p) { + p.advance(); + let factor = p.nested(D::parse_table_factor)?; + if matches!(factor, TableFactor::NestedJoin(_)) { + return Err(p.expected("a subquery or function after LATERAL")); + } + return Ok(TableFactor::Lateral(Box::new(factor))); + } + if p.eat_op("(") { + if at_nested_join(p) { + let table = p.nested(D::parse_table_with_joins)?; + D::check_nested_join(p, &table)?; + p.expect_op(")")?; + return Ok(TableFactor::NestedJoin(Box::new(table))); + } + // A derived table takes as much stack as a scalar subquery, which + // also counts as two levels because it passes through an expression. + let query = p.nested(parse_subquery_body)?; + return Ok(TableFactor::Derived(Box::new(query))); + } + let name = parse_object_name(p)?; + if p.at_op("(") { + let call = Box::new(p.parse_function_call(name)?); + let with_ordinality = p.at_keyword("WITH") && p.peek_nth(1).is_word("ORDINALITY"); + if with_ordinality { + p.advance(); + p.advance(); + } + return Ok(TableFactor::Function { + call, + with_ordinality, + }); + } + Ok(TableFactor::Named(name)) +} + +/// Parentheses group joins: `(a)` alone is not a table. +pub fn check_nested_join<'a, D: Dialect>( + p: &Parser<'a, D>, + table: &TableWithJoins<'a, D::Ext>, +) -> PResult<()> { + if table.joins.is_empty() && !matches!(table.relation.factor, TableFactor::NestedJoin(_)) { + return Err(p.expected("a join inside the parentheses")); + } + Ok(()) +} + +/// True if the word after `LATERAL` starts a subquery or a function call, as +/// opposed to `lateral` being the name of a table. +fn at_lateral_operand<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let next = p.peek_nth(1); + next.is_op("(") + || (matches!(next.kind, TokenKind::Word | TokenKind::QuotedIdent) + && (p.peek_nth(2).is_op("(") || p.peek_nth(2).is_op("."))) +} + +pub fn parse_select_item<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_op("*") { + return Ok(SelectItemKind::Wildcard.into()); + } + if at_qualified_wildcard(p) { + return parse_qualified_wildcard(p) + .map(|name| SelectItemKind::QualifiedWildcard(name).into()); + } + let expr = p.parse_expr()?; + D::parse_select_item_alias(p, expr) +} + +/// Like [`parse_select_item_alias`], but after `AS` any word can be the alias. +pub fn parse_select_item_alias_any_word<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, D::Ext>, +) -> PResult> { + if p.eat_keyword("AS") { + let alias = Some(p.parse_name_part()?); + return Ok(SelectItemKind::Expr { expr, alias }.into()); + } + parse_select_item_alias(p, expr) +} + +/// Finishes a select item, whose expression has been parsed. +pub fn parse_select_item_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, + expr: Expr<'a, D::Ext>, +) -> PResult> { + let alias = parse_optional_alias(p)?; + Ok(SelectItemKind::Expr { expr, alias }.into()) +} + +/// Looks ahead for `name.name.*` without consuming anything. +pub(super) fn at_qualified_wildcard<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + if !p.at_ident() { + return false; + } + let mut n = 1; + loop { + if !p.peek_nth(n).is_op(".") { + return false; + } + let next = p.peek_nth(n + 1); + if next.is_op("*") { + return true; + } + if !matches!(next.kind, TokenKind::Word | TokenKind::QuotedIdent) { + return false; + } + n += 2; + } +} + +pub(super) fn parse_qualified_wildcard<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let mut parts = vec![p.parse_ident()?]; + loop { + p.expect_op(".")?; + if p.eat_op("*") { + return Ok(ObjectName { parts }); + } + parts.push(p.parse_name_part()?); + } +} + +pub fn parse_table_ref<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let factor = D::parse_table_factor(p)?; + let alias = parse_optional_table_alias(p)?; + Ok(TableRef { + factor, + alias, + span: Span::default(), + }) +} + +pub fn parse_object_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let first = D::parse_object_name_part(p, &[])?; + let mut parts = Vec::with_capacity(if p.at_op(".") { 2 } else { 1 }); + parts.push(first); + while p.eat_op(".") { + let part = D::parse_object_name_part(p, &parts)?; + parts.push(part); + } + Ok(ObjectName { parts }) +} + +/// Parses one part of a name, given the parts before it. +pub fn parse_object_name_part<'a, D: Dialect>( + p: &mut Parser<'a, D>, + before: &[Ident<'a>], +) -> PResult> { + if before.is_empty() { + p.parse_ident() + } else { + p.parse_name_part() + } +} + +pub fn parse_cte<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_ident()?; + let columns = D::parse_cte_columns(p)?; + p.expect_keyword("AS")?; + p.expect_op("(")?; + let query = p.nested(D::parse_query)?; + p.expect_op(")")?; + Ok(Cte { + name, + columns, + materialized: None, + query, + }) +} + +pub fn parse_table_with_joins<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let relation = p.parse_table_ref()?; + let mut joins = Vec::new(); + while let Some(join) = D::parse_join(p)? { + joins.push(join); + } + Ok(TableWithJoins { relation, joins }) +} + +pub fn parse_join<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + let natural = p.eat_keyword("NATURAL"); + let Some((kind, spelled_out)) = parse_join_kind(p)? else { + return if natural { + Err(p.expected("JOIN")) + } else { + Ok(None) + }; + }; + if natural && kind == JoinKind::Cross { + return Err(p.expected("a join type other than CROSS after NATURAL")); + } + let has_constraint = !natural && kind != JoinKind::Cross; + let table = D::parse_join_table(p, has_constraint)?; + let constraint = if natural { + JoinConstraint::Natural + } else if kind == JoinKind::Cross { + JoinConstraint::None + } else { + parse_join_constraint(p)? + }; + Ok(Some(Join { + kind, + spelled_out, + table, + constraint, + })) +} + +/// Consumes the keywords up to and including `JOIN`, if a join starts here. +/// Also returns whether the optional `INNER` or `OUTER` keyword was written. +pub fn parse_join_kind<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult, bool)>> { + if p.eat_keyword("JOIN") { + return Ok(Some((JoinKind::Inner, false))); + } + let (kind, spelled_out) = if p.eat_keyword("INNER") { + (JoinKind::Inner, true) + } else if p.eat_keyword("CROSS") { + (JoinKind::Cross, false) + } else { + let kind = if p.eat_keyword("LEFT") { + JoinKind::Left + } else if p.eat_keyword("RIGHT") { + JoinKind::Right + } else if p.eat_keyword("FULL") { + JoinKind::Full + } else { + return Ok(None); + }; + // `FULL OUTER JOIN` renders as `FULL JOIN`, as in the original. + let outer = p.eat_keyword("OUTER"); + (kind.clone(), outer && kind != JoinKind::Full) + }; + p.expect_keyword("JOIN")?; + Ok(Some((kind, spelled_out))) +} + +pub fn parse_join_constraint<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if p.eat_keyword("ON") { + return p.parse_expr().map(JoinConstraint::On); + } + if p.eat_keyword("USING") { + return parse_ident_list(p).map(JoinConstraint::Using); + } + Ok(JoinConstraint::None) +} + +/// Parses a table alias, recording whether it was written with `AS`. +pub fn parse_optional_table_alias<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let explicit = p.eat_keyword("AS"); + if explicit || p.at_implicit_alias() { + let name = p.parse_ident()?; + let columns = if p.at_op("(") { + parse_ident_list(p)? + } else { + Vec::new() + }; + Ok(Some(TableAlias { + name, + explicit, + columns, + column_types: Vec::new(), + })) + } else { + Ok(None) + } +} + +/// Parses `AS name`, a bare `name`, or nothing. +pub fn parse_optional_alias<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult>> { + if p.eat_keyword("AS") || p.at_implicit_alias() { + p.parse_ident().map(Some) + } else { + Ok(None) + } +} + +pub fn parse_order_by_item<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let expr = p.parse_expr()?; + let (asc, nulls_first) = parse_order_by_modifiers(p)?; + Ok(OrderByItem { + using: None, + expr, + asc, + nulls_first, + ext: Default::default(), + }) +} + +/// Parses `[ASC | DESC] [NULLS {FIRST | LAST}]`. +pub fn parse_order_by_modifiers<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult<(Option, Option)> { + let asc = if p.eat_keyword("ASC") { + Some(true) + } else if p.eat_keyword("DESC") { + Some(false) + } else { + None + }; + let nulls_first = if p.eat_keyword("NULLS") { + if p.eat_keyword("FIRST") { + Some(true) + } else { + p.expect_keyword("LAST")?; + Some(false) + } + } else { + None + }; + Ok((asc, nulls_first)) +} + +/// Parses what follows the `LIMIT` keyword. +pub fn parse_limit<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if D::eat_limit_all(p) { + return parse_limit_all(p); + } + let count = p.parse_expr()?; + parse_limit_offset(p, count) +} + +/// Parses the optional `OFFSET` after `LIMIT ALL`. +fn parse_limit_all<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let (offset, offset_rows) = if p.eat_keyword("OFFSET") { + let offset = p.parse_expr()?; + (Some(offset), parse_offset_rows(p)) + } else { + (None, OffsetRows::None) + }; + Ok(Limit { + count: None, + offset, + offset_rows, + offset_comma: false, + all: true, + by: Vec::new(), + }) +} + +/// Parses an optional `OFFSET` after the limit's count. +pub fn parse_limit_offset<'a, D: Dialect>( + p: &mut Parser<'a, D>, + count: Expr<'a, D::Ext>, +) -> PResult> { + let (offset, offset_rows) = if p.eat_keyword("OFFSET") { + let offset = p.parse_expr()?; + (Some(offset), parse_offset_rows(p)) + } else { + (None, OffsetRows::None) + }; + Ok(Limit { + count: Some(count), + offset, + offset_rows, + offset_comma: false, + all: false, + by: Vec::new(), + }) +} diff --git a/sqlparser_v2/src/grammar/session.rs b/sqlparser_v2/src/grammar/session.rs new file mode 100644 index 0000000000..be62bd363f --- /dev/null +++ b/sqlparser_v2/src/grammar/session.rs @@ -0,0 +1,678 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Rules for `SHOW`, transactions, `USE`, `EXPLAIN`, `SET`, `COMMENT` and `CALL`. + +use super::*; +use crate::PResult; +use crate::ast::ExprKind; +use crate::ast::Span; +use crate::ast::StatementKind; +use crate::dialect::Dialect; +use crate::lexer::{Token, TokenKind}; +use crate::parser::Parser; +use std::borrow::Cow; + +fn at_any<'a, D: Dialect>(p: &Parser<'a, D>, words: &[&str]) -> bool { + words.iter().any(|word| p.at_keyword(word)) +} + +fn first_of<'a, D: Dialect>(p: &mut Parser<'a, D>, words: &[&'static str]) -> Option<&'static str> { + words.iter().copied().find(|word| p.eat_keyword(word)) +} + +pub fn parse_string<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.expect_kind(TokenKind::String, "a string")?; + Ok(D::string_literal(token)) +} + +fn at_statement_end<'a, D: Dialect>(p: &Parser<'a, D>, n: usize) -> bool { + let token = p.peek_nth(n); + token.kind == TokenKind::Eof || token.is_op(";") +} + +// SHOW + +const SHOW_CLAUSES: [&str; 7] = ["IN", "FROM", "LIKE", "WHERE", "STARTS", "LIMIT", "HISTORY"]; + +fn at_show_clause<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + at_any(p, &SHOW_CLAUSES) +} + +pub fn parse_show<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("SHOW")?; + let mut modifiers = Vec::new(); + while at_any(p, &["TERSE", "EXTENDED", "FULL", "GLOBAL", "SESSION"]) + && p.peek_nth(1).kind == TokenKind::Word + { + modifiers.push(p.peek().text); + p.advance(); + } + + let mut object = Vec::new(); + let mut name = None; + if p.at_keyword("CREATE") { + object.push(p.peek().text); + p.advance(); + if p.peek().kind != TokenKind::Word { + return Err(p.expected("the kind of object")); + } + object.push(p.peek().text); + p.advance(); + name = Some(parse_object_name(p)?); + } else { + while p.peek().kind == TokenKind::Word && !at_show_clause(p) { + let word = p.peek().text; + object.push(if word.eq_ignore_ascii_case("FIELDS") { + "COLUMNS" + } else { + word + }); + p.advance(); + } + if object.is_empty() { + return Err(p.expected("what to show")); + } + } + + // These two only qualify listings of tables and columns. + let detailed = modifiers + .iter() + .any(|word| word.eq_ignore_ascii_case("EXTENDED") || word.eq_ignore_ascii_case("FULL")); + let detailable = ["TABLES", "COLUMNS", "PROCESSLIST"] + .iter() + .any(|kind| object[0].eq_ignore_ascii_case(kind)); + if detailed && !detailable { + return Err(p.expected("TABLES or COLUMNS")); + } + + let mut clauses = Vec::new(); + while let Some(clause) = parse_show_clause(p)? { + clauses.push(clause); + } + Ok(Show { + modifiers: modifiers.into_iter().map(Cow::Borrowed).collect(), + object: object.into_iter().map(Cow::Borrowed).collect(), + name, + clauses, + }) +} + +fn parse_show_clause<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + let clause = if p.eat_keyword("HISTORY") { + ShowClause::History + } else if p.eat_keyword("LIKE") { + ShowClause::Like(parse_string(p)?) + } else if p.eat_keyword("WHERE") { + ShowClause::Where(p.parse_expr()?) + } else if p.eat_keyword("STARTS") { + p.expect_keyword("WITH")?; + ShowClause::StartsWith(parse_string(p)?) + } else if p.eat_keyword("LIMIT") { + ShowClause::Limit(p.parse_expr()?) + } else if p.peek().kind == TokenKind::String { + ShowClause::Pattern(parse_string(p)?) + } else if p.at_keyword("FROM") && p.peek_nth(1).kind == TokenKind::String { + p.advance(); + ShowClause::FromValue(parse_string(p)?) + } else if at_any(p, &["IN", "FROM"]) { + let from = p.at_keyword("FROM"); + p.advance(); + let scope = first_of(p, &["ACCOUNT", "DATABASE", "SCHEMA", "TABLE"]); + let name = if p.at_ident() && !at_show_clause(p) { + Some(parse_object_name(p)?) + } else { + None + }; + ShowClause::Location { + from, + scope: scope.map(Cow::Borrowed), + name, + } + } else { + return Ok(None); + }; + Ok(Some(clause)) +} + +// Transactions + +fn parse_isolation_level<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult { + if p.eat_keyword("READ") { + if p.eat_keyword("COMMITTED") { + return Ok(IsolationLevel::ReadCommitted); + } + p.expect_keyword("UNCOMMITTED")?; + return Ok(IsolationLevel::ReadUncommitted); + } + if p.eat_keyword("REPEATABLE") { + p.expect_keyword("READ")?; + return Ok(IsolationLevel::RepeatableRead); + } + if p.eat_keyword("SERIALIZABLE") { + return Ok(IsolationLevel::Serializable); + } + p.expect_keyword("SNAPSHOT")?; + Ok(IsolationLevel::Snapshot) +} + +fn parse_transaction_modes<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut modes = Vec::new(); + loop { + if p.eat_keyword("ISOLATION") { + p.expect_keyword("LEVEL")?; + modes.push(TransactionMode::IsolationLevel(parse_isolation_level(p)?)); + } else if p.eat_keyword("READ") { + if p.eat_keyword("ONLY") { + modes.push(TransactionMode::ReadOnly); + } else { + p.expect_keyword("WRITE")?; + modes.push(TransactionMode::ReadWrite); + } + } else { + return Ok(modes); + } + let next = p.peek_nth(1); + if p.at_op(",") && (next.is_word("ISOLATION") || next.is_word("READ")) { + p.advance(); + } + } +} + +fn parse_finish<'a, D: Dialect>( + p: &mut Parser<'a, D>, + kind: FinishKind, +) -> PResult> { + p.advance(); + first_of(p, &["WORK", "TRAN", "TRANSACTION"]); + let mut chain = false; + if p.eat_keyword("AND") { + let negated = p.eat_keyword("NO"); + p.expect_keyword("CHAIN")?; + chain = !negated; + } + let savepoint = if kind == FinishKind::Rollback && p.eat_keyword("TO") { + p.eat_keyword("SAVEPOINT"); + Some(p.parse_ident()?) + } else { + None + }; + Ok(Transaction::Finish { + kind, + chain, + savepoint, + }) +} + +/// True at a statement that controls a transaction. +pub fn at_transaction<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + at_any( + p, + &[ + "START", + "BEGIN", + "COMMIT", + "END", + "ROLLBACK", + "SAVEPOINT", + "RELEASE", + ], + ) +} + +/// Parses `ABORT [WORK | TRANSACTION] [AND [NO] CHAIN]`. +pub fn parse_abort<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + parse_finish(p, FinishKind::Abort).map(|t| StatementKind::Transaction(Box::new(t)).into()) +} + +pub fn parse_transaction<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + if p.eat_keyword("START") { + p.expect_keyword("TRANSACTION")?; + return parse_transaction_modes(p).map(Transaction::Start); + } + if p.eat_keyword("BEGIN") { + return Ok(Transaction::Begin( + first_of(p, &["TRAN", "TRANSACTION", "WORK"]).map(Cow::Borrowed), + )); + } + if p.at_keyword("COMMIT") { + return parse_finish(p, FinishKind::Commit); + } + if p.at_keyword("END") { + return parse_finish(p, FinishKind::End); + } + if p.at_keyword("ROLLBACK") { + return parse_finish(p, FinishKind::Rollback); + } + if p.eat_keyword("SAVEPOINT") { + return p.parse_ident().map(Transaction::Savepoint); + } + p.expect_keyword("RELEASE")?; + p.eat_keyword("SAVEPOINT"); + p.parse_ident().map(Transaction::Release) +} + +// USE + +fn parse_use_part<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let token = p.peek(); + if token.kind == TokenKind::String { + p.advance(); + return Ok(Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: Some(char::from(token.text.as_bytes()[0])), + span: token.span, + }); + } + p.parse_ident() +} + +/// Parses a name for `USE`, in which each part can be a string. +pub fn parse_use_name<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let mut parts = vec![parse_use_part(p)?]; + while p.eat_op(".") { + parts.push(parse_use_part(p)?); + } + Ok(ObjectName { parts }) +} + +// EXPLAIN + +fn at_explain_modifier<'a, D: Dialect>(p: &Parser<'a, D>, word: &str) -> bool { + p.at_keyword(word) && !at_statement_end(p, 1) && !p.peek_nth(1).is_op(".") +} + +fn eat_explain_modifier<'a, D: Dialect>(p: &mut Parser<'a, D>, word: &str) -> bool { + let found = at_explain_modifier(p, word); + if found { + p.advance(); + } + found +} + +fn parse_explain_format<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + if !at_explain_modifier(p, "FORMAT") { + return Ok(None); + } + p.advance(); + let equals = p.eat_op("="); + let token = p.expect_kind(TokenKind::Word, "a format name")?; + Ok(Some(ExplainFormat { + equals, + name: token.text.into(), + })) +} + +fn at_explainable_statement<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_op("(") + || at_any( + p, + &[ + "SELECT", "WITH", "VALUES", "INSERT", "UPDATE", "DELETE", "MERGE", "CREATE", + "DROP", "ALTER", "TRUNCATE", + ], + ) +} + +pub fn parse_explain<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let keyword = first_of(p, &["EXPLAIN", "DESCRIBE", "DESC"]) + .ok_or_else(|| p.expected("EXPLAIN or DESCRIBE"))?; + let options = if keyword == "EXPLAIN" { + D::parse_explain_options(p)? + } else { + Vec::new() + }; + let detail = if keyword == "EXPLAIN" { + None + } else if at_explain_modifier(p, "EXTENDED") { + p.advance(); + Some("EXTENDED") + } else if at_explain_modifier(p, "FORMATTED") { + p.advance(); + Some("FORMATTED") + } else { + None + }; + let analyze = eat_explain_modifier(p, "ANALYZE"); + let verbose = eat_explain_modifier(p, "VERBOSE"); + let estimate = eat_explain_modifier(p, "ESTIMATE"); + let query_plan = at_explain_modifier(p, "QUERY") && p.peek_nth(1).is_word("PLAN"); + if query_plan { + p.advance(); + p.advance(); + } + let format = parse_explain_format(p)?; + let target = D::parse_explain_target(p)?; + Ok(Explain { + keyword: keyword.into(), + options, + detail: detail.map(Cow::Borrowed), + analyze, + verbose, + estimate, + query_plan, + format, + target, + }) +} + +/// Parses what `EXPLAIN` or `DESCRIBE` applies to. +pub fn parse_explain_target<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + if at_explainable_statement(p) { + return Ok(ExplainTarget::Statement(Box::new( + p.nested(Parser::parse_statement)?, + ))); + } + Ok(ExplainTarget::Table { + table_keyword: false, + name: parse_object_name(p)?, + }) +} + +/// Parses `USE name`. +pub fn parse_use<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("USE")?; + parse_use_name(p) +} + +/// Parses a parenthesized list of `EXPLAIN` options, for dialects with them. +pub fn parse_explain_option_list<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult>> { + // No option is named like the start of a statement, so these mean the + // parentheses hold a query: `EXPLAIN (VALUES (1))`. + let next = p.peek_nth(1); + let is_query = query_starts_at(p, 1) + || next.is_op("(") + || ["TABLE", "INSERT", "UPDATE", "DELETE", "MERGE"] + .iter() + .any(|word| next.is_word(word)); + if !p.at_op("(") || is_query { + return Ok(Vec::new()); + } + p.advance(); + let options = p.parse_comma_separated(parse_explain_option)?; + p.expect_op(")")?; + Ok(options) +} + +fn is_option_value(token: Token<'_>) -> bool { + matches!( + token.kind, + TokenKind::Word | TokenKind::QuotedIdent | TokenKind::String | TokenKind::Number + ) +} + +fn parse_explain_option<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let name = p.parse_name_part()?; + let sign = if p.eat_op("-") { + "-" + } else if p.eat_op("+") { + "+" + } else { + "" + }; + let token = p.peek(); + let value = if is_option_value(token) { + p.advance(); + Some(token.text) + } else if sign.is_empty() { + None + } else { + return Err(p.expected("a number")); + }; + Ok(ExplainOption { + name, + sign: sign.into(), + value: value.map(Cow::Borrowed), + }) +} + +// SET + +fn parse_set_scope<'a, D: Dialect>(p: &mut Parser<'a, D>) -> Option<&'static str> { + first_of(p, &["LOCAL", "SESSION", "GLOBAL"]) +} + +fn is_assignment_token(token: Token<'_>) -> bool { + token.is_op("=") || token.is_word("TO") +} + +/// True if what follows `SET` and any scope is not a variable assignment. +pub fn at_special_set<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + let scoped = ["LOCAL", "SESSION", "GLOBAL"] + .iter() + .any(|word| p.peek_nth(1).is_word(word)); + let at = 1 + usize::from(scoped); + let word = p.peek_nth(at); + let next = p.peek_nth(at + 1); + (word.is_word("ROLE") && !is_assignment_token(next)) + || word.is_word("AUTHORIZATION") + || word.is_word("CHARACTERISTICS") + || word.is_word("TRANSACTION") + || (word.is_word("TIME") && next.is_word("ZONE")) +} + +pub fn parse_set<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let special = at_special_set(p); + p.expect_keyword("SET")?; + let scope = parse_set_scope(p); + if special { + return parse_special_set(p, scope); + } + let name = parse_object_name(p)?; + if !is_assignment_token(p.peek()) { + return Err(p.expected("= or TO")); + } + p.advance(); + let values = p.parse_comma_separated(Parser::parse_expr)?; + Ok(SetStatement::Variable { + scope: scope.map(Cow::Borrowed), + name, + values, + }) +} + +fn parse_special_set<'a, D: Dialect>( + p: &mut Parser<'a, D>, + scope: Option<&'static str>, +) -> PResult> { + if p.eat_keyword("ROLE") { + let role = p.parse_expr()?; + return Ok(SetStatement::Role { + scope: scope.map(Cow::Borrowed), + role, + }); + } + if p.eat_keyword("AUTHORIZATION") { + let user = p.parse_expr()?; + return Ok(SetStatement::Authorization { + scope: scope.map(Cow::Borrowed), + user, + }); + } + if p.eat_keyword("CHARACTERISTICS") { + p.expect_keyword("AS")?; + p.expect_keyword("TRANSACTION")?; + let modes = parse_transaction_modes(p)?; + return Ok(SetStatement::Transaction { + characteristics: true, + modes, + snapshot: None, + }); + } + if p.eat_keyword("TRANSACTION") { + let snapshot = if p.eat_keyword("SNAPSHOT") { + Some(parse_string(p)?) + } else { + None + }; + let modes = parse_transaction_modes(p)?; + return Ok(SetStatement::Transaction { + characteristics: false, + modes, + snapshot, + }); + } + p.expect_keyword("TIME")?; + p.expect_keyword("ZONE")?; + if p.eat_keyword("TO") { + let name = ObjectName { + parts: vec![Ident { + text: "TIMEZONE".into(), + quote: None, + span: Span::default(), + }], + }; + let values = vec![p.parse_expr()?]; + return Ok(SetStatement::Variable { + scope: scope.map(Cow::Borrowed), + name, + values, + }); + } + let value = p.parse_expr()?; + Ok(SetStatement::TimeZone { + scope: scope.map(Cow::Borrowed), + value, + }) +} + +/// True at `SET NAMES`, for dialects that have it. +pub fn at_set_names<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("SET") && p.peek_nth(1).is_word("NAMES") +} + +/// Parses `SET NAMES charset [COLLATE collation]`. +pub fn parse_set_names<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.advance(); + p.advance(); + let charset = p.nested(Parser::parse_prefix)?; + let collate = if p.eat_keyword("COLLATE") { + Some(p.parse_ident()?) + } else { + None + }; + Ok(SetStatement::Names { charset, collate }) +} + +/// Parses `SET [scope] a = 1, [scope] b = 2`, for dialects that assign +/// several variables at once. +pub fn parse_set_assignments<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + p.expect_keyword("SET")?; + let assignments = p.parse_comma_separated(|p| { + let scope = parse_set_scope(p); + let name = parse_object_name(p)?; + if !is_assignment_token(p.peek()) { + return Err(p.expected("= or TO")); + } + p.advance(); + let value = p.parse_expr()?; + Ok(SetAssignment { + scope: scope.map(Cow::Borrowed), + name, + value, + }) + })?; + Ok(SetStatement::Assignments(assignments)) +} + +// COMMENT and CALL + +const COMMENT_OBJECTS: [&str; 15] = [ + "COLLATION", + "COLUMN", + "DATABASE", + "DOMAIN", + "EXTENSION", + "FUNCTION", + "INDEX", + "PROCEDURE", + "ROLE", + "SCHEMA", + "SEQUENCE", + "TABLE", + "TYPE", + "USER", + "VIEW", +]; + +/// Parses `COMMENT [IF EXISTS] ON kind name IS value`, for dialects with it. +pub fn parse_comment_on<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + parse_comment_on_with(p, &[]) +} + +/// Parses `COMMENT ON` with additional multi-word object kinds, each given +/// as its words. A dialect that has a kind the core lacks lists it here. +pub fn parse_comment_on_with<'a, D: Dialect>( + p: &mut Parser<'a, D>, + extra: &[&[&'static str]], +) -> PResult> { + p.expect_keyword("COMMENT")?; + let if_exists = super::parse_if_exists(p); + p.expect_keyword("ON")?; + let kind = if p.at_keyword("MATERIALIZED") { + parse_kind_words(p, &["IS"]) + } else if let Some(words) = extra.iter().find(|words| { + words + .iter() + .enumerate() + .all(|(i, w)| p.peek_nth(i).is_word(w)) + }) { + words.iter().map(|_| p.advance().text).collect::>() + } else { + let token = p.peek(); + let known = COMMENT_OBJECTS.iter().any(|kind| token.is_word(kind)); + if !known { + return Err(p.expected("a kind of object")); + } + p.advance(); + vec![token.text] + }; + let name = parse_object_name(p)?; + p.expect_keyword("IS")?; + let comment = if p.eat_keyword("NULL") { + None + } else { + Some(parse_string(p)?) + }; + Ok(CommentOn { + if_exists, + kind: kind.into_iter().map(Cow::Borrowed).collect(), + name, + comment, + }) +} + +pub fn parse_call<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + p.expect_keyword("CALL")?; + p.spanned_expr(|p| { + let name = parse_object_name(p)?; + if p.at_op("(") { + return p.parse_function_call(name); + } + Ok(ExprKind::Compound(name).into()) + }) +} diff --git a/sqlparser_v2/src/grammar/xml.rs b/sqlparser_v2/src/grammar/xml.rs new file mode 100644 index 0000000000..04f621f45b --- /dev/null +++ b/sqlparser_v2/src/grammar/xml.rs @@ -0,0 +1,125 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `XMLTABLE`, shared by the dialects that have SQL/XML. + +use super::*; + +/// True at `XMLTABLE (`. +pub fn at_xml_table<'a, D: Dialect>(p: &Parser<'a, D>) -> bool { + p.at_keyword("XMLTABLE") && p.peek_nth(1).is_op("(") +} + +/// Parses `XMLTABLE(...)`, with `PASSING` required if `require_passing`. +pub fn parse_xml_table<'a, D: Dialect>( + p: &mut Parser<'a, D>, + require_passing: bool, +) -> PResult> { + p.expect_keyword("XMLTABLE")?; + p.expect_op("(")?; + let namespaces = if p.eat_keyword("XMLNAMESPACES") { + p.expect_op("(")?; + let namespaces = p.parse_comma_separated(parse_xml_namespace)?; + p.expect_op(")")?; + p.expect_op(",")?; + namespaces + } else { + Vec::new() + }; + let row_expression = p.parse_expr()?; + let passing = if p.eat_keyword("PASSING") { + p.parse_comma_separated(parse_xml_passing_argument)? + } else if require_passing { + return Err(p.expected("PASSING")); + } else { + Vec::new() + }; + p.expect_keyword("COLUMNS")?; + let columns = p.parse_comma_separated(parse_xml_table_column)?; + p.expect_op(")")?; + Ok(TableFactor::XmlTable(Box::new(XmlTable { + namespaces, + row_expression, + passing, + columns, + }))) +} + +fn parse_xml_namespace<'a, D: Dialect>(p: &mut Parser<'a, D>) -> PResult> { + let uri = p.parse_expr()?; + p.expect_keyword("AS")?; + let name = p.parse_ident()?; + Ok(XmlNamespace { uri, name }) +} + +fn parse_xml_passing_argument<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let by_value = p.at_keyword("BY"); + if by_value { + p.advance(); + p.expect_keyword("VALUE")?; + } + let expr = p.parse_expr()?; + let alias = if p.eat_keyword("AS") { + Some(p.parse_ident()?) + } else { + None + }; + Ok(XmlPassingArgument { + by_value, + expr, + alias, + }) +} + +fn parse_xml_table_column<'a, D: Dialect>( + p: &mut Parser<'a, D>, +) -> PResult> { + let name = p.parse_ident()?; + if p.eat_keyword("FOR") { + p.expect_keyword("ORDINALITY")?; + return Ok(XmlTableColumn { + name, + kind: XmlColumnKind::ForOrdinality, + }); + } + let data_type = Box::new(D::parse_data_type(p)?); + let (mut path, mut default, mut not_null) = (None, None, false); + loop { + if path.is_none() && p.eat_keyword("PATH") { + path = Some(p.parse_expr()?); + } else if default.is_none() && p.eat_keyword("DEFAULT") { + default = Some(p.parse_expr()?); + } else if !not_null && p.at_keyword("NOT") && p.peek_nth(1).is_word("NULL") { + p.advance(); + p.advance(); + not_null = true; + } else if !p.eat_keyword("NULL") { + break; + } + } + Ok(XmlTableColumn { + name, + kind: XmlColumnKind::Data { + data_type, + path, + default, + not_null, + }, + }) +} diff --git a/sqlparser_v2/src/lexer.rs b/sqlparser_v2/src/lexer.rs new file mode 100644 index 0000000000..e2776dda15 --- /dev/null +++ b/sqlparser_v2/src/lexer.rs @@ -0,0 +1,392 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Splits SQL into tokens that borrow from the input. +//! +//! Keywords and operators are not enums: a token is just a kind and a slice +//! of the source, so a dialect can introduce new ones without changing this +//! module. + +use crate::ast::Span; +use crate::dialect::Dialect; +use crate::{PResult, ParseError}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TokenKind { + /// An unquoted word: a keyword or an identifier. + Word, + QuotedIdent, + String, + Number, + /// A bind parameter such as `?`, `$1` or `:name`. + Placeholder, + /// `X'AB'` or `0xAB`. + HexString, + /// `$tag$text$tag$`. Only produced by dialects that have this syntax. + DollarString, + /// A literal whose syntax only a dialect knows. That dialect reads it in + /// `parse_prefix`, and the core rejects it wherever it appears. + DialectLiteral, + /// An operator or punctuation. + Op, + Eof, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Token<'a> { + pub kind: TokenKind, + /// The token's full source text, including any quotes. + pub text: &'a str, + pub span: Span, +} + +impl Token<'_> { + /// True if this is the unquoted word `word`, in any case. + pub fn is_word(&self, word: &str) -> bool { + self.kind == TokenKind::Word && self.text.eq_ignore_ascii_case(word) + } + + /// True if this is the operator or punctuation `op`. + pub fn is_op(&self, op: &str) -> bool { + self.kind == TokenKind::Op && self.text == op + } +} + +/// The kind and byte length of a token found at the start of the input. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Lexeme { + pub kind: TokenKind, + pub len: usize, +} + +pub type LexResult = Result; + +/// Tokenizes `sql`. The result always ends with an [`TokenKind::Eof`] token. +pub fn tokenize(sql: &str) -> PResult>> { + if u32::try_from(sql.len()).is_err() { + return Err(lex_error("input is larger than 4GiB", 0)); + } + + let mut tokens = Vec::with_capacity(sql.len() / 4 + 1); + let mut pos = 0; + let mut after_line_comment = false; + loop { + let rest = &sql[pos..]; + let trimmed = rest.trim_ascii_start(); + let gap = &rest[..rest.len() - trimmed.len()]; + pos += gap.len(); + if trimmed.is_empty() { + break; + } + + if (after_line_comment || gap.contains(['\n', '\r'])) + && let Some((index, len)) = D::lex_payload_line(sql, &tokens, pos) + { + let text = trimmed + .get(..len) + .filter(|text| !text.is_empty()) + .ok_or_else(|| lex_error("dialect produced an invalid token length", pos))?; + let end = pos + len; + tokens.insert( + index.min(tokens.len()), + Token { + kind: TokenKind::DialectLiteral, + text, + span: span(pos, end), + }, + ); + pos = end; + continue; + } + + if let Some(comment) = D::lex_comment(trimmed) { + let len = comment.map_err(|message| lex_error(message, pos))?; + if trimmed.get(..len).is_none_or(str::is_empty) { + return Err(lex_error("dialect produced an invalid comment length", pos)); + } + pos += len; + after_line_comment = trimmed[..len].ends_with(['\n', '\r']); + continue; + } + after_line_comment = false; + + let adjacent = tokens + .last() + .filter(|token: &&Token<'_>| token.span.end as usize == pos) + .copied(); + let lexeme = D::lex_after(adjacent, trimmed) + .or_else(|| D::lex_token(trimmed)) + .unwrap_or_else(|| lex_core(trimmed)) + .map_err(|message| lex_error(message, pos))?; + let text = trimmed + .get(..lexeme.len) + .filter(|text| !text.is_empty()) + .ok_or_else(|| lex_error("dialect produced an invalid token length", pos))?; + + let end = pos + lexeme.len; + tokens.push(Token { + kind: lexeme.kind, + text, + span: span(pos, end), + }); + pos = end; + } + + tokens.push(Token { + kind: TokenKind::Eof, + text: "", + span: span(pos, pos), + }); + Ok(tokens) +} + +fn span(start: usize, end: usize) -> Span { + // `tokenize` has checked that all offsets fit in a u32. + Span { + start: start as u32, + end: end as u32, + } +} + +fn lex_error(message: &str, pos: usize) -> ParseError { + ParseError { + message: message.to_string(), + span: span(pos, pos + 1), + } +} + +/// Lexes one token of the core grammar. `rest` must not be empty. +#[inline] +pub fn lex_core(rest: &str) -> LexResult { + let bytes = rest.as_bytes(); + match bytes[0] { + b'\'' => quoted(rest, TokenKind::String), + b'"' => quoted(rest, TokenKind::QuotedIdent), + b'0' if bytes.get(1) == Some(&b'x') => hex_number(bytes), + b'x' | b'X' if bytes.get(1) == Some(&b'\'') => { + let string = quoted(&rest[1..], TokenKind::HexString)?; + Ok(Lexeme { + kind: TokenKind::HexString, + len: string.len + 1, + }) + } + b'0'..=b'9' => number(bytes), + b'.' if bytes.get(1).is_some_and(u8::is_ascii_digit) => number(bytes), + b'?' | b'$' | b':' => placeholder(bytes).map_or_else(|| operator(bytes), Ok), + b if is_word_start(b) => Ok(word(bytes)), + _ => operator(bytes), + } +} + +/// Lexes text quoted by the first byte of `rest`, in which the quote is +/// escaped by doubling it. +#[inline] +pub fn quoted(rest: &str, kind: TokenKind) -> LexResult { + let bytes = rest.as_bytes(); + let quote = bytes[0]; + let mut i = 1; + while i < bytes.len() { + if bytes[i] == quote { + if bytes.get(i + 1) == Some("e) { + i += 2; + continue; + } + return Ok(Lexeme { kind, len: i + 1 }); + } + i += 1; + } + Err("unterminated quoted text") +} + +#[inline] +fn is_word_start(b: u8) -> bool { + b.is_ascii_alphabetic() || b == b'_' || !b.is_ascii() +} + +#[inline] +fn word(bytes: &[u8]) -> Lexeme { + let len = bytes + .iter() + .position(|&b| !is_word_start(b) && !b.is_ascii_digit()) + .unwrap_or(bytes.len()); + Lexeme { + kind: TokenKind::Word, + len, + } +} + +#[inline] +fn hex_number(bytes: &[u8]) -> LexResult { + let digits = bytes[2..] + .iter() + .take_while(|b| b.is_ascii_hexdigit()) + .count(); + let len = 2 + digits; + if bytes.get(len).is_some_and(|&b| is_word_start(b)) { + return Err("invalid number"); + } + Ok(Lexeme { + kind: TokenKind::HexString, + len, + }) +} + +#[inline] +/// True if the point at `at` in `bytes` belongs to the number before it. A +/// point followed by a letter or another point is left for the parser, unless +/// the letter starts an exponent, as in `1.e5`. +pub fn point_continues_number(bytes: &[u8], at: usize) -> bool { + if bytes.get(at) != Some(&b'.') { + return false; + } + match bytes.get(at + 1) { + Some(b'e' | b'E') => { + let sign = usize::from(matches!(bytes.get(at + 2), Some(b'+' | b'-'))); + bytes.get(at + 2 + sign).is_some_and(u8::is_ascii_digit) + } + Some(&b) => !(is_word_start(b) || b == b'.'), + None => true, + } +} + +fn number(bytes: &[u8]) -> LexResult { + let digits = |from: usize| { + bytes[from..] + .iter() + .take_while(|b| b.is_ascii_digit()) + .count() + }; + let mut len = digits(0); + if point_continues_number(bytes, len) { + len += 1 + digits(len + 1); + } + if matches!(bytes.get(len), Some(b'e' | b'E')) { + let sign = usize::from(matches!(bytes.get(len + 1), Some(b'+' | b'-'))); + let exponent = digits(len + 1 + sign); + if exponent > 0 { + len += 1 + sign + exponent; + } + } + // Otherwise `1a` would silently read as `1` with the alias `a`. + if bytes.get(len).is_some_and(|&b| is_word_start(b)) { + return Err("invalid number"); + } + Ok(Lexeme { + kind: TokenKind::Number, + len, + }) +} + +/// The token for `?`, `?1`, `$1`, `$name` or `:name`, if one starts here. +#[inline] +fn placeholder(bytes: &[u8]) -> Option { + let is_digit = |b: &u8| b.is_ascii_digit(); + let is_name = |b: &u8| is_word_start(*b) || b.is_ascii_digit(); + let tail = &bytes[1..]; + let extra = match bytes[0] { + b'?' => tail.iter().take_while(|b| is_digit(b)).count(), + b'$' if tail.first().is_some_and(is_name) => tail.iter().take_while(|b| is_name(b)).count(), + b':' if tail.first().is_some_and(|&b| is_word_start(b)) => { + tail.iter().take_while(|b| is_name(b)).count() + } + _ => return None, + }; + Some(Lexeme { + kind: TokenKind::Placeholder, + len: 1 + extra, + }) +} + +#[inline] +fn operator(bytes: &[u8]) -> LexResult { + let len = match bytes { + [b'<', b'=' | b'>' | b'<', ..] + | [b'>', b'=' | b'>', ..] + | [b'!', b'=', ..] + | [b'|', b'|', ..] + | [b'=', b'>', ..] => 2, + [ + b'=' | b'<' | b'>' | b'+' | b'-' | b'*' | b'/' | b'%' | b'(' | b')' | b',' | b';' + | b'.' | b'|' | b'&' | b'^' | b'[' | b']', + .., + ] => 1, + _ => return Err("unexpected character"), + }; + Ok(Lexeme { + kind: TokenKind::Op, + len, + }) +} + +/// The core comment syntax: `--` to the end of the line, and nesting `/* */`. +#[inline] +pub fn lex_core_comment(rest: &str) -> Option> { + match rest.as_bytes() { + [b'-', b'-', ..] => Some(Ok(line_comment(rest))), + [b'/', b'*', ..] => Some(block_comment(rest, true)), + _ => None, + } +} + +/// The length of a comment running to the end of the line. +pub fn line_comment(rest: &str) -> usize { + rest.find('\n').map_or(rest.len(), |newline| newline + 1) +} + +/// The length of the block comment starting at `rest`. +pub fn block_comment(rest: &str, nested: bool) -> Result { + let bytes = rest.as_bytes(); + let mut depth = 1; + let mut i = 2; + while i + 1 < bytes.len() { + match (bytes[i], bytes[i + 1]) { + (b'*', b'/') => { + depth -= 1; + i += 2; + if depth == 0 { + return Ok(i); + } + } + (b'/', b'*') if nested => { + depth += 1; + i += 2; + } + _ => i += 1, + } + } + Err("unterminated block comment") +} + +/// Like [`quoted`], for dialects where a backslash also escapes the next byte. +#[inline] +pub fn quoted_with_backslash(rest: &str, kind: TokenKind) -> LexResult { + let bytes = rest.as_bytes(); + let quote = bytes[0]; + let mut i = 1; + while i < bytes.len() { + let Some(off) = bytes[i..].iter().position(|&b| b == quote || b == b'\\') else { + break; + }; + i += off; + if bytes[i] == b'\\' || bytes.get(i + 1) == Some("e) { + i += 2; + } else { + return Ok(Lexeme { kind, len: i + 1 }); + } + } + Err("unterminated quoted text") +} diff --git a/sqlparser_v2/src/lib.rs b/sqlparser_v2/src/lib.rs new file mode 100644 index 0000000000..d05d6317ba --- /dev/null +++ b/sqlparser_v2/src/lib.rs @@ -0,0 +1,86 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! A zero-copy Pratt SQL parser with composable dialects. + +// The derive macros name this crate's traits by their public paths. +pub mod ast; +pub mod dialect; +pub mod display; +pub mod grammar; +pub mod lexer; +pub mod parser; + +use std::fmt; + +use ast::{Expr, Query, Span, Statement}; +use dialect::Dialect; +use parser::Parser; + +#[derive(Debug, Clone, PartialEq)] +pub struct ParseError { + pub message: String, + pub span: Span, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} at byte {}", self.message, self.span.start) + } +} + +impl std::error::Error for ParseError {} + +pub type PResult = Result; + +/// Parses a list of statements separated by semicolons. +pub fn parse_sql(sql: &str) -> PResult>> { + parse_statements(&mut Parser::::new(sql)?) +} + +fn parse_statements<'a, D: Dialect>( + parser: &mut Parser<'a, D>, +) -> PResult>> { + let mut statements = Vec::new(); + loop { + while parser.eat_op(";") {} + if parser.at_eof() { + return Ok(statements); + } + statements.push(parser.parse_statement()?); + if !parser.at_op(";") && !parser.at_eof() { + return Err(parser.expected("end of statement")); + } + } +} + +/// Parses a single query, with an optional trailing semicolon. +pub fn parse_query(sql: &str) -> PResult> { + let mut parser = Parser::::new(sql)?; + let query = D::parse_query(&mut parser)?; + parser.eat_op(";"); + parser.expect_eof()?; + Ok(query) +} + +/// Parses a single expression. +pub fn parse_expr(sql: &str) -> PResult> { + let mut parser = Parser::::new(sql)?; + let expr = parser.parse_expr()?; + parser.expect_eof()?; + Ok(expr) +} diff --git a/sqlparser_v2/src/parser.rs b/sqlparser_v2/src/parser.rs new file mode 100644 index 0000000000..d235705d48 --- /dev/null +++ b/sqlparser_v2/src/parser.rs @@ -0,0 +1,516 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The token cursor and the Pratt expression loop. +//! +//! This module holds no grammar. Rules live in [`crate::grammar`] and are +//! always invoked through the [`Dialect`] trait so that a dialect's override +//! applies wherever the rule is used. + +use std::borrow::Cow; +use std::marker::PhantomData; + +use crate::ast::{ + BinaryOp, Expr, Ident, ObjectName, SelectItem, SetOperator, Span, Statement, TableRef, +}; +use crate::dialect::Dialect; +use crate::lexer::{Token, TokenKind, tokenize}; +use crate::{PResult, ParseError}; + +/// The default nesting allowed before parsing fails, protecting the stack. +pub const DEFAULT_MAX_NESTING_DEPTH: usize = 64; + +/// The default limit on the height of a parsed tree. +/// +/// Long operator chains parse in a loop, so they never reach +/// [`DEFAULT_MAX_NESTING_DEPTH`], but they build trees whose destructor and derived +/// traits recurse once per level. This keeps those safe on a 2 MiB stack in a +/// debug build. +/// Debug-build frames grow with the number of `Expr` variants, so this margin +/// shrinks as the grammar grows. `tests/tree_limits.rs` fails when it runs out. +const DEFAULT_MAX_TREE_HEIGHT: usize = 1_200; + +/// Parses the operator at the current token, which has not been consumed. +/// The final argument is the operator's binding power. +pub type InfixParseFn<'a, D> = fn(&mut Parser<'a, D>, ExprOf<'a, D>, u8) -> PResult>; + +type ExprOf<'a, D> = Expr<'a, ::Ext>; + +pub enum InfixAction<'a, D: Dialect> { + /// A left-associative operator producing [`Binary`](crate::ast::ExprKind::Binary). + Binary(BinaryOp<'a>), + Custom(InfixParseFn<'a, D>), +} + +/// How to parse the infix operator at the current token. The binding power +/// and the action are returned together so that they cannot disagree. +pub struct InfixRule<'a, D: Dialect> { + pub bp: u8, + pub action: InfixAction<'a, D>, +} + +impl<'a, D: Dialect> InfixRule<'a, D> { + pub fn binary(bp: u8, op: BinaryOp<'a>) -> Self { + Self { + bp, + action: InfixAction::Binary(op), + } + } + + pub fn custom(bp: u8, parse: InfixParseFn<'a, D>) -> Self { + Self { + bp, + action: InfixAction::Custom(parse), + } + } +} + +/// A set operator at the current token and its binding power. +pub struct SetOperatorRule { + pub bp: u8, + pub op: SetOperator, +} + +pub struct Parser<'a, D: Dialect> { + source: &'a str, + tokens: Vec>, + pos: usize, + depth: usize, + max_nesting_depth: usize, + /// Height of the tree built so far at the current nesting level. + height: usize, + max_tree_height: usize, + /// Flags set by [`Parser::with_context`]. + context: u32, + dialect: PhantomData, +} + +/// Runs a rule and records the span of the node it builds. A macro, because a +/// function would add a stack frame to every level of recursion. +macro_rules! spanned { + ($parser:ident, $rule:expr) => {{ + let start = $parser.peek().span.start; + spanned!($parser, start, $rule) + }}; + ($parser:ident, $start:expr, $rule:expr) => {{ + let mut node = $rule?; + node.span = $parser.span_since($start); + Ok(node) + }}; +} + +impl<'a, D: Dialect> Parser<'a, D> { + /// True if `flag` is set by an enclosing [`Parser::with_context`]. + pub fn has_context(&self, flag: u32) -> bool { + self.context & flag != 0 + } + + /// Runs `rule` with `flag` set, for syntax that means something different + /// inside a particular clause. + pub fn with_context( + &mut self, + flag: u32, + rule: impl FnOnce(&mut Self) -> PResult, + ) -> PResult { + let outer = self.context; + self.context |= flag; + let result = rule(self); + self.context = outer; + result + } + + /// Runs `rule` with `flag` cleared, for syntax where a clause's meaning + /// stops applying, such as inside parentheses. + pub fn without_context( + &mut self, + flag: u32, + rule: impl FnOnce(&mut Self) -> PResult, + ) -> PResult { + let outer = self.context; + self.context &= !flag; + let result = rule(self); + self.context = outer; + result + } + + pub fn new(sql: &'a str) -> PResult { + Ok(Self { + source: sql, + tokens: tokenize::(sql)?, + pos: 0, + depth: 0, + max_nesting_depth: DEFAULT_MAX_NESTING_DEPTH, + height: 0, + max_tree_height: DEFAULT_MAX_TREE_HEIGHT, + context: 0, + dialect: PhantomData, + }) + } + + /// Sets the tallest tree this parser will build. Raising it above the + /// default is only safe where every thread that drops, clones, compares + /// or walks the tree has a correspondingly larger stack. + pub fn with_max_tree_height(mut self, max_tree_height: usize) -> Self { + self.max_tree_height = max_tree_height; + self + } + + /// Sets how deeply rules may nest, such as parenthesized expressions and + /// subqueries, before parsing fails. Each level uses stack, so raising it + /// above the default is only safe on a correspondingly larger stack. + pub fn with_max_nesting_depth(mut self, max_nesting_depth: usize) -> Self { + self.max_nesting_depth = max_nesting_depth; + self + } + + /// How deeply rules may nest; see [`Parser::with_max_nesting_depth`]. + pub fn max_nesting_depth(&self) -> usize { + self.max_nesting_depth + } + + /// The SQL being parsed, for a rule that joins adjacent tokens into one + /// slice. + pub fn source(&self) -> &'a str { + self.source + } + + pub fn peek(&self) -> Token<'a> { + self.tokens[self.pos] + } + + /// The source text of `span`, which may cover several tokens. + pub fn text(&self, span: crate::ast::Span) -> &'a str { + &self.source[span.start as usize..span.end as usize] + } + + /// The token `n` places after the current one, or the final + /// [`TokenKind::Eof`] token. + pub fn peek_nth(&self, n: usize) -> Token<'a> { + self.tokens[(self.pos + n).min(self.tokens.len() - 1)] + } + + /// The whitespace and comments just before the token `n` places after + /// the current one. The lexer drops these, so this is the only way for a + /// dialect to give meaning to a comment. + pub fn gap_before_nth(&self, n: usize) -> &'a str { + let index = (self.pos + n).min(self.tokens.len() - 1); + let start = match index { + 0 => 0, + _ => self.tokens[index - 1].span.end as usize, + }; + &self.source[start..self.tokens[index].span.start as usize] + } + + /// Returns the current token and moves past it. Stays on the final + /// [`TokenKind::Eof`] token once it is reached. + pub fn advance(&mut self) -> Token<'a> { + let token = self.peek(); + if token.kind != TokenKind::Eof { + self.pos += 1; + } + token + } + + pub fn at_keyword(&self, keyword: &str) -> bool { + let token = self.peek(); + token.kind == TokenKind::Word && token.text.eq_ignore_ascii_case(keyword) + } + + pub fn eat_keyword(&mut self, keyword: &str) -> bool { + let found = self.at_keyword(keyword); + if found { + self.advance(); + } + found + } + + pub fn expect_keyword(&mut self, keyword: &str) -> PResult<()> { + if self.eat_keyword(keyword) { + Ok(()) + } else { + Err(self.expected(keyword)) + } + } + + /// Expects each of `keywords` in turn. + pub fn expect_keywords(&mut self, keywords: &[&str]) -> PResult<()> { + keywords + .iter() + .try_for_each(|word| self.expect_keyword(word)) + } + + /// Consumes a token of `kind`, or fails naming `what` was expected. + pub fn expect_kind(&mut self, kind: TokenKind, what: &str) -> PResult> { + let token = self.peek(); + if token.kind != kind { + return Err(self.expected(what)); + } + self.advance(); + Ok(token) + } + + pub fn at_op(&self, op: &str) -> bool { + let token = self.peek(); + token.kind == TokenKind::Op && token.text == op + } + + pub fn eat_op(&mut self, op: &str) -> bool { + let found = self.at_op(op); + if found { + self.advance(); + } + found + } + + pub fn expect_op(&mut self, op: &str) -> PResult<()> { + if self.eat_op(op) { + Ok(()) + } else { + Err(self.expected(op)) + } + } + + /// Consumes the `>` that closes a type's angle brackets. When `>>` closes + /// two of them at once, as in `ARRAY>`, it consumes one `>` and + /// leaves the other. + pub fn expect_angle_close(&mut self) -> PResult<()> { + let token = self.peek(); + if token.is_op(">") { + self.advance(); + return Ok(()); + } + if token.kind != TokenKind::Op || !token.text.starts_with('>') || token.text.len() < 2 { + return Err(self.expected(">")); + } + self.tokens[self.pos] = Token { + kind: TokenKind::Op, + text: &token.text[1..], + span: crate::ast::Span { + start: token.span.start + 1, + end: token.span.end, + }, + }; + Ok(()) + } + + pub fn at_eof(&self) -> bool { + self.peek().kind == TokenKind::Eof + } + + pub fn expect_eof(&self) -> PResult<()> { + if self.at_eof() { + Ok(()) + } else { + Err(self.expected("end of input")) + } + } + + /// An error saying that the SQL nests more deeply than `limit`. + fn too_deep(&self, limit: usize) -> ParseError { + ParseError { + message: format!("SQL is nested too deeply (the limit is {limit})"), + span: self.peek().span, + } + } + + /// An error saying that `what` was expected at the current token. + pub fn expected(&self, what: &str) -> ParseError { + let token = self.peek(); + let found = match token.kind { + TokenKind::Eof => "end of input", + _ => token.text, + }; + ParseError { + message: format!("expected {what}, found {found}"), + span: token.span, + } + } + + /// True if the current token can be an alias without a preceding `AS`. + pub fn at_implicit_alias(&self) -> bool { + let token = self.peek(); + self.at_ident() && !(token.kind == TokenKind::Word && D::is_reserved_for_alias(token.text)) + } + + /// True if the current token can be used as an identifier. + pub fn at_ident(&self) -> bool { + let token = self.peek(); + match token.kind { + TokenKind::QuotedIdent => true, + TokenKind::Word => !D::is_reserved(token.text), + _ => false, + } + } + + pub fn parse_ident(&mut self) -> PResult> { + if !self.at_ident() { + return Err(self.expected("identifier")); + } + let token = self.advance(); + Ok(match token.kind { + TokenKind::QuotedIdent => Ident { + text: Cow::Borrowed(&token.text[1..token.text.len() - 1]), + quote: token.text.chars().next(), + span: token.span, + }, + _ => Ident { + text: token.text.into(), + quote: None, + span: token.span, + }, + }) + } + + /// Parses a name after a dot, where reserved words are allowed. + pub fn parse_name_part(&mut self) -> PResult> { + D::parse_name_part(self) + } + + pub fn parse_expr(&mut self) -> PResult> { + self.parse_expr_bp(0) + } + + /// Parses an expression containing only operators that bind tighter than + /// `min_bp`. + pub fn parse_expr_bp(&mut self, min_bp: u8) -> PResult> { + self.nested(|p| p.pratt_loop(min_bp)) + } + + /// Runs a rule that can recurse, failing if nesting gets too deep. + /// Every recursive path through the grammar must pass through this. + pub fn nested(&mut self, rule: impl FnOnce(&mut Self) -> PResult) -> PResult { + if self.depth >= self.max_nesting_depth { + return Err(self.too_deep(self.max_nesting_depth)); + } + self.depth += 1; + let outer_height = self.height; + self.height = 0; + let result = rule(self); + self.depth -= 1; + // Siblings do not add up: the tree is as tall as its tallest child. + self.height = outer_height.max(self.height + 1); + if result.is_ok() { + self.check_height()?; + } + result + } + + /// Records that a loop added a level to the tree, failing if it is now + /// too tall. Every loop that builds a left-deep tree must call this. + pub fn deepen(&mut self) -> PResult<()> { + self.deepen_by(1) + } + + /// Like [`Parser::deepen`], for a node that takes more stack to clone or + /// render than one ordinary level of the tree. + pub fn deepen_by(&mut self, levels: usize) -> PResult<()> { + self.height += levels; + self.check_height() + } + + fn check_height(&self) -> PResult<()> { + if self.height > self.max_tree_height { + return Err(self.too_deep(self.max_tree_height)); + } + Ok(()) + } + + /// Parses one or more items separated by commas. + pub fn parse_comma_separated( + &mut self, + mut item: impl FnMut(&mut Self) -> PResult, + ) -> PResult> { + let mut items = vec![item(self)?]; + while self.eat_op(",") { + items.push(item(self)?); + } + Ok(items) + } + + fn pratt_loop(&mut self, min_bp: u8) -> PResult> { + let start = self.peek().span.start; + let mut left = D::parse_prefix(self)?; + left.span = self.span_since(start); + while let Some(rule) = D::infix_rule(self) { + if rule.bp <= min_bp { + break; + } + self.deepen()?; + left = match rule.action { + InfixAction::Binary(op) => { + self.advance(); + crate::grammar::parse_binary_right(self, left, op, rule.bp)? + } + InfixAction::Custom(parse) => { + // Dialect nodes pass through wrapper types, so each level of + // them takes more stack than a core node. + self.deepen()?; + parse(self, left, rule.bp)? + } + }; + left.span = self.span_since(start); + } + Ok(left) + } + + /// Parses a prefix expression alone, recording its span. + pub fn parse_prefix(&mut self) -> PResult> { + spanned!(self, D::parse_prefix(self)) + } + + /// Parses a statement, recording its span. + pub fn parse_statement(&mut self) -> PResult> { + spanned!(self, D::parse_statement(self)) + } + + /// Runs `rule`, recording the span of the expression it builds. Only rules + /// that are reached without going through [`Parser::parse_expr`] need this. + pub fn spanned_expr( + &mut self, + rule: impl FnOnce(&mut Self) -> PResult>, + ) -> PResult> { + spanned!(self, rule(self)) + } + + /// Parses a function call after its `name`, recording its span. + pub fn parse_function_call(&mut self, name: ObjectName<'a>) -> PResult> { + let start = name.parts[0].span.start; + spanned!(self, start, D::parse_function_call(self, name)) + } + + /// Parses a select item, recording its span. + pub fn parse_select_item(&mut self) -> PResult> { + spanned!(self, D::parse_select_item(self)) + } + + /// Parses a table reference, recording its span. + pub fn parse_table_ref(&mut self) -> PResult> { + spanned!(self, D::parse_table_ref(self)) + } + + /// The span from byte offset `start` to the end of the last token read. + pub fn span_since(&self, start: u32) -> Span { + let end = match self.pos { + 0 => start, + pos => self.tokens[pos - 1].span.end, + }; + Span { + start, + end: end.max(start), + } + } +} From 9e7b50cc18e43ae3e64d8e5f39d2afc202dbb0be Mon Sep 17 00:00:00 2001 From: Andy Grove Date: Wed, 18 Nov 2026 09:02:29 -0700 Subject: [PATCH 2/2] Add an opt-in v2 feature that parses with sqlparser_v2 sqlparser::v2::parse_sql parses with the v2 parser and converts its AST to this crate's AST, for the built-in dialects that v2 has. GenericDialect and AnsiDialect have no v2 equivalent and are rejected. Nodes with no conversion yet fail with Error::Unconverted, and parse_sql_with_fallback retries those with this crate's parser. compare runs both parsers. tests/sqlparser_v2.rs checks every statement in tests/v2_corpus.txt against this crate's parser in each dialect: a converted AST must equal this crate's, apart from the cases in v2_known_differences.txt, where the two parsers read the SQL differently. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 3 + sqlparser_bench/Cargo.toml | 6 +- sqlparser_bench/benches/v2_bridge.rs | 78 + src/lib.rs | 2 + src/v2/convert.rs | 1371 ++ src/v2/mod.rs | 134 + tests/sqlparser_v2.rs | 256 + tests/v2_corpus.txt | 29974 +++++++++++++++++++++++++ tests/v2_known_differences.txt | 307 + 10 files changed, 32131 insertions(+), 1 deletion(-) create mode 100644 sqlparser_bench/benches/v2_bridge.rs create mode 100644 src/v2/convert.rs create mode 100644 src/v2/mod.rs create mode 100644 tests/sqlparser_v2.rs create mode 100644 tests/v2_corpus.txt create mode 100644 tests/v2_known_differences.txt diff --git a/Cargo.lock b/Cargo.lock index df2b32ae9f..6a23646d26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -647,6 +647,7 @@ dependencies = [ "serde_json", "simple_logger", "sqlparser_derive", + "sqlparser_v2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 2c1cbe50dd..c1a92dfb63 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,6 +60,8 @@ recursive-protection = ["std", "recursive"] json_example = ["serde_json", "serde"] derive-dialect = ["sqlparser_derive"] visitor = ["sqlparser_derive"] +# Parse with the v2 parser, returning this crate's AST. +v2 = ["std", "dep:sqlparser_v2"] [dependencies] bigdecimal = { version = "0.4.1", features = ["serde"], optional = true } @@ -72,6 +74,7 @@ serde = { version = "1.0", default-features = false, features = ["derive", "allo # https://github.com/rust-lang/cargo/issues/1596 serde_json = { version = "1.0", optional = true } sqlparser_derive = { version = "0.7.0", path = "derive", optional = true } +sqlparser_v2 = { version = "2.0.0", path = "sqlparser_v2", optional = true } [dev-dependencies] simple_logger = "5.0" diff --git a/sqlparser_bench/Cargo.toml b/sqlparser_bench/Cargo.toml index 687d399739..b87b8b1e5c 100644 --- a/sqlparser_bench/Cargo.toml +++ b/sqlparser_bench/Cargo.toml @@ -23,7 +23,7 @@ authors = ["Dandandan "] edition = "2018" [dependencies] -sqlparser = { path = "../" } +sqlparser = { path = "../", features = ["v2"] } [dev-dependencies] criterion = "0.8" @@ -31,3 +31,7 @@ criterion = "0.8" [[bench]] name = "sqlparser_bench" harness = false + +[[bench]] +name = "v2_bridge" +harness = false diff --git a/sqlparser_bench/benches/v2_bridge.rs b/sqlparser_bench/benches/v2_bridge.rs new file mode 100644 index 0000000000..2c67ab8f97 --- /dev/null +++ b/sqlparser_bench/benches/v2_bridge.rs @@ -0,0 +1,78 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Compares this crate's parser with the v2 parser converted to this crate's AST. + +use criterion::{criterion_group, criterion_main, Criterion}; +use sqlparser::dialect::PostgreSqlDialect; +use sqlparser::parser::Parser; +use std::hint::black_box; + +fn large_statement() -> String { + let list = + |f: &dyn Fn(usize) -> String, sep: &str| (0..1000).map(f).collect::>().join(sep); + format!( + "SELECT {} FROM {} WHERE {} ORDER BY {}", + list(&|n| format!("FN_{n}(COL_{n})"), ", "), + list(&|n| format!("TABLE_{n}"), " CROSS JOIN "), + list(&|n| format!("COL_{n} = {n}"), " OR "), + list(&|n| format!("COL_{n} DESC"), ", "), + ) +} + +fn v2_bridge(c: &mut Criterion) { + let dialect = PostgreSqlDialect {}; + let queries = [ + ("select", "SELECT * FROM my_table WHERE 1 = 1".to_string()), + ( + "with_select", + "WITH derived AS (SELECT MAX(a) AS max_a, COUNT(b) AS b_num, user_id \ + FROM MY_TABLE GROUP BY user_id) \ + SELECT * FROM my_table LEFT JOIN derived USING (user_id)" + .to_string(), + ), + ( + "tpch_q5", + "SELECT n_name, sum(l_extendedprice * (1 - l_discount)) AS revenue \ + FROM customer, orders, lineitem, supplier, nation, region \ + WHERE c_custkey = o_custkey AND l_orderkey = o_orderkey AND l_suppkey = s_suppkey \ + AND c_nationkey = s_nationkey AND s_nationkey = n_nationkey \ + AND n_regionkey = r_regionkey AND r_name = 'ASIA' \ + AND o_orderdate >= DATE '1994-01-01' AND o_orderdate < DATE '1995-01-01' \ + GROUP BY n_name ORDER BY revenue DESC" + .to_string(), + ), + ("large_statement", large_statement()), + ]; + let mut group = c.benchmark_group("v2_bridge"); + for (name, sql) in &queries { + assert_eq!( + sqlparser::v2::parse_sql(&dialect, sql).unwrap(), + Parser::parse_sql(&dialect, sql).unwrap() + ); + group.bench_function(format!("{name}/v1"), |b| { + b.iter(|| Parser::parse_sql(&dialect, black_box(sql)).unwrap()) + }); + group.bench_function(format!("{name}/v2"), |b| { + b.iter(|| sqlparser::v2::parse_sql(&dialect, black_box(sql)).unwrap()) + }); + } + group.finish(); +} + +criterion_group!(benches, v2_bridge); +criterion_main!(benches); diff --git a/src/lib.rs b/src/lib.rs index 5f62e86eca..f7fa73d4d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -175,6 +175,8 @@ mod display_utils; pub mod keywords; pub mod parser; pub mod tokenizer; +#[cfg(feature = "v2")] +pub mod v2; #[doc(hidden)] // This is required to make utilities accessible by both the crate-internal diff --git a/src/v2/convert.rs b/src/v2/convert.rs new file mode 100644 index 0000000000..eaf68e9832 --- /dev/null +++ b/src/v2/convert.rs @@ -0,0 +1,1371 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Conversion from the v2 AST to this crate's AST. +//! +//! Every conversion either reproduces what this crate's parser builds for the +//! same SQL, or fails with [`Error::Unconverted`]. + +use sqlparser_v2::ast as v2; +use sqlparser_v2::dialect::builtin::{BuiltinQueryTail, BuiltinSelect}; +use sqlparser_v2::dialect::Builtin; + +use super::Error; +use crate::ast::helpers::attached_token::AttachedToken; +use crate::ast::*; +use crate::dialect::{Dialect, PostgreSqlDialect}; +use crate::parser::{Parser, ParserError}; +use crate::tokenizer::{Location, Span}; + +type Result = core::result::Result; + +type V2Expr<'a> = v2::Expr<'a, Builtin>; + +fn unconverted(what: impl Into) -> Result { + Err(Error::Unconverted(what.into())) +} + +/// Byte offsets to line and column numbers. +struct LineIndex<'s> { + sql: &'s str, + line_starts: Vec, + /// Whether every line is ASCII, so that columns are byte offsets. + ascii: bool, +} + +impl<'s> LineIndex<'s> { + fn new(sql: &'s str) -> Self { + let line_starts = core::iter::once(0) + .chain(sql.match_indices('\n').map(|(i, _)| i + 1)) + .collect(); + Self { + sql, + line_starts, + ascii: sql.is_ascii(), + } + } + + fn location(&self, offset: u32) -> Location { + let offset = (offset as usize).min(self.sql.len()); + let line = self.line_starts.partition_point(|&start| start <= offset); + let start = self.line_starts[line - 1]; + let column = if self.ascii { + offset - start + } else { + self.sql.get(start..offset).map_or(0, |s| s.chars().count()) + }; + Location::new(line as u64, column as u64 + 1) + } + + fn span(&self, span: v2::Span) -> Span { + if span == v2::Span::default() { + return Span::empty(); + } + Span::new(self.location(span.start), self.location(span.end)) + } +} + +pub(super) fn parse_error(sql: &str, error: &sqlparser_v2::ParseError) -> ParserError { + let at = LineIndex::new(sql).location(error.span.start); + ParserError::ParserError(format!("{}{at}", error.message)) +} + +pub(super) struct Converter<'s> { + dialect: &'s dyn Dialect, + lines: LineIndex<'s>, +} + +impl<'s> Converter<'s> { + pub(super) fn new(dialect: &'s dyn Dialect, sql: &'s str) -> Self { + Self { + dialect, + lines: LineIndex::new(sql), + } + } + + pub(super) fn statements( + &self, + statements: &[v2::Statement<'_, Builtin>], + ) -> Result> { + statements.iter().map(|s| self.statement(s)).collect() + } + + fn statement(&self, statement: &v2::Statement<'_, Builtin>) -> Result { + match &statement.kind { + v2::StatementKind::Query(query) => Ok(Statement::Query(Box::new(self.query(query)?))), + other => unconverted(format!("statement {}", variant_name(other))), + } + } + + // Names and literals + + fn ident(&self, ident: &v2::Ident<'_>) -> Ident { + Ident { + value: ident.value().into_owned(), + quote_style: ident.quote, + span: self.lines.span(ident.span), + } + } + + fn idents(&self, idents: &[v2::Ident<'_>]) -> Vec { + idents.iter().map(|i| self.ident(i)).collect() + } + + fn object_name(&self, name: &v2::ObjectName<'_>) -> ObjectName { + ObjectName( + name.parts + .iter() + .map(|part| ObjectNamePart::Identifier(self.ident(part))) + .collect(), + ) + } + + fn literal(&self, literal: &v2::Literal<'_>) -> Result { + Ok(match literal { + v2::Literal::Number(text) => number(text)?, + v2::Literal::String(string) => string_value(string)?, + v2::Literal::HexString(digits) => Value::HexStringLiteral(digits.to_string()), + v2::Literal::DollarQuoted { tag, text } => { + Value::DollarQuotedString(DollarQuotedString { + value: text.to_string(), + tag: (!tag.is_empty()).then(|| tag.to_string()), + }) + } + v2::Literal::Null => Value::Null, + v2::Literal::Boolean(b) => Value::Boolean(*b), + }) + } + + fn value(&self, value: Value, span: v2::Span) -> Expr { + Expr::Value(ValueWithSpan { + value, + span: self.lines.span(span), + }) + } + + /// Converts a type by rendering it and parsing it with this crate's + /// parser, which resolves type names differently in each dialect. + fn data_type(&self, ty: &v2::DataType<'_>) -> Result { + let text = ty.to_string(); + let parsed = Parser::new(self.dialect) + .try_with_sql(&text) + .and_then(|mut parser| { + let ty = parser.parse_data_type()?; + parser.expect_token(&crate::tokenizer::Token::EOF)?; + Ok(ty) + }); + parsed.or_else(|_| unconverted(format!("data type {text}"))) + } + + // Expressions + + fn boxed(&self, expr: &V2Expr<'_>) -> Result> { + self.expr(expr).map(Box::new) + } + + fn exprs(&self, exprs: &[V2Expr<'_>]) -> Result> { + exprs.iter().map(|e| self.expr(e)).collect() + } + + fn opt_expr(&self, expr: Option<&V2Expr<'_>>) -> Result> { + expr.map(|e| self.expr(e)).transpose() + } + + #[cfg_attr(feature = "recursive-protection", recursive::recursive)] + fn expr(&self, expr: &V2Expr<'_>) -> Result { + use v2::ExprKind as K; + Ok(match &expr.kind { + K::Ident(ident) => Expr::Identifier(self.ident(ident)), + K::Compound(name) => Expr::CompoundIdentifier(self.idents(&name.parts)), + K::Literal(literal) => self.value(self.literal(literal)?, expr.span), + K::Placeholder(text) => self.value(Value::Placeholder(text.to_string()), expr.span), + K::Unary { op, expr } => match (op, &expr.kind) { + (v2::UnaryOp::Not, K::Exists(query)) => Expr::Exists { + subquery: Box::new(self.query(query)?), + negated: true, + }, + _ => Expr::UnaryOp { + op: unary_op(op), + expr: self.boxed(expr)?, + }, + }, + K::Binary { left, op, right } => Expr::BinaryOp { + left: self.boxed(left)?, + op: binary_op(op)?, + right: self.boxed(right)?, + }, + K::Cast { expr, ty, style } => Expr::Cast { + kind: match style { + v2::CastStyle::Function => CastKind::Cast, + v2::CastStyle::TryFunction => CastKind::TryCast, + v2::CastStyle::SafeFunction => CastKind::SafeCast, + v2::CastStyle::DoubleColon => CastKind::DoubleColon, + }, + expr: self.boxed(expr)?, + data_type: self.data_type(ty)?, + format: None, + }, + K::Interval(interval) => Expr::Interval(Interval { + value: self.boxed(&interval.value)?, + leading_field: interval + .leading_field + .as_deref() + .map(date_time_field) + .transpose()?, + leading_precision: interval + .leading_precision + .as_deref() + .map(u64_arg) + .transpose()?, + last_field: interval + .last_field + .as_deref() + .map(date_time_field) + .transpose()?, + fractional_seconds_precision: interval + .fractional_seconds_precision + .as_deref() + .map(u64_arg) + .transpose()?, + }), + K::TypedString(typed) => Expr::TypedString(TypedString { + data_type: self.data_type(&typed.ty)?, + value: ValueWithSpan { + value: string_value(&typed.value)?, + span: Span::empty(), + }, + uses_odbc_syntax: false, + }), + K::Special(special) => self.special(special)?, + K::Function { + name, + args, + options, + } => self.function(name, args, options.as_deref())?, + K::Subquery(query) => Expr::Subquery(Box::new(self.query(query)?)), + K::Exists(query) => Expr::Exists { + subquery: Box::new(self.query(query)?), + negated: false, + }, + K::InList { + expr, + list, + negated, + } => Expr::In { + expr: self.boxed(expr)?, + target: InTarget::List(self.exprs(list)?), + negated: *negated, + global: false, + }, + K::InSubquery { + expr, + subquery, + negated, + } => Expr::In { + expr: self.boxed(expr)?, + target: InTarget::Subquery(Box::new(self.query(subquery)?)), + negated: *negated, + global: false, + }, + K::Is { + expr, + test, + negated, + } => self.is(expr, test, *negated)?, + K::Like { + expr, + pattern, + negated, + kind, + escape, + } => { + let expr = self.boxed(expr)?; + let pattern = self.boxed(pattern)?; + let escape_char = escape.as_deref().map(|e| self.boxed(e)).transpose()?; + let negated = *negated; + match kind { + v2::LikeKind::Like => Expr::Like { + negated, + any: false, + expr, + pattern, + escape_char, + }, + v2::LikeKind::ILike => Expr::ILike { + negated, + any: false, + expr, + pattern, + escape_char, + }, + v2::LikeKind::SimilarTo => Expr::SimilarTo { + negated, + expr, + pattern, + escape_char, + }, + v2::LikeKind::Named(name) if escape_char.is_none() => { + let regexp = match name.to_ascii_uppercase().as_str() { + "REGEXP" => true, + "RLIKE" => false, + _ => return unconverted(format!("{name} operator")), + }; + Expr::RLike { + negated, + expr, + pattern, + regexp, + } + } + v2::LikeKind::Named(name) => return unconverted(format!("{name} operator")), + } + } + K::Between { + expr, + low, + high, + negated, + } => Expr::Between { + expr: self.boxed(expr)?, + negated: *negated, + low: self.boxed(low)?, + high: self.boxed(high)?, + }, + K::Case(case) => Expr::Case { + case_token: AttachedToken::empty(), + end_token: AttachedToken::empty(), + operand: case.operand.as_ref().map(|e| self.boxed(e)).transpose()?, + conditions: case + .branches + .iter() + .map(|branch| { + Ok(CaseWhen { + condition: self.expr(&branch.condition)?, + result: self.expr(&branch.result)?, + }) + }) + .collect::>()?, + else_result: case + .else_result + .as_ref() + .map(|e| self.boxed(e)) + .transpose()?, + }, + K::Nested(inner) => Expr::Nested(self.boxed(inner)?), + K::Ext(_) => return unconverted("dialect-specific expression"), + }) + } + + fn is(&self, expr: &V2Expr<'_>, test: &v2::IsTest<'_, Builtin>, negated: bool) -> Result { + let expr = self.boxed(expr)?; + Ok(match (test, negated) { + (v2::IsTest::Null, false) => Expr::IsNull(expr), + (v2::IsTest::Null, true) => Expr::IsNotNull(expr), + (v2::IsTest::True, false) => Expr::IsTrue(expr), + (v2::IsTest::True, true) => Expr::IsNotTrue(expr), + (v2::IsTest::False, false) => Expr::IsFalse(expr), + (v2::IsTest::False, true) => Expr::IsNotFalse(expr), + (v2::IsTest::Unknown, false) => Expr::IsUnknown(expr), + (v2::IsTest::Unknown, true) => Expr::IsNotUnknown(expr), + (v2::IsTest::DistinctFrom(other), false) => { + Expr::IsDistinctFrom(expr, self.boxed(other)?) + } + (v2::IsTest::DistinctFrom(other), true) => { + Expr::IsNotDistinctFrom(expr, self.boxed(other)?) + } + (v2::IsTest::Json { .. }, _) => return unconverted("IS JSON"), + (v2::IsTest::Normalized(_), _) => return unconverted("IS NORMALIZED"), + }) + } + + fn special(&self, special: &v2::SpecialExpr<'_, Builtin>) -> Result { + use v2::SpecialExpr as S; + Ok(match special { + S::Quantified { + left, + op, + quantifier, + right, + } => { + let left = self.boxed(left)?; + let compare_op = binary_op(op)?; + let right = self.boxed(right)?; + match quantifier { + v2::Quantifier::Any | v2::Quantifier::Some => Expr::AnyOp { + left, + compare_op, + right, + is_some: matches!(quantifier, v2::Quantifier::Some), + }, + v2::Quantifier::All => Expr::AllOp { + left, + compare_op, + right, + }, + } + } + S::AtTimeZone { expr, zone } => Expr::AtTimeZone { + timestamp: self.boxed(expr)?, + time_zone: self.boxed(zone)?, + }, + S::Collate { expr, collation } => Expr::Collate { + expr: self.boxed(expr)?, + collation: self.object_name(collation), + }, + S::Subscript { .. } | S::Slice { .. } => self.subscripts(special)?, + S::Array(items) => Expr::Array(Array { + elem: self.exprs(items)?, + named: true, + }), + S::Tuple(items) => Expr::Tuple(self.exprs(items)?), + S::Extract { field, expr } => Expr::Extract { + field: date_time_field(field)?, + syntax: ExtractSyntax::From, + expr: self.boxed(expr)?, + }, + S::Round { ceil, expr, field } => { + let expr = self.boxed(expr)?; + let field = CeilFloorKind::DateTimeField(date_time_field(field)?); + if *ceil { + Expr::Ceil { expr, field } + } else { + Expr::Floor { expr, field } + } + } + S::Position { needle, haystack } => Expr::Position { + expr: self.boxed(needle)?, + r#in: self.boxed(haystack)?, + }, + S::Substring { + shorthand, + expr, + from, + length, + } => Expr::Substring { + expr: self.boxed(expr)?, + substring_from: from.as_ref().map(|e| self.boxed(e)).transpose()?, + substring_for: length.as_ref().map(|e| self.boxed(e)).transpose()?, + special: false, + shorthand: *shorthand, + }, + S::Trim { side, what, expr } => Expr::Trim { + trim_where: side.as_ref().map(|side| match side { + v2::TrimSide::Both => TrimWhereField::Both, + v2::TrimSide::Leading => TrimWhereField::Leading, + v2::TrimSide::Trailing => TrimWhereField::Trailing, + }), + trim_what: what.as_ref().map(|e| self.boxed(e)).transpose()?, + expr: self.boxed(expr)?, + trim_characters: None, + }, + S::Overlay { + expr, + what, + from, + length, + } => Expr::Overlay { + expr: self.boxed(expr)?, + overlay_what: self.boxed(what)?, + overlay_from: self.boxed(from)?, + overlay_for: length.as_ref().map(|e| self.boxed(e)).transpose()?, + }, + S::Grouping { kind, sets } => { + let sets = sets + .iter() + .map(|set| self.exprs(set)) + .collect::>()?; + match kind { + v2::GroupingKind::Rollup => Expr::Rollup(sets), + v2::GroupingKind::Cube => Expr::Cube(sets), + v2::GroupingKind::Sets => Expr::GroupingSets(sets), + } + } + // This crate reads these as functions only in PostgreSQL. + S::Niladic(name) + if !self.dialect.is::() + && name.quote.is_none() + && ["CURRENT_CATALOG", "CURRENT_USER", "SESSION_USER", "USER"] + .iter() + .any(|word| name.text.eq_ignore_ascii_case(word)) => + { + Expr::Identifier(self.ident(name)) + } + S::Niladic(name) => Expr::Function(Function { + name: ObjectName::from(vec![self.ident(name)]), + uses_odbc_syntax: false, + parameters: FunctionArguments::None, + args: FunctionArguments::None, + filter: None, + null_treatment: None, + over: None, + within_group: vec![], + }), + S::Prior(expr) => Expr::Prior(self.boxed(expr)?), + S::OuterJoinMark(expr) => Expr::OuterJoin(self.boxed(expr)?), + other => return unconverted(format!("expression {}", variant_name(other))), + }) + } + + /// Flattens a chain of subscripts into one access expression. + fn subscripts(&self, special: &v2::SpecialExpr<'_, Builtin>) -> Result { + let mut chain = Vec::new(); + let mut current = special; + let root = loop { + let (inner, subscript) = match current { + v2::SpecialExpr::Subscript { expr, index } => ( + expr, + Subscript::Index { + index: self.expr(index)?, + }, + ), + v2::SpecialExpr::Slice { + expr, + lower, + upper, + step, + } => ( + expr, + Subscript::Slice { + lower_bound: self.opt_expr(lower.as_ref())?, + upper_bound: self.opt_expr(upper.as_ref())?, + stride: self.opt_expr(step.as_ref())?, + }, + ), + other => return unconverted(format!("expression {}", variant_name(other))), + }; + chain.push(AccessExpr::Subscript(subscript)); + match &inner.kind { + v2::ExprKind::Special(next) + if matches!( + **next, + v2::SpecialExpr::Subscript { .. } | v2::SpecialExpr::Slice { .. } + ) => + { + current = next + } + v2::ExprKind::Compound(name) => { + let (first, rest) = + name.parts.split_first().expect("compound names have parts"); + chain.extend( + rest.iter() + .rev() + .map(|part| AccessExpr::Dot(Expr::Identifier(self.ident(part)))), + ); + break Box::new(Expr::Identifier(self.ident(first))); + } + _ => break self.boxed(inner)?, + } + }; + chain.reverse(); + Ok(Expr::CompoundFieldAccess { + root, + access_chain: chain, + }) + } + + fn function( + &self, + name: &v2::ObjectName<'_>, + args: &[v2::FunctionArg<'_, Builtin>], + options: Option<&v2::FunctionOptions<'_, Builtin>>, + ) -> Result { + if options.is_none() { + if let Some(expr) = self.keyword_function(name, args)? { + return Ok(expr); + } + } + let mut list = FunctionArgumentList { + duplicate_treatment: None, + args: self.function_args(args)?, + clauses: vec![], + }; + let mut function = Function { + name: self.object_name(name), + uses_odbc_syntax: false, + parameters: FunctionArguments::None, + args: FunctionArguments::None, + filter: None, + null_treatment: None, + over: None, + within_group: vec![], + }; + if let Some(options) = options { + if options.separator.is_some() || options.on_overflow.is_some() { + return unconverted("function argument clauses"); + } + if !options.parameters.is_empty() { + function.parameters = FunctionArguments::List(FunctionArgumentList { + duplicate_treatment: None, + args: self.function_args(&options.parameters)?, + clauses: vec![], + }); + } + list.duplicate_treatment = match options.quantifier { + v2::SetQuantifier::None => None, + v2::SetQuantifier::All => Some(DuplicateTreatment::All), + v2::SetQuantifier::Distinct => Some(DuplicateTreatment::Distinct), + }; + if let Some(treatment) = &options.inner_null_treatment { + list.clauses + .push(FunctionArgumentClause::IgnoreOrRespectNulls( + null_treatment(treatment), + )); + } + if !options.order_by.is_empty() { + list.clauses.push(FunctionArgumentClause::OrderBy( + self.order_by_items(&options.order_by)?, + )); + } + function.within_group = self.order_by_items(&options.within_group)?; + function.filter = options.filter.as_ref().map(|e| self.boxed(e)).transpose()?; + function.null_treatment = options.null_treatment.as_ref().map(null_treatment); + function.over = options + .over + .as_ref() + .map(|o| self.window_over(o)) + .transpose()?; + } + function.args = FunctionArguments::List(list); + Ok(Expr::Function(function)) + } + + /// Calls that this crate's parser reads into their own nodes. + fn keyword_function( + &self, + name: &v2::ObjectName<'_>, + args: &[v2::FunctionArg<'_, Builtin>], + ) -> Result> { + let [name] = name.parts.as_slice() else { + return Ok(None); + }; + if name.quote.is_some() { + return Ok(None); + } + let mut exprs = Vec::with_capacity(args.len()); + for arg in args { + let v2::FunctionArg::Expr(expr) = arg else { + return Ok(None); + }; + exprs.push(expr); + } + let name = name.text.to_ascii_uppercase(); + Ok(Some(match (name.as_str(), exprs.as_slice()) { + ("SUBSTR" | "SUBSTRING", [expr, rest @ ..]) if rest.len() <= 2 => Expr::Substring { + expr: self.boxed(expr)?, + substring_from: rest.first().map(|e| self.boxed(e)).transpose()?, + substring_for: rest.get(1).map(|e| self.boxed(e)).transpose()?, + special: !rest.is_empty(), + shorthand: name == "SUBSTR", + }, + ("CEIL" | "FLOOR", [expr, scale @ ..]) if scale.len() <= 1 => { + let field = match scale.first().map(|e| &e.kind) { + None => CeilFloorKind::DateTimeField(DateTimeField::NoDateTime), + Some(v2::ExprKind::Literal(literal @ v2::Literal::Number(_))) => { + CeilFloorKind::Scale(ValueWithSpan { + value: self.literal(literal)?, + span: self.lines.span(scale[0].span), + }) + } + Some(_) => return Ok(None), + }; + let expr = self.boxed(expr)?; + if name == "CEIL" { + Expr::Ceil { expr, field } + } else { + Expr::Floor { expr, field } + } + } + ("TRIM", [expr, characters @ ..]) + if characters.is_empty() || self.dialect.supports_comma_separated_trim() => + { + Expr::Trim { + trim_where: None, + trim_what: None, + expr: self.boxed(expr)?, + trim_characters: if characters.is_empty() { + None + } else { + Some( + characters + .iter() + .map(|e| self.expr(e)) + .collect::>()?, + ) + }, + } + } + _ => return Ok(None), + })) + } + + fn function_args(&self, args: &[v2::FunctionArg<'_, Builtin>]) -> Result> { + args.iter() + .map(|arg| { + Ok(match arg { + v2::FunctionArg::Wildcard => FunctionArg::Unnamed(FunctionArgExpr::Wildcard), + v2::FunctionArg::QualifiedWildcard(name) => FunctionArg::Unnamed( + FunctionArgExpr::QualifiedWildcard(self.object_name(name)), + ), + v2::FunctionArg::Expr(expr) => { + FunctionArg::Unnamed(FunctionArgExpr::Expr(self.expr(expr)?)) + } + v2::FunctionArg::Named { name, value } => FunctionArg::Named { + name: self.ident(name), + arg: FunctionArgExpr::Expr(self.expr(value)?), + operator: FunctionArgOperator::RightArrow, + }, + v2::FunctionArg::NamedWith { + name, + operator, + value, + } => FunctionArg::Named { + name: self.ident(name), + arg: FunctionArgExpr::Expr(self.expr(value)?), + operator: match operator.as_ref() { + "=" => FunctionArgOperator::Equals, + ":=" => FunctionArgOperator::Assignment, + ":" => FunctionArgOperator::Colon, + other => { + return unconverted(format!("named argument operator {other}")) + } + }, + }, + }) + }) + .collect() + } + + fn window_over(&self, over: &v2::WindowOver<'_, Builtin>) -> Result { + Ok(match over { + v2::WindowOver::Named(name) => WindowType::NamedWindow(self.ident(name)), + v2::WindowOver::Spec(spec) => WindowType::WindowSpec(self.window_spec(spec)?), + }) + } + + fn window_spec(&self, spec: &v2::WindowSpec<'_, Builtin>) -> Result { + Ok(WindowSpec { + window_name: spec.base.as_ref().map(|i| self.ident(i)), + partition_by: self.exprs(&spec.partition_by)?, + order_by: self.order_by_items(&spec.order_by)?, + window_frame: spec + .frame + .as_ref() + .map(|frame| { + Ok(WindowFrame { + units: match frame.units { + v2::FrameUnits::Rows => WindowFrameUnits::Rows, + v2::FrameUnits::Range => WindowFrameUnits::Range, + v2::FrameUnits::Groups => WindowFrameUnits::Groups, + }, + start_bound: self.frame_bound(&frame.start)?, + end_bound: frame + .end + .as_ref() + .map(|b| self.frame_bound(b)) + .transpose()?, + }) + }) + .transpose()?, + }) + } + + fn frame_bound(&self, bound: &v2::FrameBound<'_, Builtin>) -> Result { + Ok(match bound { + v2::FrameBound::CurrentRow => WindowFrameBound::CurrentRow, + v2::FrameBound::UnboundedPreceding => WindowFrameBound::Preceding(None), + v2::FrameBound::UnboundedFollowing => WindowFrameBound::Following(None), + v2::FrameBound::Preceding(e) => WindowFrameBound::Preceding(Some(self.boxed(e)?)), + v2::FrameBound::Following(e) => WindowFrameBound::Following(Some(self.boxed(e)?)), + }) + } + + // Queries + + #[cfg_attr(feature = "recursive-protection", recursive::recursive)] + fn query(&self, query: &v2::Query<'_, Builtin>) -> Result { + if query.distribution.is_some() + || !query.locks.is_empty() + || !query.pipes.is_empty() + || query.tail != BuiltinQueryTail::default() + { + return unconverted("query clauses"); + } + Ok(Query { + with: query.with.as_deref().map(|w| self.with(w)).transpose()?, + body: Box::new(self.set_expr(&query.body)?), + order_by: if query.order_by.is_empty() { + None + } else { + Some(OrderBy { + kind: OrderByKind::Expressions(self.order_by_items(&query.order_by)?), + interpolate: None, + }) + }, + limit_clause: query.limit.as_deref().map(|l| self.limit(l)).transpose()?, + fetch: query + .fetch + .as_deref() + .map(|fetch| { + Ok(Fetch { + with_ties: fetch.with_ties, + percent: fetch.percent, + quantity: self.opt_expr(fetch.quantity.as_ref())?, + }) + }) + .transpose()?, + locks: vec![], + for_clause: None, + settings: None, + format_clause: None, + pipe_operators: vec![], + }) + } + + fn with(&self, with: &v2::With<'_, Builtin>) -> Result { + Ok(With { + with_token: AttachedToken::empty(), + recursive: with.recursive, + cte_tables: with + .ctes + .iter() + .map(|cte| { + Ok(Cte { + alias: TableAlias { + explicit: false, + name: self.ident(&cte.name), + columns: cte + .columns + .iter() + .map(|c| TableAliasColumnDef::from_name(self.ident(c).value)) + .collect(), + at: None, + }, + query: Box::new(self.query(&cte.query)?), + from: None, + materialized: cte.materialized.map(|m| { + if m { + CteAsMaterialized::Materialized + } else { + CteAsMaterialized::NotMaterialized + } + }), + closing_paren_token: AttachedToken::empty(), + }) + }) + .collect::>()?, + }) + } + + fn limit(&self, limit: &v2::Limit<'_, Builtin>) -> Result { + if limit.all { + return unconverted("LIMIT ALL"); + } + if limit.offset_comma { + let (Some(offset), Some(count)) = (&limit.offset, &limit.count) else { + return unconverted("LIMIT offset, count"); + }; + return Ok(LimitClause::OffsetCommaLimit { + offset: self.expr(offset)?, + limit: self.expr(count)?, + }); + } + Ok(LimitClause::LimitOffset { + limit: self.opt_expr(limit.count.as_ref())?, + offset: limit + .offset + .as_ref() + .map(|offset| { + Ok(Offset { + value: self.expr(offset)?, + rows: match limit.offset_rows { + v2::OffsetRows::None => OffsetRows::None, + v2::OffsetRows::Row => OffsetRows::Row, + v2::OffsetRows::Rows => OffsetRows::Rows, + }, + }) + }) + .transpose()?, + limit_by: self.exprs(&limit.by)?, + }) + } + + fn order_by_items(&self, items: &[v2::OrderByItem<'_, Builtin>]) -> Result> { + items + .iter() + .map(|item| { + if item.ext != Default::default() { + return unconverted("ORDER BY item options"); + } + let sort = match (&item.using, item.asc) { + (Some(_), _) => return unconverted("ORDER BY USING"), + (None, Some(true)) => Some(OrderBySort::Asc), + (None, Some(false)) => Some(OrderBySort::Desc), + (None, None) => None, + }; + Ok(OrderByExpr { + expr: self.expr(&item.expr)?, + options: OrderByOptions { + sort, + nulls_first: item.nulls_first, + }, + with_fill: None, + }) + }) + .collect() + } + + #[cfg_attr(feature = "recursive-protection", recursive::recursive)] + fn set_expr(&self, body: &v2::SetExpr<'_, Builtin>) -> Result { + Ok(match body { + v2::SetExpr::Select(select) => SetExpr::Select(Box::new(self.select(select)?)), + v2::SetExpr::Query(query) => SetExpr::Query(Box::new(self.query(query)?)), + v2::SetExpr::Values(rows) => SetExpr::Values(self.values(rows, false)?), + v2::SetExpr::RowValues(rows) => SetExpr::Values(self.values(rows, true)?), + v2::SetExpr::Statement(_) => return unconverted("statement as a query body"), + v2::SetExpr::Table(_) => return unconverted("TABLE query"), + v2::SetExpr::SetOperation { + left, + op, + quantifier, + by_name, + right, + } => SetExpr::SetOperation { + left: Box::new(self.set_expr(left)?), + op: match op { + v2::SetOperator::Union => SetOperator::Union, + v2::SetOperator::Except => SetOperator::Except, + v2::SetOperator::Intersect => SetOperator::Intersect, + v2::SetOperator::Minus => SetOperator::Minus, + }, + set_quantifier: match (quantifier, by_name) { + (v2::SetQuantifier::None, false) => SetQuantifier::None, + (v2::SetQuantifier::All, false) => SetQuantifier::All, + (v2::SetQuantifier::Distinct, false) => SetQuantifier::Distinct, + (v2::SetQuantifier::None, true) => SetQuantifier::ByName, + (v2::SetQuantifier::All, true) => SetQuantifier::AllByName, + (v2::SetQuantifier::Distinct, true) => SetQuantifier::DistinctByName, + }, + right: Box::new(self.set_expr(right)?), + }, + }) + } + + fn values(&self, rows: &[Vec>], explicit_row: bool) -> Result { + Ok(Values { + explicit_row, + value_keyword: false, + rows: rows + .iter() + .map(|row| { + Ok(Parens { + opening_token: AttachedToken::empty(), + content: self.exprs(row)?, + closing_token: AttachedToken::empty(), + }) + }) + .collect::>()?, + }) + } + + fn select(&self, select: &v2::Select<'_, Builtin>) -> Result