s5dsn-eqee commented on code in PR #2839:
URL: 
https://github.com/apache/datafusion-sqlparser-rs/pull/2839#discussion_r4506042211


##########
fuzz/fuzz_targets/fuzz_postgres_expr.rs:
##########
@@ -0,0 +1,267 @@
+// 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;
+
+use expression::{parenthesize, Case, Grammar};
+use libfuzzer_sys::fuzz_target;
+use serde_json::Value;
+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| {

Review Comment:
   I'd propose this check: without it, Display bugs are reported as grouping 
errors.
   
   ```
     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 };
   
     let printed = statement.to_string();
     let Ok(baseline) = pg_query::parse(&printed) else {
         panic!("PostgreSQL rejects sqlparser's output\n  sql: {sql}\n  
printed: {printed}");
     };
     if tree(&original) != tree(&baseline) {
         // The tokens changed: a Display bug, or sqlparser parsed a different 
construct (e.g. a keyword taken as an alias).
         panic!("sqlparser reads or prints the statement differently\n  sql: 
{sql}\n  printed: {printed}");
     }
   
     parenthesize(statement); // Only wraps in `Nested`, no rewrites.
     let grouped = statement.to_string();
     let regrouped = pg_query::parse(&grouped);
     if !regrouped.as_ref().is_ok_and(|r| tree(&baseline) == tree(r)) {
         // Same tokens, only the parentheses differ, so this is a real 
grouping bug.
         panic!("sqlparser groups the expression differently\n  sql: {sql}\n  
grouped: {grouped}");
     }
   ```



##########
fuzz/fuzz_targets/expression/mod.rs:
##########
@@ -0,0 +1,243 @@
+// 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, BinaryOperator, Expr, Ident, Statement, Value, 
ValueWithSpan,
+};
+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<u8>,
+    primary: Primary,
+    postfix: Vec<u8>,
+    tight: bool,
+}
+
+#[derive(Arbitrary, Debug)]
+enum Primary {
+    Atom(u8),
+    Group(Box<Chain>),
+    List(Box<Chain>, Vec<Chain>),
+    Call(u8, Vec<Chain>),
+    Cast(Box<Chain>, u8),
+    Case {
+        operand: Option<Box<Chain>>,
+        when: Box<(Chain, Chain)>,
+        more: Vec<(Chain, Chain)>,
+        otherwise: Option<Box<Chain>>,
+    },
+    Scalar(Box<Chain>),
+    Array(Vec<Chain>),
+}
+
+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<Item = &'a Chain>,
+    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.
+///
+/// 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) {

Review Comment:
   It rewrites the statement tree, so let's cover it with tests.



##########
fuzz/fuzz_targets/fuzz_sqlite_expr.rs:
##########
@@ -0,0 +1,290 @@
+// 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;
+
+use expression::{parenthesize, Case, Grammar};
+use libfuzzer_sys::fuzz_target;
+use libsqlite3_sys as ffi;
+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<Vec<u8>>; 6];
+
+/// SQLite's message for SQL it refuses to compile.
+#[derive(Debug, thiserror::Error)]
+#[error("{}", .0.escape_ascii())]
+struct Rejected(Vec<u8>);
+
+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: &[u8]) -> Result<Vec<Instruction>, Rejected> {
+        let mut text = b"EXPLAIN ".to_vec();
+        text.extend_from_slice(sql);
+        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::<u8>(), 
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) {

Review Comment:
   Same as the PostgreSQL target: bytecode depends on how constants are 
spelled, so 0x1F printing as X'1F' shows up as a grouping difference. The 
two-step check would help here too: explain(original) vs explain(printed), then 
explain(printed) vs explain(grouped).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to