Separate printing from grouping in the expression fuzz targets
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index dcf891d..271f4ea 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml
@@ -90,6 +90,8 @@ - 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 b9b6968..d0d5aca 100644 --- a/docs/fuzzing.md +++ b/docs/fuzzing.md
@@ -37,7 +37,7 @@ `fuzz_duckdb_accepts` parses the input with DuckDB's own parser and fails when DuckDB accepts a `SELECT` that `DuckDbDialect` rejects. -`fuzz_postgres_expr` and `fuzz_sqlite_expr` generate operator chains from a small token grammar, print sqlparser's tree fully parenthesized, and fail when the engine reads that text differently from the original. Custom operators print as `OPERATOR(name)` so lexing differences show up too. +`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.
diff --git a/fuzz/fuzz_targets/expression/mod.rs b/fuzz/fuzz_targets/expression/mod.rs index 180d806..f18a858 100644 --- a/fuzz/fuzz_targets/expression/mod.rs +++ b/fuzz/fuzz_targets/expression/mod.rs
@@ -18,9 +18,7 @@ //! Unparenthesized operator chains for the expression shape targets. use libfuzzer_sys::arbitrary::{self, Arbitrary}; -use sqlparser::ast::{ - visit_expressions_mut, BinaryOperator, Expr, Ident, Statement, Value, ValueWithSpan, -}; +use sqlparser::ast::{visit_expressions_mut, Expr, Statement}; use std::fmt::Write; use std::ops::ControlFlow; @@ -208,23 +206,8 @@ } /// Wraps every compound expression of `statement` in parentheses, so its text spells out the tree sqlparser built. -/// -/// A custom operator prints as `OPERATOR(name)`, so its name reaches the engine even when the bare text would lex differently. -/// Booleans print as `TRUE` and `FALSE` like the generated text, since SQLite's constant reuse compares token text. pub fn parenthesize(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)]); - } - } - if let Expr::Value(ValueWithSpan { - value: Value::Boolean(b), - .. - }) = expr - { - *expr = Expr::Identifier(Ident::new(if *b { "TRUE" } else { "FALSE" })); - } // These already print inside their own parentheses or are single tokens. if !matches!( expr,
diff --git a/fuzz/fuzz_targets/expression/postgres.rs b/fuzz/fuzz_targets/expression/postgres.rs new file mode 100644 index 0000000..e474ad1 --- /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 0000000..fd08611 --- /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 index dd513c6..3307138 100644 --- a/fuzz/fuzz_targets/fuzz_postgres_expr.rs +++ b/fuzz/fuzz_targets/fuzz_postgres_expr.rs
@@ -23,10 +23,13 @@ #![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; @@ -244,24 +247,36 @@ 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(); - let regrouped = pg_query::parse(&grouped); - if regrouped - .as_ref() - .is_ok_and(|regrouped| tree(&original) == tree(regrouped)) - { - return; - } - let version = original.protobuf.version; - let reading = original.deparse().unwrap_or_default(); - match regrouped { - Err(err) => panic!( - "PostgreSQL {version} rejects sqlparser's grouping of SQL it accepts\n sql: {sql}\n grouped: {grouped}\n postgres: {reading}\n error: {err}" - ), + 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: {reading}\n sqlparser: {}", + "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 index 361ecfc..9c4071c 100644 --- a/fuzz/fuzz_targets/fuzz_sqlite_expr.rs +++ b/fuzz/fuzz_targets/fuzz_sqlite_expr.rs
@@ -23,10 +23,13 @@ #![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}; @@ -200,9 +203,9 @@ } /// Compiles `EXPLAIN sql` and returns its program, or SQLite's error message. - fn explain(&self, sql: &[u8]) -> Result<Vec<Instruction>, Rejected> { + fn explain(&self, sql: &str) -> Result<Vec<Instruction>, Rejected> { let mut text = b"EXPLAIN ".to_vec(); - text.extend_from_slice(sql); + 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. @@ -263,7 +266,7 @@ fn check(db: &Db, case: &Case) { let sql = case.render(&SQLITE); - let Ok(original) = db.explain(sql.as_bytes()) else { + let Ok(original) = db.explain(&sql) else { return; }; let Ok(mut statements) = Parser::parse_sql(&SQLiteDialect {}, &sql) else { @@ -272,18 +275,29 @@ let [statement] = statements.as_mut_slice() else { return; }; - parenthesize(statement); - let grouped = statement.to_string(); + let printed = statement.to_string(); // SAFETY: sqlite3_libversion returns a static NUL terminated string. let version = unsafe { CStr::from_ptr(ffi::sqlite3_libversion()) }; - match db.explain(grouped.as_bytes()) { + 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}" ), - Ok(regrouped) => assert!( - original == regrouped, - "sqlparser groups the expression differently from SQLite {version:?}\n sql: {sql}\n grouped: {grouped}" - ), } }
diff --git a/fuzz/tests/expression.rs b/fuzz/tests/expression.rs new file mode 100644 index 0000000..ba90cff --- /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" + ); +}