Skip to content

Commit db83ccb

Browse files
committed
Expand require_semicolon_stmt_delimiter parser option & tests
- a corresponding `supports_statements_without_semicolon_delimiter` Dialect trait function - this is optional for SQL Server, so it's set to `true` for that dialect - for the implementation, `RETURN` parsing needs to be tightened up to avoid ambiguity & tests that formerly asserted "end of statement" now maybe need to assert "an SQL statement" - a new `assert_err_parse_statements` splits the dialects based on semicolon requirements & asserts the expected error message accordingly
1 parent 3c61db5 commit db83ccb

File tree

7 files changed

+646
-136
lines changed

7 files changed

+646
-136
lines changed

src/dialect/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,6 +1207,11 @@ pub trait Dialect: Debug + Any {
12071207
fn supports_semantic_view_table_factor(&self) -> bool {
12081208
false
12091209
}
1210+
1211+
/// Returns true if the dialect supports parsing statements without a semicolon delimiter.
1212+
fn supports_statements_without_semicolon_delimiter(&self) -> bool {
1213+
false
1214+
}
12101215
}
12111216

12121217
/// This represents the operators for which precedence must be defined

src/dialect/mssql.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl Dialect for MsSqlDialect {
6767
}
6868

6969
fn supports_connect_by(&self) -> bool {
70-
true
70+
false
7171
}
7272

