diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index dcf891d3ac..271f4ea9ac 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -90,6 +90,8 @@ jobs: - uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2.7.8 - name: Test run: cargo test --locked --all-features + - name: Test fuzz helpers + run: cargo test --locked --manifest-path fuzz/Cargo.toml --test expression coverage: runs-on: ubuntu-latest diff --git a/docs/fuzzing.md b/docs/fuzzing.md index be47c83aaa..d0d5aca7eb 100644 --- a/docs/fuzzing.md +++ b/docs/fuzzing.md @@ -37,7 +37,9 @@ rendered statement no longer parses. `fuzz_duckdb_accepts` parses the input with DuckDB's own parser and fails when DuckDB accepts a `SELECT` that `DuckDbDialect` rejects. -The three oracle targets compile their engine from source, so each builds only with its feature, `sqlite`, `postgres` or `duckdb`, as in `cargo +nightly fuzz run --features sqlite fuzz_sqlite_accepts fuzz_seeds`. `cargo +nightly fuzz build --all-features` builds every target. +`fuzz_postgres_expr` and `fuzz_sqlite_expr` generate operator chains from a small token grammar. They fail when the engine reads sqlparser's printed statement differently from the original, which catches misreads and printing bugs, and then when it reads the fully parenthesized print differently from the plain one, which catches grouping bugs. Custom operators print as `OPERATOR(name)` so lexing differences show up too. + +The oracle targets compile their engine from source, so each builds only with its feature, `sqlite`, `postgres` or `duckdb`, as in `cargo +nightly fuzz run --features sqlite fuzz_sqlite_accepts fuzz_seeds`. `cargo +nightly fuzz build --all-features` builds every target. `fuzz_stage_cost` times tokenizing, parsing and printing the input with every dialect and fails when parsing takes more than 50 times as long as tokenizing, or printing more than 50 times as long as parsing, once the slower stage passes 10 ms. It reports superlinear paths whose cost stays far below the fuzzer's timeout. diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index a1dfa60b72..53189f405c 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -37,6 +37,9 @@ name = "arbitrary" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] [[package]] name = "base64" @@ -126,6 +129,17 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "either" version = "1.19.0" @@ -203,6 +217,7 @@ dependencies = [ "pg_query", "serde_json", "sqlparser", + "thiserror 2.0.21", ] [[package]] @@ -487,7 +502,7 @@ dependencies = [ "prost-build", "serde", "serde_json", - "thiserror", + "thiserror 1.0.69", ] [[package]] @@ -785,10 +800,20 @@ checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" [[package]] name = "sqlparser" -version = "0.63.0" +version = "0.64.0" dependencies = [ "log", "recursive", + "sqlparser_derive", +] + +[[package]] +name = "sqlparser_derive" +version = "0.7.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", ] [[package]] @@ -862,7 +887,16 @@ version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", ] [[package]] @@ -876,6 +910,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "unicode-ident" version = "1.0.27" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index a30f338ebd..5ddf958d86 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -25,17 +25,18 @@ publish = false cargo-fuzz = true [dependencies] -libfuzzer-sys = "0.4" +libfuzzer-sys = { version = "0.4", features = ["arbitrary-derive"] } libsqlite3-sys = { version = "0.39", features = ["bundled"], optional = true } pg_query = { version = "6.2", optional = true } libduckdb-sys = { version = "1.10505.0", features = ["bundled", "json"], optional = true } serde_json = { version = "1", optional = true } -sqlparser = { path = ".." } +thiserror = { version = "2", optional = true } +sqlparser = { path = "..", features = ["visitor"] } # The oracle targets build their engines from source, so each compiles only when its feature is on. [features] -sqlite = ["dep:libsqlite3-sys"] -postgres = ["dep:pg_query"] +sqlite = ["dep:libsqlite3-sys", "dep:thiserror"] +postgres = ["dep:pg_query", "dep:serde_json"] duckdb = ["dep:libduckdb-sys", "dep:serde_json"] # Prevent this from interfering with workspaces @@ -80,6 +81,22 @@ test = false doc = false bench = false +[[bin]] +name = "fuzz_sqlite_expr" +path = "fuzz_targets/fuzz_sqlite_expr.rs" +required-features = ["sqlite"] +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_postgres_expr" +path = "fuzz_targets/fuzz_postgres_expr.rs" +required-features = ["postgres"] +test = false +doc = false +bench = false + [[bin]] name = "fuzz_stage_cost" path = "fuzz_targets/fuzz_stage_cost.rs" diff --git a/fuzz/fuzz_targets/expression/mod.rs b/fuzz/fuzz_targets/expression/mod.rs new file mode 100644 index 0000000000..f18a858485 --- /dev/null +++ b/fuzz/fuzz_targets/expression/mod.rs @@ -0,0 +1,226 @@ +// 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. + +//! Unparenthesized operator chains for the expression shape targets. + +use libfuzzer_sys::arbitrary::{self, Arbitrary}; +use sqlparser::ast::{visit_expressions_mut, Expr, Statement}; +use std::fmt::Write; +use std::ops::ControlFlow; + +const MAX_DEPTH: usize = 6; + +/// The tokens one dialect's chains are built from. +pub struct Grammar { + pub atoms: &'static [&'static str], + pub prefix: &'static [&'static str], + pub infix: &'static [&'static str], + pub postfix: &'static [&'static str], + pub functions: &'static [&'static str], + pub types: &'static [&'static str], + /// Opening and closing text of an array constructor. + pub array: (&'static str, &'static str), + /// Statements a chain is placed in, with `{}` where the chain goes. + pub contexts: &'static [&'static str], +} + +/// A chain placed in one of the grammar's statement contexts. +#[derive(Arbitrary, Debug)] +pub struct Case { + context: u8, + chain: Chain, +} + +impl Case { + /// Writes the statement as SQL text in the tokens of `grammar`. + pub fn render(&self, grammar: &Grammar) -> String { + pick(grammar.contexts, self.context).replacen("{}", &self.chain.render(grammar), 1) + } +} + +/// An expression written as operands joined by operators, with no parentheses unless the input asks for a group. +#[derive(Arbitrary, Debug)] +pub struct Chain { + first: Operand, + rest: Vec<(Infix, Operand)>, +} + +#[derive(Arbitrary, Debug)] +struct Infix { + op: u8, + tight: bool, +} + +#[derive(Arbitrary, Debug)] +struct Operand { + prefix: Vec, + primary: Primary, + postfix: Vec, + tight: bool, +} + +#[derive(Arbitrary, Debug)] +enum Primary { + Atom(u8), + Group(Box), + List(Box, Vec), + Call(u8, Vec), + Cast(Box, u8), + Case { + operand: Option>, + when: Box<(Chain, Chain)>, + more: Vec<(Chain, Chain)>, + otherwise: Option>, + }, + Scalar(Box), + Array(Vec), +} + +fn pick(table: &'static [&'static str], index: u8) -> &'static str { + table[usize::from(index) % table.len()] +} + +impl Chain { + /// Writes the chain as SQL text in the tokens of `grammar`. + pub fn render(&self, grammar: &Grammar) -> String { + let mut out = String::new(); + self.write(grammar, 0, &mut out); + out + } + + fn write(&self, grammar: &Grammar, depth: usize, out: &mut String) { + self.first.write(grammar, depth, out); + for (infix, operand) in &self.rest { + let gap = if infix.tight { "" } else { " " }; + let _ = write!(out, "{gap}{}{gap}", pick(grammar.infix, infix.op)); + operand.write(grammar, depth, out); + } + } +} + +impl Operand { + fn write(&self, grammar: &Grammar, depth: usize, out: &mut String) { + let gap = if self.tight { "" } else { " " }; + for &op in &self.prefix { + let _ = write!(out, "{}{gap}", pick(grammar.prefix, op)); + } + self.primary.write(grammar, depth, out); + for &op in &self.postfix { + let _ = write!(out, "{gap}{}", pick(grammar.postfix, op)); + } + } +} + +fn write_list<'a>( + chains: impl IntoIterator, + grammar: &Grammar, + depth: usize, + out: &mut String, +) { + for (i, chain) in chains.into_iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + chain.write(grammar, depth, out); + } +} + +impl Primary { + fn write(&self, grammar: &Grammar, depth: usize, out: &mut String) { + let inner = depth + 1; + if inner > MAX_DEPTH && !matches!(self, Primary::Atom(_)) { + out.push_str(grammar.atoms[0]); + return; + } + match self { + Primary::Atom(i) => out.push_str(pick(grammar.atoms, *i)), + Primary::Group(chain) => { + out.push('('); + chain.write(grammar, inner, out); + out.push(')'); + } + Primary::List(first, rest) => { + out.push('('); + write_list(std::iter::once(&**first).chain(rest), grammar, inner, out); + out.push(')'); + } + Primary::Call(name, args) => { + let _ = write!(out, "{}(", pick(grammar.functions, *name)); + write_list(args, grammar, inner, out); + out.push(')'); + } + Primary::Cast(chain, ty) => { + out.push_str("CAST("); + chain.write(grammar, inner, out); + let _ = write!(out, " AS {})", pick(grammar.types, *ty)); + } + Primary::Case { + operand, + when, + more, + otherwise, + } => { + out.push_str("CASE"); + if let Some(operand) = operand { + out.push(' '); + operand.write(grammar, inner, out); + } + for (condition, result) in std::iter::once(&**when).chain(more) { + out.push_str(" WHEN "); + condition.write(grammar, inner, out); + out.push_str(" THEN "); + result.write(grammar, inner, out); + } + if let Some(otherwise) = otherwise { + out.push_str(" ELSE "); + otherwise.write(grammar, inner, out); + } + out.push_str(" END"); + } + Primary::Scalar(chain) => { + out.push_str("(SELECT "); + chain.write(grammar, inner, out); + out.push(')'); + } + Primary::Array(elements) => { + out.push_str(grammar.array.0); + write_list(elements, grammar, inner, out); + out.push_str(grammar.array.1); + } + } + } +} + +/// Wraps every compound expression of `statement` in parentheses, so its text spells out the tree sqlparser built. +pub fn parenthesize(statement: &mut Statement) { + let _ = visit_expressions_mut(statement, |expr| { + // These already print inside their own parentheses or are single tokens. + if !matches!( + expr, + Expr::Value(_) + | Expr::Identifier(_) + | Expr::CompoundIdentifier(_) + | Expr::Nested(_) + | Expr::Subquery(_) + | Expr::Tuple(_) + ) { + let inner = std::mem::replace(expr, Expr::value(sqlparser::ast::Value::Null)); + *expr = Expr::Nested(Box::new(inner)); + } + ControlFlow::<()>::Continue(()) + }); +} diff --git a/fuzz/fuzz_targets/expression/postgres.rs b/fuzz/fuzz_targets/expression/postgres.rs new file mode 100644 index 0000000000..e474ad14fc --- /dev/null +++ b/fuzz/fuzz_targets/expression/postgres.rs @@ -0,0 +1,33 @@ +// 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 spelling for the expression shape target. + +use sqlparser::ast::{visit_expressions_mut, BinaryOperator, Expr, Statement}; +use std::ops::ControlFlow; + +/// Spells every custom operator as `OPERATOR(name)`, so its name reaches the engine even when the bare text would lex differently. +pub fn spell_custom_operators(statement: &mut Statement) { + let _ = visit_expressions_mut(statement, |expr| { + if let Expr::BinaryOp { op, .. } = expr { + if let BinaryOperator::Custom(name) = op { + *op = BinaryOperator::PGCustomBinaryOperator(vec![std::mem::take(name)]); + } + } + ControlFlow::<()>::Continue(()) + }); +} diff --git a/fuzz/fuzz_targets/expression/sqlite.rs b/fuzz/fuzz_targets/expression/sqlite.rs new file mode 100644 index 0000000000..fd08611c1c --- /dev/null +++ b/fuzz/fuzz_targets/expression/sqlite.rs @@ -0,0 +1,55 @@ +// 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 spelling for the expression shape target. + +/// Lowercases `TRUE` and `FALSE` outside quotes, since SQLite reuses a constant only when its token text matches. +pub fn fold_booleans(sql: &str) -> String { + let mut out = String::with_capacity(sql.len()); + let mut chars = sql.char_indices().peekable(); + while let Some((start, c)) = chars.next() { + let close = match c { + '\'' | '"' | '`' => Some(c), + '[' => Some(']'), + _ => None, + }; + let mut end = start + c.len_utf8(); + if let Some(close) = close { + for (i, d) in chars.by_ref() { + end = i + d.len_utf8(); + if d == close { + break; + } + } + } else if c.is_alphanumeric() || c == '_' { + while let Some(&(i, d)) = chars.peek() { + if !(d.is_alphanumeric() || d == '_' || d == '$') { + break; + } + end = i + d.len_utf8(); + chars.next(); + } + } + let token = &sql[start..end]; + if token.eq_ignore_ascii_case("true") || token.eq_ignore_ascii_case("false") { + out.push_str(&token.to_ascii_lowercase()); + } else { + out.push_str(token); + } + } + out +} diff --git a/fuzz/fuzz_targets/fuzz_postgres_expr.rs b/fuzz/fuzz_targets/fuzz_postgres_expr.rs new file mode 100644 index 0000000000..3307138139 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_postgres_expr.rs @@ -0,0 +1,282 @@ +// 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. + +//! Checks that sqlparser groups PostgreSQL operators the way PostgreSQL does. +//! +//! sqlparser's tree is printed with every compound expression parenthesized, and PostgreSQL must +//! build the same parse tree from that text as from the original. + +#![no_main] + +mod expression; +#[path = "expression/postgres.rs"] +mod spelling; + +use expression::{parenthesize, Case, Grammar}; +use libfuzzer_sys::fuzz_target; +use serde_json::Value; +use spelling::spell_custom_operators; +use sqlparser::dialect::PostgreSqlDialect; +use sqlparser::parser::Parser; + +const POSTGRES: Grammar = Grammar { + atoms: &[ + "1", + "2", + "3", + "0", + "2.5", + "1e3", + "'a'", + "'{1,2}'", + "NULL", + "TRUE", + "FALSE", + "a", + "t.b", + "$1", + "B'101'", + "E'\\n'", + "DATE '2020-01-01'", + "INTERVAL '1 day'", + ".5", + "1.5e-3", + "0x1F", + "0o17", + "0b101", + "1_000", + "U&'a'", + "$$a$$", + "X'1F'", + "CURRENT_TIMESTAMP", + "CURRENT_USER", + "ROW(1, 2)", + "'(1,2)'::point", + "'{\"a\":1}'::jsonb", + "(SELECT 1)", + "EXISTS (SELECT 1)", + ], + prefix: &[ + "-", + "+", + "~", + "NOT", + "@", + "|/", + "||/", + "OPERATOR(pg_catalog.-)", + ], + infix: &[ + "+", + "-", + "*", + "/", + "%", + "^", + "||", + "&", + "|", + "#", + "<<", + ">>", + "=", + "<>", + "!=", + "<", + ">", + "<=", + ">=", + "AND", + "OR", + "IS DISTINCT FROM", + "IS NOT DISTINCT FROM", + "LIKE", + "NOT LIKE", + "ILIKE", + "NOT ILIKE", + "SIMILAR TO", + "NOT SIMILAR TO", + "ESCAPE", + "BETWEEN", + "NOT BETWEEN", + "BETWEEN SYMMETRIC", + "IN", + "NOT IN", + "~", + "!~", + "~*", + "!~*", + "~~", + "!~~", + "@>", + "<@", + "&&", + "->", + "->>", + "#>", + "#>>", + "?", + "?|", + "@@", + "AT TIME ZONE", + "OVERLAPS", + "IS", + "IS NOT", + "= ANY", + "< ALL", + "> SOME", + "<> ALL", + "LIKE ANY", + "OPERATOR(pg_catalog.+)", + "<->", + "-|-", + "#-", + "?&", + "@?", + "##", + "<<|", + "|>>", + "&<", + "&>", + "<^", + ">^", + "?#", + "~=", + "<<=", + ">>=", + "AND NOT", + "OR NOT", + ], + postfix: &[ + "IS NULL", + "IS NOT NULL", + "ISNULL", + "NOTNULL", + "IS TRUE", + "IS NOT TRUE", + "IS FALSE", + "IS UNKNOWN", + "::int", + "::text", + "::numeric", + "::int[]", + "::regclass", + "::jsonb", + "::bit(3)", + "::varchar(5)", + "::timestamp(3) with time zone", + "::double precision", + "::\"char\"", + "IS NOT UNKNOWN", + "IS NOT NORMALIZED", + "IS NFC NORMALIZED", + "IS JSON OBJECT", + "IS NOT JSON", + "[1][2]", + "[:2]", + "[1:]", + "COLLATE \"C\"", + "[1]", + "[1:2]", + "AT LOCAL", + "IS NORMALIZED", + "IS JSON", + ], + functions: &["abs", "coalesce", "greatest", "length", "now", "row"], + types: &[ + "int", + "text", + "numeric(10, 2)", + "bool", + "int[]", + "timestamptz", + ], + array: ("ARRAY[", "]"), + contexts: &[ + "SELECT {} FROM t", + "SELECT 1 FROM t WHERE {}", + "SELECT 1 FROM t ORDER BY {}", + "SELECT 1 FROM t GROUP BY 1 HAVING {}", + "SELECT 1 FROM t JOIN u ON {}", + "UPDATE t SET a = {}", + ], +}; + +/// Drops source positions, which differ between the two texts by construction. +fn strip_locations(value: &mut Value) { + match value { + Value::Object(map) => { + map.retain(|key, _| { + !(key.ends_with("location") || key == "stmt_len" || key.starts_with("list_")) + }); + map.values_mut().for_each(strip_locations); + } + Value::Array(items) => items.iter_mut().for_each(strip_locations), + _ => {} + } +} + +fn tree(parsed: &pg_query::ParseResult) -> Value { + let mut tree = serde_json::to_value(&parsed.protobuf.stmts).expect("parse trees serialize"); + strip_locations(&mut tree); + tree +} + +fuzz_target!(|case: Case| { + let sql = case.render(&POSTGRES); + let Ok(original) = pg_query::parse(&sql) else { + return; + }; + let Ok(mut statements) = Parser::parse_sql(&PostgreSqlDialect {}, &sql) else { + return; + }; + let [statement] = statements.as_mut_slice() else { + return; + }; + spell_custom_operators(statement); + let printed = statement.to_string(); + let version = original.protobuf.version; + let reading = || original.deparse().unwrap_or_default(); + let expected = tree(&original); + match pg_query::parse(&printed) { + Ok(baseline) if tree(&baseline) == expected => {} + Ok(baseline) => panic!( + "sqlparser reads or prints the statement differently from PostgreSQL {version}\n sql: {sql}\n printed: {printed}\n postgres: {}\n sqlparser: {}", + reading(), + baseline.deparse().unwrap_or_default(), + ), + Err(err) => panic!( + "PostgreSQL {version} rejects sqlparser's printing of SQL it accepts\n sql: {sql}\n printed: {printed}\n postgres: {}\n error: {err}", + reading(), + ), + } + // `printed` and `grouped` differ only in parentheses, so any difference left is grouping. + parenthesize(statement); + let grouped = statement.to_string(); + match pg_query::parse(&grouped) { + Ok(regrouped) if tree(®rouped) == expected => {} + Ok(regrouped) => panic!( + "sqlparser groups the expression differently from PostgreSQL {version}\n sql: {sql}\n postgres: {}\n sqlparser: {}", + reading(), + regrouped.deparse().unwrap_or(grouped), + ), + Err(err) => panic!( + "PostgreSQL {version} rejects sqlparser's grouping of SQL it accepts\n sql: {sql}\n grouped: {grouped}\n postgres: {}\n error: {err}", + reading(), + ), + } +}); diff --git a/fuzz/fuzz_targets/fuzz_sqlite_expr.rs b/fuzz/fuzz_targets/fuzz_sqlite_expr.rs new file mode 100644 index 0000000000..9c4071c82b --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_sqlite_expr.rs @@ -0,0 +1,304 @@ +// 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. + +//! Checks that sqlparser groups SQLite operators the way SQLite does. +//! +//! sqlparser's tree is printed with every compound expression parenthesized, and SQLite must +//! compile that text to the same bytecode as the original. + +#![no_main] + +mod expression; +#[path = "expression/sqlite.rs"] +mod spelling; + +use expression::{parenthesize, Case, Grammar}; +use libfuzzer_sys::fuzz_target; +use libsqlite3_sys as ffi; +use spelling::fold_booleans; +use sqlparser::dialect::SQLiteDialect; +use sqlparser::parser::Parser; +use std::ffi::{c_int, CStr}; +use std::ptr; + +const SQLITE: Grammar = Grammar { + // `X'01'` is spelled as sqlparser prints it, since SQLite's constant reuse compares token text. + atoms: &[ + "1", + "2", + "3", + "0", + "2.5", + "1e3", + "'a'", + "NULL", + "TRUE", + "FALSE", + "a", + "t.b", + "X'01'", + "?1", + "CURRENT_DATE", + "9223372036854775808", + ".5", + "1.5e-3", + "0x1F", + "1_000", + "CURRENT_TIME", + "CURRENT_TIMESTAMP", + ":p", + "@p", + "$p", + "?", + "(SELECT 1)", + "EXISTS (SELECT 1)", + "\"a\"", + "[a]", + "`a`", + ], + prefix: &["-", "+", "~", "NOT"], + infix: &[ + "+", + "-", + "*", + "/", + "%", + "||", + "&", + "|", + "<<", + ">>", + "=", + "==", + "<>", + "!=", + "<", + ">", + "<=", + ">=", + "AND", + "OR", + "IS", + "IS NOT", + "IS DISTINCT FROM", + "IS NOT DISTINCT FROM", + "LIKE", + "NOT LIKE", + "GLOB", + "NOT GLOB", + "ESCAPE", + "BETWEEN", + "NOT BETWEEN", + "IN", + "NOT IN", + "->", + "->>", + "MATCH", + "NOT MATCH", + "AND NOT", + "OR NOT", + ], + postfix: &[ + "ISNULL", + "NOTNULL", + "NOT NULL", + "IS NULL", + "IS NOT NULL", + "IS TRUE", + "IS NOT FALSE", + "COLLATE NOCASE", + "COLLATE BINARY", + "COLLATE RTRIM", + ], + functions: &[ + "abs", + "coalesce", + "max", + "length", + "iif", + "json", + "printf", + "json_extract", + "nullif", + "typeof", + "unlikely", + ], + types: &[ + "INTEGER", + "TEXT", + "REAL", + "NUMERIC", + "BLOB", + "VARCHAR(10)", + "DECIMAL(5, 2)", + "UNSIGNED BIG INT", + "DOUBLE PRECISION", + "INT8", + ], + array: ("(", ")"), + contexts: &[ + "SELECT {} FROM t", + "SELECT 1 FROM t WHERE {}", + "SELECT 1 FROM t ORDER BY {}", + "SELECT 1 FROM t GROUP BY 1 HAVING {}", + "SELECT 1 FROM t JOIN (SELECT 1 AS z) AS u ON {}", + "UPDATE t SET a = {}", + ], +}; + +struct Db(*mut ffi::sqlite3); + +/// One bytecode instruction as `EXPLAIN` lists it: opcode and p1 to p5. +type Instruction = [Option>; 6]; + +/// SQLite's message for SQL it refuses to compile. +#[derive(Debug, thiserror::Error)] +#[error("{}", .0.escape_ascii())] +struct Rejected(Vec); + +impl Db { + fn open() -> Self { + let mut db = ptr::null_mut(); + // SAFETY: the filename is NUL terminated and `db` is a valid out pointer. + let rc = unsafe { + ffi::sqlite3_open_v2( + c":memory:".as_ptr(), + &mut db, + ffi::SQLITE_OPEN_READWRITE | ffi::SQLITE_OPEN_CREATE, + ptr::null(), + ) + }; + assert_eq!( + rc, + ffi::SQLITE_OK, + "cannot open an in-memory SQLite database" + ); + let db = Self(db); + // SAFETY: the statement is NUL terminated and the handle is open. + let rc = unsafe { + ffi::sqlite3_exec( + db.0, + c"CREATE TABLE t(a INTEGER, b TEXT)".as_ptr(), + None, + ptr::null_mut(), + ptr::null_mut(), + ) + }; + assert_eq!(rc, ffi::SQLITE_OK, "cannot create the fixture table"); + db + } + + /// Compiles `EXPLAIN sql` and returns its program, or SQLite's error message. + fn explain(&self, sql: &str) -> Result, Rejected> { + let mut text = b"EXPLAIN ".to_vec(); + text.extend_from_slice(fold_booleans(sql).as_bytes()); + let len = c_int::try_from(text.len()).expect("SQL fits a c_int"); + let mut stmt = ptr::null_mut(); + // SAFETY: SQLite reads at most `len` bytes of `text`, which outlives the call. + let rc = unsafe { + ffi::sqlite3_prepare_v2( + self.0, + text.as_ptr().cast(), + len, + &mut stmt, + ptr::null_mut(), + ) + }; + if rc != ffi::SQLITE_OK || stmt.is_null() { + // SAFETY: finalizing NULL is a no-op, and sqlite3_errmsg returns a NUL terminated + // string owned by the handle that stays valid until the next call, so it is copied first. + return Err(Rejected(unsafe { + ffi::sqlite3_finalize(stmt); + CStr::from_ptr(ffi::sqlite3_errmsg(self.0)) + .to_bytes() + .to_vec() + })); + } + let mut program = Vec::new(); + // SAFETY: `stmt` is a live prepared statement until the final finalize, and each column's + // bytes are copied before the next step invalidates them. + unsafe { + while ffi::sqlite3_step(stmt) == ffi::SQLITE_ROW { + let instruction: Instruction = std::array::from_fn(|i| { + let column = c_int::try_from(i + 1).expect("column index fits a c_int"); + let data = ffi::sqlite3_column_blob(stmt, column); + let len = ffi::sqlite3_column_bytes(stmt, column); + (!data.is_null()).then(|| { + let len = usize::try_from(len).expect("column length is non-negative"); + std::slice::from_raw_parts(data.cast::(), len).to_vec() + }) + }); + if instruction[0].as_deref() != Some(b"Init") { + program.push(instruction); + } + } + ffi::sqlite3_finalize(stmt); + } + Ok(program) + } +} + +impl Drop for Db { + fn drop(&mut self) { + // SAFETY: every statement is finalized, so the handle closes. + unsafe { ffi::sqlite3_close(self.0) }; + } +} + +thread_local! { + // EXPLAIN compiles without running, so one database serves every input. + static DB: Db = Db::open(); +} + +fn check(db: &Db, case: &Case) { + let sql = case.render(&SQLITE); + let Ok(original) = db.explain(&sql) else { + return; + }; + let Ok(mut statements) = Parser::parse_sql(&SQLiteDialect {}, &sql) else { + return; + }; + let [statement] = statements.as_mut_slice() else { + return; + }; + let printed = statement.to_string(); + // SAFETY: sqlite3_libversion returns a static NUL terminated string. + let version = unsafe { CStr::from_ptr(ffi::sqlite3_libversion()) }; + let baseline = match db.explain(&printed) { + Ok(baseline) if baseline == original => baseline, + Ok(_) => panic!( + "sqlparser reads or prints the statement differently from SQLite {version:?}\n sql: {sql}\n printed: {printed}" + ), + Err(err) => panic!( + "SQLite {version:?} rejects sqlparser's printing of SQL it accepts\n sql: {sql}\n printed: {printed}\n error: {err}" + ), + }; + // `printed` and `grouped` differ only in parentheses, so any difference left is grouping. + parenthesize(statement); + let grouped = statement.to_string(); + match db.explain(&grouped) { + Ok(regrouped) => assert!( + regrouped == baseline, + "sqlparser groups the expression differently from SQLite {version:?}\n sql: {sql}\n grouped: {grouped}" + ), + Err(err) => panic!( + "SQLite {version:?} rejects sqlparser's grouping of SQL it accepts\n sql: {sql}\n grouped: {grouped}\n error: {err}" + ), + } +} + +fuzz_target!(|case: Case| DB.with(|db| check(db, &case))); diff --git a/fuzz/tests/expression.rs b/fuzz/tests/expression.rs new file mode 100644 index 0000000000..ba90cff84f --- /dev/null +++ b/fuzz/tests/expression.rs @@ -0,0 +1,130 @@ +// 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. + +#[path = "../fuzz_targets/expression/mod.rs"] +#[expect( + dead_code, + reason = "the chain generator is only used by the fuzz targets" +)] +mod expression; + +#[path = "../fuzz_targets/expression/postgres.rs"] +mod postgres; +#[path = "../fuzz_targets/expression/sqlite.rs"] +mod sqlite; + +use expression::parenthesize; +use postgres::spell_custom_operators; +use sqlite::fold_booleans; +use sqlparser::ast::{visit_expressions_mut, Expr, Statement}; +use sqlparser::dialect::{Dialect, GenericDialect, PostgreSqlDialect, SQLiteDialect}; +use sqlparser::parser::Parser; +use std::ops::ControlFlow; + +fn statement(dialect: &dyn Dialect, sql: &str) -> Statement { + let [statement] = <[Statement; 1]>::try_from(Parser::parse_sql(dialect, sql).unwrap()) + .expect("one statement"); + statement +} + +fn parenthesized(dialect: &dyn Dialect, sql: &str) -> String { + let mut statement = statement(dialect, sql); + parenthesize(&mut statement); + statement.to_string() +} + +fn without_nested(mut statement: Statement) -> Statement { + let _ = visit_expressions_mut(&mut statement, |expr| { + while let Expr::Nested(inner) = expr { + *expr = std::mem::replace(inner, Expr::value(sqlparser::ast::Value::Null)); + } + ControlFlow::<()>::Continue(()) + }); + statement +} + +#[test] +fn parenthesize_wraps_each_compound_expression_once() { + assert_eq!( + parenthesized( + &GenericDialect {}, + "SELECT a + b * c FROM t WHERE NOT a = 1" + ), + "SELECT (a + (b * c)) FROM t WHERE (NOT (a = 1))" + ); +} + +#[test] +fn parenthesize_leaves_atoms_and_parenthesized_forms_alone() { + let sql = "SELECT (a), (SELECT 1), (1, 2), 'x', t.b FROM t"; + assert_eq!(parenthesized(&GenericDialect {}, sql), sql); +} + +#[test] +fn parenthesize_only_adds_parentheses() { + let cases: [(&dyn Dialect, &str); 6] = [ + (&GenericDialect {}, "SELECT a + b * c - d / e FROM t"), + ( + &PostgreSqlDialect {}, + "SELECT CASE WHEN a THEN b ELSE c END::int, -a ^ 2 FROM t", + ), + ( + &PostgreSqlDialect {}, + "SELECT a = ANY(ARRAY[1, 2]) AND b IS NOT NULL FROM t", + ), + ( + &PostgreSqlDialect {}, + "UPDATE t SET a = CAST(b AS int) + abs(c) WHERE a BETWEEN 1 AND 2", + ), + ( + &SQLiteDialect {}, + "SELECT a COLLATE NOCASE || b, a IN (1, 2), x ->> '$.n' FROM t", + ), + ( + &SQLiteDialect {}, + "SELECT 1 FROM t ORDER BY a LIKE 'x%' ESCAPE '\\', NOT b", + ), + ]; + for (dialect, sql) in cases { + let grouped = parenthesized(dialect, sql); + assert_eq!( + without_nested(statement(dialect, &grouped)), + without_nested(statement(dialect, sql)), + "{sql} became {grouped}" + ); + } +} + +#[test] +fn spell_custom_operators_names_only_custom_operators() { + let mut statement = statement(&PostgreSqlDialect {}, "SELECT a<>-1, a + 1, a <-> b FROM t"); + spell_custom_operators(&mut statement); + assert_eq!( + statement.to_string(), + "SELECT a OPERATOR(<>-) 1, a + 1, a <-> b FROM t" + ); +} + +#[test] +fn fold_booleans_lowercases_only_unquoted_keywords() { + assert_eq!( + fold_booleans( + "SELECT TRUE, False, 'TRUE', \"TRUE\", [TRUE], `TRUE`, trueish, x_TRUE FROM t" + ), + "SELECT true, false, 'TRUE', \"TRUE\", [TRUE], `TRUE`, trueish, x_TRUE FROM t" + ); +}