Skip to content

Commit 8481452

Browse files
committed
Include snippet of SQL which led to parsing error
1 parent cd1e301 commit 8481452

File tree

6 files changed

+175
-69
lines changed

6 files changed

+175
-69
lines changed

src/parser/mod.rs

+18-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use alloc::{
2323
use core::fmt;
2424

2525
use log::debug;
26+
2627
use recursion::RecursionCounter;
2728
use IsLateral::*;
2829
use IsOptional::*;
@@ -2319,8 +2320,23 @@ impl<'a> Parser<'a> {
23192320

23202321
/// Report unexpected token
23212322
pub fn expected<T>(&self, expected: &str, found: TokenWithLocation) -> Result<T, ParserError> {
2323+
let start_off = self.index.saturating_sub(10);
2324+
let end_off = self.index.min(self.tokens.len());
2325+
let near_tokens = &self.tokens[start_off..end_off];
2326+
struct TokensDisplay<'a>(&'a [TokenWithLocation]);
2327+
impl<'a> fmt::Display for TokensDisplay<'a> {
2328+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2329+
for token in self.0 {
2330+
write!(f, "{}", token)?;
2331+
}
2332+
Ok(())
2333+
}
2334+
}
23222335
parser_err!(
2323-
format!("Expected {expected}, found: {found}"),
2336+
format!(
2337+
"Expected {expected}, found: {found}\nNear `{}`",
2338+
TokensDisplay(near_tokens)
2339+
),
23242340
found.location
23252341
)
23262342
}
@@ -8234,7 +8250,7 @@ mod tests {
82348250
assert_eq!(
82358251
ast,
82368252
Err(ParserError::ParserError(
8237-
"Expected [NOT] NULL or TRUE|FALSE or [NOT] DISTINCT FROM after IS, found: a at Line: 1, Column 16"
8253+
"Expected [NOT] NULL or TRUE|FALSE or [NOT] DISTINCT FROM after IS, found: a\nNear `SELECT this is` at Line: 1, Column 16"
82388254
.to_string()
82398255
))
82408256
);

tests/sqlparser_bigquery.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ fn test_select_wildcard_with_except() {
402402
.parse_sql_statements("SELECT * EXCEPT () FROM employee_table")
403403
.unwrap_err()
404404
.to_string(),
405-
"sql parser error: Expected identifier, found: )"
405+
"sql parser error: Expected identifier, found: )\nNear `SELECT * EXCEPT ()`"
406406
);
407407
}
408408

0 commit comments

Comments
 (0)