7373
fn supports_eq_alias_assignment(&self) -> bool {
@@ -123,6 +123,10 @@ impl Dialect for MsSqlDialect {
123123
true
124124
}
125125

126+
fn supports_statements_without_semicolon_delimiter(&self) -> bool {
127+
true
128+
}
129+
126130
/// See <https://learn.microsoft.com/en-us/sql/relational-databases/security/authentication-access/server-level-roles>
127131
fn get_reserved_grantees_types(&self) -> &[GranteesType] {
128132
&[GranteesType::Public]
@@ -284,6 +288,9 @@ impl MsSqlDialect {
284288
) -> Result<Vec<Statement>, ParserError> {
285289
let mut stmts = Vec::new();
286290
loop {
291+
while let Token::SemiColon = parser.peek_token_ref().token {
292+
parser.advance_token();
293+
}
287294
if let Token::EOF = parser.peek_token_ref().token {
288295
break;
289296
}

src/keywords.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1120,6 +1120,7 @@ pub const RESERVED_FOR_TABLE_ALIAS: &[Keyword] = &[
11201120
Keyword::ANTI,
11211121
Keyword::SEMI,
11221122
Keyword::RETURNING,
1123+
Keyword::RETURN,
11231124
Keyword::ASOF,
11241125
Keyword::MATCH_CONDITION,
11251126
// for MSSQL-specific OUTER APPLY (seems reserved in most dialects)
@@ -1174,6 +1175,7 @@ pub const RESERVED_FOR_COLUMN_ALIAS: &[Keyword] = &[
11741175
Keyword::CLUSTER,
11751176
Keyword::DISTRIBUTE,
11761177
Keyword::RETURNING,
1178+
Keyword::RETURN,
11771179
// Reserved only as a column alias in the `SELECT` clause
11781180
Keyword::FROM,
11791181
Keyword::INTO,
@@ -1188,6 +1190,7 @@ pub const RESERVED_FOR_TABLE_FACTOR: &[Keyword] = &[
11881190
Keyword::LIMIT,
11891191
Keyword::HAVING,
11901192
Keyword::WHERE,
1193+
Keyword::RETURN,
11911194
];
11921195

11931196
/// Global list of reserved keywords that cannot be parsed as identifiers
@@ -1198,4 +1201,5 @@ pub const RESERVED_FOR_IDENTIFIER: &[Keyword] = &[
11981201
Keyword::INTERVAL,
11991202
Keyword::STRUCT,
12001203
Keyword::TRIM,
1204+
Keyword::RETURN,
12011205
];

src/parser/mod.rs

Lines changed: 58 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,22 @@ impl ParserOptions {
271271
self.unescape = unescape;
272272
self
273273
}
274+
275+
/// Set if semicolon statement delimiters are required.
276+
///
277+
/// If this option is `true`, the following SQL will not parse. If the option is `false`, the SQL will parse.
278+
///
279+
/// ```sql
280+
/// SELECT 1
281+
/// SELECT 2
282+
/// ```
283+
pub fn with_require_semicolon_stmt_delimiter(
284+
mut self,
285+
require_semicolon_stmt_delimiter: bool,
286+
) -> Self {
287+
self.require_semicolon_stmt_delimiter = require_semicolon_stmt_delimiter;
288+
self
289+
}
274290
}
275291

276292
#[derive(Copy, Clone)]
@@ -367,7 +383,11 @@ impl<'a> Parser<'a> {
367383
state: ParserState::Normal,
368384
dialect,
369385
recursion_counter: RecursionCounter::new(DEFAULT_REMAINING_DEPTH),
370-
options: ParserOptions::new().with_trailing_commas(dialect.supports_trailing_commas()),
386+
options: ParserOptions::new()
387+
.with_trailing_commas(dialect.supports_trailing_commas())
388+
.with_require_semicolon_stmt_delimiter(
389+
!dialect.supports_statements_without_semicolon_delimiter(),
390+
),
371391
}
372392
}
373393

@@ -490,10 +510,10 @@ impl<'a> Parser<'a> {
490510
match self.peek_token().token {
491511
Token::EOF => break,
492512

493-
// end of statement
494-
Token::Word(word) => {
495-
if expecting_statement_delimiter && word.keyword == Keyword::END {
496-
break;
513+
// don't expect a semicolon statement delimiter after a newline when not otherwise required
514+
Token::Whitespace(Whitespace::Newline) => {
515+
if !self.options.require_semicolon_stmt_delimiter {
516+
expecting_statement_delimiter = false;
497517
}
498518
}
499519
_ => {}
@@ -505,7 +525,7 @@ impl<'a> Parser<'a> {
505525

506526
let statement = self.parse_statement()?;
507527
stmts.push(statement);
508-
expecting_statement_delimiter = true;
528+
expecting_statement_delimiter = self.options.require_semicolon_stmt_delimiter;
509529
}
510530
Ok(stmts)
511531
}
@@ -4632,6 +4652,9 @@ impl<'a> Parser<'a> {
46324652
) -> Result<Vec<Statement>, ParserError> {
46334653
let mut values = vec![];
46344654
loop {
4655+
// ignore empty statements (between successive statement delimiters)
4656+
while self.consume_token(&Token::SemiColon) {}
4657+
46354658
match &self.peek_nth_token_ref(0).token {
46364659
Token::EOF => break,
46374660
Token::Word(w) => {
@@ -4643,7 +4666,13 @@ impl<'a> Parser<'a> {
46434666
}
46444667

46454668
values.push(self.parse_statement()?);
4646-
self.expect_token(&Token::SemiColon)?;
4669+
4670+
if self.options.require_semicolon_stmt_delimiter {
4671+
self.expect_token(&Token::SemiColon)?;
4672+
}
4673+
4674+
// ignore empty statements (between successive statement delimiters)
4675+
while self.consume_token(&Token::SemiColon) {}
46474676
}
46484677
Ok(values)
46494678
}
@@ -17271,7 +17300,28 @@ impl<'a> Parser<'a> {
1727117300

1727217301
/// Parse [Statement::Return]
1727317302
fn parse_return(&mut self) -> Result<Statement, ParserError> {
17274-
match self.maybe_parse(|p| p.parse_expr())? {
17303+
let rs = self.maybe_parse(|p| {
17304+
let expr = p.parse_expr()?;
17305+
17306+
match &expr {
17307+
Expr::Value(_)
17308+
| Expr::Function(_)
17309+
| Expr::UnaryOp { .. }
17310+
| Expr::BinaryOp { .. }
17311+
| Expr::Case { .. }
17312+
| Expr::Cast { .. }
17313+
| Expr::Convert { .. }
17314+
| Expr::Subquery(_) => Ok(expr),
17315+
// todo: how to retstrict to variables?
17316+
Expr::Identifier(id) if id.value.starts_with('@') => Ok(expr),
17317+
_ => parser_err!(
17318+
"Non-returnable expression found following RETURN",
17319+
p.peek_token().span.start
17320+
),
17321+
}
17322+
})?;
17323+
17324+
match rs {
1727517325
Some(expr) => Ok(Statement::Return(ReturnStatement {
1727617326
value: Some(ReturnStatementValue::Expr(expr)),
1727717327
})),

src/test_utils.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#[cfg(not(feature = "std"))]
2626
use alloc::{
2727
boxed::Box,
28+
format,
2829
string::{String, ToString},
2930
vec,
3031
vec::Vec,
@@ -186,6 +187,37 @@ impl TestedDialects {
186187
statements
187188
}
188189

190+
/// The same as [`statements_parse_to`] but it will strip semicolons from the SQL text.
191+
pub fn statements_without_semicolons_parse_to(
192+
&self,
193+
sql: &str,
194+
canonical: &str,
195+
) -> Vec<Statement> {
196+
let sql_without_semicolons = sql
197+
.replace("; ", " ")
198+
.replace(" ;", " ")
199+
.replace(";\n", "\n")
200+
.replace("\n;", "\n")
201+
.replace(";", " ");
202+
let statements = self
203+
.parse_sql_statements(&sql_without_semicolons)
204+
.expect(&sql_without_semicolons);
205+
if !canonical.is_empty() && sql != canonical {
206+
assert_eq!(self.parse_sql_statements(canonical).unwrap(), statements);
207+
} else {
208+
assert_eq!(
209+
sql,
210+
statements
211+
.iter()
212+
// note: account for format_statement_list manually inserted semicolons
213+
.map(|s| s.to_string().trim_end_matches(";").to_string())
214+
.collect::<Vec<_>>()
215+
.join("; ")
216+
);
217+
}
218+
statements
219+
}
220+
189221
/// Ensures that `sql` parses as an [`Expr`], and that
190222
/// re-serializing the parse result produces canonical
191223
pub fn expr_parses_to(&self, sql: &str, canonical: &str) -> Expr {
@@ -318,6 +350,43 @@ where
318350
all_dialects_where(|d| !except(d))
319351
}
320352

353+
/// Returns all dialects that don't support statements without semicolon delimiters.
354+
/// (i.e. dialects that require semicolon delimiters.)
355+
pub fn all_dialects_requiring_semicolon_statement_delimiter() -> TestedDialects {
356+
let tested_dialects =
357+
all_dialects_except(|d| d.supports_statements_without_semicolon_delimiter());
358+
assert_ne!(tested_dialects.dialects.len(), 0);
359+
tested_dialects
360+
}
361+
362+
/// Returns all dialects that do support statements without semicolon delimiters.
363+
/// (i.e. dialects not requiring semicolon delimiters.)
364+
pub fn all_dialects_not_requiring_semicolon_statement_delimiter() -> TestedDialects {
365+
let tested_dialects =
366+
all_dialects_where(|d| d.supports_statements_without_semicolon_delimiter());
367+
assert_ne!(tested_dialects.dialects.len(), 0);
368+
tested_dialects
369+
}
370+
371+
/// Asserts an error for `parse_sql_statements`:
372+
/// - "end of statement" for dialects that require semicolon delimiters
373+
/// - "an SQL statement" for dialects that don't require semicolon delimiters.
374+
pub fn assert_err_parse_statements(sql: &str, found: &str) {
375+
assert_eq!(
376+
ParserError::ParserError(format!("Expected: end of statement, found: {found}")),
377+
all_dialects_requiring_semicolon_statement_delimiter()
378+
.parse_sql_statements(sql)
379+
.unwrap_err()
380+
);
381+
382+
assert_eq!(
383+
ParserError::ParserError(format!("Expected: an SQL statement, found: {found}")),
384+
all_dialects_not_requiring_semicolon_statement_delimiter()
385+
.parse_sql_statements(sql)
386+
.unwrap_err()
387+
);
388+
}
389+
321390
pub fn assert_eq_vec<T: ToString>(expected: &[&str], actual: &[T]) {
322391
assert_eq!(
323392
expected,

0 commit comments

Comments
 (0)