diff --git a/fuzz/fuzz_seeds/hive_2589_digit_prefixed_field.sql b/fuzz/fuzz_seeds/hive_2589_digit_prefixed_field.sql new file mode 100644 index 0000000000..4375daef43 --- /dev/null +++ b/fuzz/fuzz_seeds/hive_2589_digit_prefixed_field.sql @@ -0,0 +1 @@ +SELECT [dbo]. 1te_sk = 1 diff --git a/src/ast/mod.rs b/src/ast/mod.rs index eb5bc6cc75..16383358fa 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -1503,10 +1503,19 @@ const fn is_number_expr(expr: &Expr) -> bool { matches!(expr, Expr::Value(v) if matches!(v.value, Value::Number(_, _))) } +/// Whether a leading `.` would merge into `expr` when the displayed SQL is +/// re-lexed: `.1` lexes as a number in front of a numeric literal or an +/// unquoted identifier starting with a digit (Hive allows such words). +fn dot_merges_with_expr(expr: &Expr) -> bool { + is_number_expr(expr) + || matches!(expr, Expr::Identifier(ident) if ident.quote_style.is_none() + && ident.value.starts_with(|c: char| c.is_ascii_digit())) +} + impl fmt::Display for AccessExpr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - AccessExpr::Dot(expr) if is_number_expr(expr) => write!(f, " . {expr}"), + AccessExpr::Dot(expr) if dot_merges_with_expr(expr) => write!(f, " . {expr}"), AccessExpr::Dot(expr) => write!(f, ".{expr}"), AccessExpr::Subscript(subscript) => write!(f, "[{subscript}]"), } diff --git a/tests/sqlparser_hive.rs b/tests/sqlparser_hive.rs index 21e76e23b6..d6cfb1c12d 100644 --- a/tests/sqlparser_hive.rs +++ b/tests/sqlparser_hive.rs @@ -569,6 +569,16 @@ fn parse_create_table_with_map_column_comment() { ); } +#[test] +fn test_field_access_on_digit_prefixed_identifier() { + // The space before `1te_sk` keeps `.1` from being lexed as a number, + // which previously reparsed as a different statement. See + // https://github.com/apache/datafusion-sqlparser-rs/issues/2589 + hive().one_statement_parses_to("SELECT [dbo]. 1te_sk = 1", "SELECT [dbo] . 1te_sk = 1"); + hive().verified_stmt("SELECT [dbo] . 1te_sk"); + hive().verified_stmt("SELECT dbo.1te_sk"); +} + fn hive() -> TestedDialects { TestedDialects::new(vec![Box::new(HiveDialect {})]) }