From aec6972495c2ce43cc547d1dc8d6803ff7bb29aa Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Fri, 4 Dec 2026 23:21:02 +0000 Subject: [PATCH 1/4] Report SQL file syntax errors before execution --- CHANGELOG.md | 1 + .../your-first-sql-website/tutorial.md | 2 +- src/webserver/database/sql.rs | 175 ++++++++---------- tests/errors/mod.rs | 12 ++ tests/errors/syntax_error.sql | 2 + 5 files changed, 89 insertions(+), 103 deletions(-) create mode 100644 tests/errors/syntax_error.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 69f3bc898..3e68ac773 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## unreleased +- SQLPage reports syntax errors before running any statements in the affected SQL file. ([#1706](https://github.com/sqlpage/SQLPage/discussions/1706)) - OIDC logs focus on configuration and failures. SQLPage omits tokens, cookie values, user claims, and callback and logout query strings from OIDC diagnostics. - Standard alert descriptions have higher text contrast. - An `alert` without `color` uses the info color again, and its `role` attribute no longer starts with a space. ([#1697](https://github.com/sqlpage/SQLPage/issues/1697)) diff --git a/examples/official-site/your-first-sql-website/tutorial.md b/examples/official-site/your-first-sql-website/tutorial.md index 7ef99a11e..cf4fd1f9f 100644 --- a/examples/official-site/your-first-sql-website/tutorial.md +++ b/examples/official-site/your-first-sql-website/tutorial.md @@ -10,7 +10,7 @@ In the root folder of your SQLPage website, create a new SQL file called `index. Open it in a text editor that supports SQL syntax highlighting (I recommend [VSCode](https://code.visualstudio.com/)). The `index.sql` file will be executed every time a visitor opens your website's home page, and the results will be displayed to the visitor -using the components you specify in the file. +using the components you specify in the file. If SQLPage finds a syntax error, it reports the error before running any statement in that file. Let's start with a simple `index.sql` that displays a list of popular websites: diff --git a/src/webserver/database/sql.rs b/src/webserver/database/sql.rs index 65c4db86a..3a90c0663 100644 --- a/src/webserver/database/sql.rs +++ b/src/webserver/database/sql.rs @@ -3,10 +3,9 @@ //! A routed `.sql` file reaches this module before request-specific values are //! available. It selects the connected DBMS's parser dialect, tokenizes and //! parses statements with source locations, and classifies each statement as a -//! query, `SQLPage` `SET` assignment, CSV import, or error. Parse and rewrite -//! errors are retained as statements so they can flow through `SQLPage`'s normal -//! execution and rendering error path, while the resulting [`SqlFile`] remains -//! request-independent and safe to reuse from the file cache. +//! query, `SQLPage` `SET` assignment, CSV import, or error. A syntax error +//! replaces the entire execution plan. Rewrite errors are recorded at the +//! statement that failed. The [`SqlFile`] is safe to reuse from the file cache. //! //! Ordinary statements and `SET` value queries are delegated to [`rewrite`], //! which lowers the parsed AST into database SQL plus SQLPage-owned expressions. @@ -15,7 +14,6 @@ //! `SQLPage` expressions. This module therefore owns parsing and statement //! classification, but not query execution or database-row decoding. -use std::fmt::Write as _; use std::path::Path; use async_trait::async_trait; @@ -27,7 +25,7 @@ use sqlparser::ast::{ use sqlparser::dialect::Dialect; use sqlparser::parser::{Parser, ParserError}; use sqlparser::tokenizer::Token::{self, EOF, SemiColon}; -use sqlparser::tokenizer::{Location, Span, TokenWithSpan, Tokenizer}; +use sqlparser::tokenizer::{Location, TokenWithSpan, Tokenizer}; #[cfg(test)] use super::SupportedDatabase; @@ -64,7 +62,7 @@ impl SqlFile { dialect ); let statements = match parse_sql(database, dialect.as_ref(), sql) { - Ok(statements) => statements.collect::>().into_boxed_slice(), + Ok(statements) => statements.into_boxed_slice(), Err(error) => { return Self::from_error(error, source_path); } @@ -99,11 +97,11 @@ impl AsyncFromStrWithState for SqlFile { } } -fn parse_sql<'a>( - database: &'a DbInfo, - dialect: &'a dyn Dialect, - sql: &'a str, -) -> anyhow::Result + 'a> { +fn parse_sql( + database: &DbInfo, + dialect: &dyn Dialect, + sql: &str, +) -> anyhow::Result> { log::trace!("Parsing {} SQL: {sql}", database.dbms_name); let tokens = Tokenizer::new(dialect, sql) .tokenize_with_location() @@ -115,49 +113,41 @@ fn parse_sql<'a>( )) })?; let mut parser = Parser::new(dialect).with_tokens_with_locations(tokens); - let mut has_error = false; - Ok(std::iter::from_fn(move || { - if has_error { - return None; + let mut statements = Vec::new(); + while parser.peek_token() != EOF { + let statement = parser + .parse_statement() + .map_err(|error| syntax_error(error, sql))?; + let mut semicolon = false; + while parser.consume_token(&SemiColon) { + semicolon = true; } - let statement = parse_single_statement(&mut parser, database, sql); - if matches!(statement, Some(FileStatement::Error(_))) { - has_error = true; + let statement = rewrite_statement(statement, database, semicolon); + let failed = matches!(statement, FileStatement::Error(_)); + statements.push(statement); + if failed { + break; } - statement - })) + } + Ok(statements) } -fn parse_single_statement( - parser: &mut Parser<'_>, +fn rewrite_statement( + mut statement: Statement, database: &DbInfo, - source_sql: &str, -) -> Option { - if parser.peek_token() == EOF { - return None; - } - let mut statement = match parser.parse_statement() { - Ok(statement) => statement, - Err(error) => return Some(syntax_error(error, parser, source_sql)), - }; - let mut semicolon = false; - while parser.consume_token(&SemiColon) { - semicolon = true; - } - + semicolon: bool, +) -> FileStatement { if let Some(statement) = extract_set_variable(&mut statement, database) { - return Some(statement); + return statement; } if let Some(csv_import) = extract_csv_copy_statement(&mut statement) { - return Some(FileStatement::CsvImport(csv_import)); + return FileStatement::CsvImport(csv_import); } - Some( - match rewrite::rewrite_query(statement, database, semicolon) { - Ok(query) => FileStatement::Query(query), - Err(error) => FileStatement::Error(error), - }, - ) + match rewrite::rewrite_query(statement, database, semicolon) { + Ok(query) => FileStatement::Query(query), + Err(error) => FileStatement::Error(error), + } } fn extract_set_variable(statement: &mut Statement, database: &DbInfo) -> Option { @@ -193,29 +183,23 @@ fn extract_set_variable(statement: &mut Statement, database: &DbInfo) -> Option< ) } -fn syntax_error(error: ParserError, parser: &Parser<'_>, sql: &str) -> FileStatement { - let Span { - start: Location { - line: start_line, - column: start_column, - }, - end: Location { line: end_line, .. }, - } = parser.peek_token_no_skip().span; - let mut message = String::from( - "Parsing failed: SQLPage couldn't understand the SQL file. Please check for syntax errors on ", - ); - if start_line == end_line { - write!(&mut message, "line {start_line}:").unwrap(); - } else { - write!(&mut message, "lines {start_line} to {end_line}:").unwrap(); - } - write!( - &mut message, - "\n{}", - quote_source_with_highlight(sql, start_line, start_column) - ) - .unwrap(); - FileStatement::Error(anyhow::Error::from(error).context(message)) +fn syntax_error(error: ParserError, sql: &str) -> anyhow::Error { + let Some(location) = parser_error_location(&error) else { + return error.into(); + }; + let excerpt = quote_source_with_highlight(sql, location.line, location.column); + anyhow::Error::new(error).context(excerpt) +} + +// sqlparser includes the offending token's location only in its error message. +// The parser cursor may already be past that token when parsing fails. +fn parser_error_location(error: &ParserError) -> Option { + let ParserError::ParserError(message) = error else { + return None; + }; + let (_, position) = message.rsplit_once(" at Line: ")?; + let (line, column) = position.split_once(", Column: ")?; + Some(Location::new(line.parse().ok()?, column.parse().ok()?)) } fn expression_to_query(expression: Expr) -> Statement { @@ -292,24 +276,24 @@ mod tests { } } + fn parse_one(database: &DbInfo, dialect: &dyn Dialect, sql: &str) -> FileStatement { + let mut statements = parse_sql(database, dialect, sql).unwrap(); + assert_eq!(statements.len(), 1); + statements.pop().unwrap() + } + fn one(sql: &str) -> FileStatement { one_for(SupportedDatabase::Postgres, sql) } fn one_for(database_type: SupportedDatabase, sql: &str) -> FileStatement { let database = database(database_type); - parse_sql(&database, &PostgreSqlDialect {}, sql) - .unwrap() - .next() - .unwrap() + parse_one(&database, &PostgreSqlDialect {}, sql) } fn one_mssql(sql: &str) -> FileStatement { let database = database(SupportedDatabase::Mssql); - parse_sql(&database, &MsSqlDialect {}, sql) - .unwrap() - .next() - .unwrap() + parse_one(&database, &MsSqlDialect {}, sql) } fn rewrite_database(sql: &str) -> DatabaseQuery { @@ -486,16 +470,15 @@ mod tests { #[test] fn positional_bindings_follow_source_order() { let database = database(SupportedDatabase::MySql); - let mut statements = parse_sql( + let statement = parse_one( &database, &MySqlDialect {}, "select $a, upper(sqlpage.url_encode($b))", - ) - .unwrap(); + ); let FileStatement::Query(Query { body: QueryBody::Database(query), .. - }) = statements.next().unwrap() + }) = statement else { panic!("expected database query"); }; @@ -513,14 +496,11 @@ mod tests { #[test] fn positional_bindings_follow_cte_rendering_order() { let database = database(SupportedDatabase::MySql); - let statement = parse_sql( + let statement = parse_one( &database, &MySqlDialect {}, "with c as (select $a as x) select $b as y from c", - ) - .unwrap() - .next() - .unwrap(); + ); let FileStatement::Query(Query { body: QueryBody::Database(query), .. @@ -535,14 +515,11 @@ mod tests { #[test] fn positional_bindings_follow_rendered_projection_order() { let database = database(SupportedDatabase::MySql); - let statement = parse_sql( + let statement = parse_one( &database, &MySqlDialect {}, "select $a as a, sqlpage.url_encode(upper(col || sqlpage.url_encode($b))) as b, $c as c from t", - ) - .unwrap() - .next() - .unwrap(); + ); let FileStatement::Query(Query { body: QueryBody::Database(query), .. @@ -662,14 +639,11 @@ mod tests { #[test] fn placeholder_like_literal_is_not_rewritten() { let database = database(SupportedDatabase::MySql); - let statement = parse_sql( + let statement = parse_one( &database, &MySqlDialect {}, "select '@SQLPAGE_TEMP1' where id = $id", - ) - .unwrap() - .next() - .unwrap(); + ); let FileStatement::Query(Query { body: QueryBody::Database(query), .. @@ -719,10 +693,7 @@ mod tests { let FileStatement::Query(Query { body: QueryBody::Database(query), .. - }) = parse_sql(&info, dialect.as_ref(), "select $b, $a, $b from t") - .unwrap() - .next() - .unwrap() + }) = parse_one(&info, dialect.as_ref(), "select $b, $a, $b from t") else { panic!("expected database query for {db:?} via {kind:?}"); }; @@ -1083,11 +1054,11 @@ mod tests { } fn sql_for_dbinfo(info: &DbInfo, sql: &str) -> String { - match parse_sql(info, &PostgreSqlDialect {}, sql).unwrap().next() { - Some(FileStatement::Query(Query { + match parse_one(info, &PostgreSqlDialect {}, sql) { + FileStatement::Query(Query { body: QueryBody::Database(q), .. - })) => q.sql, + }) => q.sql, other => panic!("Expected database query for `{sql}`\nGot: {other:?}"), } } diff --git a/tests/errors/mod.rs b/tests/errors/mod.rs index 4005c99c9..7832d842a 100644 --- a/tests/errors/mod.rs +++ b/tests/errors/mod.rs @@ -4,6 +4,18 @@ use crate::common::{make_app_data_from_config, response_with, response_with_data mod basic_auth; mod invalid_header; +#[actix_web::test] +async fn syntax_error_precedes_redirect() { + let resp = crate::common::response_for("/tests/errors/syntax_error.sql").await; + let body = crate::common::read_body_string(resp).await; + assert!( + body.contains("found: INTO at Line: 2, Column: 21"), + "{body}" + ); + assert!(body.contains("\n ⬆️"), "{body}"); + assert!(body.contains("syntax_error.sql"), "{body}"); +} + /// Regression test for a cache privilege-escalation bug. /// /// `sqlpage.run_sql(...)` loads include files with privilege, so it is allowed to diff --git a/tests/errors/syntax_error.sql b/tests/errors/syntax_error.sql new file mode 100644 index 000000000..71bb3b985 --- /dev/null +++ b/tests/errors/syntax_error.sql @@ -0,0 +1,2 @@ +SELECT 'redirect' AS component, '/' AS link; +SET new_id = INSERT INTO shelves (name) VALUES ('Books') RETURNING id; From b02cc959cba362de769bd2db3787e97d02343656 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Fri, 4 Dec 2026 23:25:21 +0000 Subject: [PATCH 2/4] Use a missing operand in the syntax error fixture --- tests/errors/mod.rs | 7 ++----- tests/errors/syntax_error.sql | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/tests/errors/mod.rs b/tests/errors/mod.rs index 7832d842a..67045c6bb 100644 --- a/tests/errors/mod.rs +++ b/tests/errors/mod.rs @@ -8,11 +8,8 @@ mod invalid_header; async fn syntax_error_precedes_redirect() { let resp = crate::common::response_for("/tests/errors/syntax_error.sql").await; let body = crate::common::read_body_string(resp).await; - assert!( - body.contains("found: INTO at Line: 2, Column: 21"), - "{body}" - ); - assert!(body.contains("\n ⬆️"), "{body}"); + assert!(body.contains("found: ) at Line: 2, Column: 13"), "{body}"); + assert!(body.contains("SELECT (1 + );\n ⬆️"), "{body}"); assert!(body.contains("syntax_error.sql"), "{body}"); } diff --git a/tests/errors/syntax_error.sql b/tests/errors/syntax_error.sql index 71bb3b985..783bab5db 100644 --- a/tests/errors/syntax_error.sql +++ b/tests/errors/syntax_error.sql @@ -1,2 +1,2 @@ SELECT 'redirect' AS component, '/' AS link; -SET new_id = INSERT INTO shelves (name) VALUES ('Books') RETURNING id; +SELECT (1 + ); From 5ea3569f665931ace79db6b6b896f200abb06bc5 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Fri, 4 Dec 2026 23:25:44 +0000 Subject: [PATCH 3/4] Remove the tutorial edit from the syntax error fix --- examples/official-site/your-first-sql-website/tutorial.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/official-site/your-first-sql-website/tutorial.md b/examples/official-site/your-first-sql-website/tutorial.md index cf4fd1f9f..7ef99a11e 100644 --- a/examples/official-site/your-first-sql-website/tutorial.md +++ b/examples/official-site/your-first-sql-website/tutorial.md @@ -10,7 +10,7 @@ In the root folder of your SQLPage website, create a new SQL file called `index. Open it in a text editor that supports SQL syntax highlighting (I recommend [VSCode](https://code.visualstudio.com/)). The `index.sql` file will be executed every time a visitor opens your website's home page, and the results will be displayed to the visitor -using the components you specify in the file. If SQLPage finds a syntax error, it reports the error before running any statement in that file. +using the components you specify in the file. Let's start with a simple `index.sql` that displays a list of popular websites: From d2a0f8fce06270e6e0606a803844804bd6166427 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Fri, 4 Dec 2026 23:33:37 +0000 Subject: [PATCH 4/4] Use the statement span for syntax error context --- src/webserver/database/sql.rs | 40 +++++++++++++---------------------- tests/errors/mod.rs | 2 +- 2 files changed, 16 insertions(+), 26 deletions(-) diff --git a/src/webserver/database/sql.rs b/src/webserver/database/sql.rs index 3a90c0663..0f005c3df 100644 --- a/src/webserver/database/sql.rs +++ b/src/webserver/database/sql.rs @@ -16,6 +16,7 @@ use std::path::Path; +use anyhow::Context as _; use async_trait::async_trait; use sqlparser::ast::helpers::attached_token::AttachedToken; use sqlparser::ast::{ @@ -23,9 +24,9 @@ use sqlparser::ast::{ Statement, Value, }; use sqlparser::dialect::Dialect; -use sqlparser::parser::{Parser, ParserError}; +use sqlparser::parser::Parser; use sqlparser::tokenizer::Token::{self, EOF, SemiColon}; -use sqlparser::tokenizer::{Location, TokenWithSpan, Tokenizer}; +use sqlparser::tokenizer::{TokenWithSpan, Tokenizer}; #[cfg(test)] use super::SupportedDatabase; @@ -114,10 +115,18 @@ fn parse_sql( })?; let mut parser = Parser::new(dialect).with_tokens_with_locations(tokens); let mut statements = Vec::new(); - while parser.peek_token() != EOF { - let statement = parser - .parse_statement() - .map_err(|error| syntax_error(error, sql))?; + loop { + let first = parser.peek_token_ref(); + if first.token == EOF { + break; + } + let start = first.span.start; + let statement = parser.parse_statement().with_context(|| { + format!( + "While parsing the statement starting here:\n{}", + quote_source_with_highlight(sql, start.line, start.column) + ) + })?; let mut semicolon = false; while parser.consume_token(&SemiColon) { semicolon = true; @@ -183,25 +192,6 @@ fn extract_set_variable(statement: &mut Statement, database: &DbInfo) -> Option< ) } -fn syntax_error(error: ParserError, sql: &str) -> anyhow::Error { - let Some(location) = parser_error_location(&error) else { - return error.into(); - }; - let excerpt = quote_source_with_highlight(sql, location.line, location.column); - anyhow::Error::new(error).context(excerpt) -} - -// sqlparser includes the offending token's location only in its error message. -// The parser cursor may already be past that token when parsing fails. -fn parser_error_location(error: &ParserError) -> Option { - let ParserError::ParserError(message) = error else { - return None; - }; - let (_, position) = message.rsplit_once(" at Line: ")?; - let (line, column) = position.split_once(", Column: ")?; - Some(Location::new(line.parse().ok()?, column.parse().ok()?)) -} - fn expression_to_query(expression: Expr) -> Statement { if let Expr::Subquery(query) = expression { return Statement::Query(query); diff --git a/tests/errors/mod.rs b/tests/errors/mod.rs index 67045c6bb..615aec345 100644 --- a/tests/errors/mod.rs +++ b/tests/errors/mod.rs @@ -9,7 +9,7 @@ async fn syntax_error_precedes_redirect() { let resp = crate::common::response_for("/tests/errors/syntax_error.sql").await; let body = crate::common::read_body_string(resp).await; assert!(body.contains("found: ) at Line: 2, Column: 13"), "{body}"); - assert!(body.contains("SELECT (1 + );\n ⬆️"), "{body}"); + assert!(body.contains("SELECT (1 + );\n⬆️"), "{body}"); assert!(body.contains("syntax_error.sql"), "{body}"); }