fix(database): keep routine and trigger bodies, DELIMITER and GO batches whole when splitting scripts (#8214)

The console cut a script at every ; outside literals and comments, so a routine or trigger body ran in pieces: Execute on the DELETE inside a CREATE TRIGGER ... BEGIN ... END ran only that DELETE, a SQLite trigger script stopped with "incomplete input", a DELIMITER // script (mysqldump output) with 42000, a PostgreSQL BEGIN ATOMIC procedure with 42601, an SSMS script with "Incorrect syntax near 'GO'", and a SQL Server CREATE PROCEDURE kept only its first statement.

Statements now end where each dialect's own client ends them: a SQLite CREATE TRIGGER at ; END ;, PostgreSQL routines by counting BEGIN/CASE/END outside parentheses (psql), MySQL by DELIMITER lines and BEGIN ... END bodies of stored programs, with statements made only of executable comments (/*! ... */) kept, and SQL Server by GO lines, with CREATE/ALTER PROCEDURE/FUNCTION/TRIGGER taking the rest of its batch and IF ... BEGIN ... END / TRY-CATCH blocks staying whole.

Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
ntbang0901 authored and GitHub committed 2026-12-05 18:42:22 +08:00
1 джерело 4bd6f8e720
коміт 6e642b4d4b
5 files changed
+596 -13

No files matched your search

+474 -13
Переглянути файл
@@ -2,6 +2,8 @@
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
//! Routine and trigger bodies, the mysql client's `DELIMITER` and SQL Server's
//! `GO` end statements where each dialect's own client ends them.
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
use crate::DbDriver;
@@ -29,6 +31,19 @@ enum State {
BlockComment,
}
/// The routine or trigger body a statement holds: what ends the statement, as its `;` may not.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Body {
None,
/// BEGIN … END blocks (and the CASE … END inside them) outside parentheses: psql's rule for
/// PostgreSQL routines, also read in MySQL routines and every T-SQL statement.
Blocks,
/// A SQLite trigger, which only `;` END `;` ends (sqlite3_complete).
Trigger,
/// A SQL Server routine: the rest of its batch.
Batch,
}
// Starts just after the opening `/*`.
fn after_nested_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
@@ -74,6 +89,12 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
/// Every statement of `text` that contains more than whitespace and comments.
pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
split_with(text, driver, ";".into()).0
}
/// [`split`] with the mysql client's `delimiter` in effect at the start; also returns the one in
/// effect at the end.
fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlStatement>, String) {
let mysql = driver == DbDriver::Mysql;
let clickhouse = driver == DbDriver::Clickhouse;
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
@@ -114,6 +135,21 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
let mut defines = false;
// The open string is PostgreSQL's `E'…'`.
let mut escape_string = false;
let mut body = Body::None;
// Block keywords inside parentheses (a parameter named `begin`) count for nothing.
let mut parens = 0usize;
// The previous `;` of a SQLite trigger.
let mut last_semi: Option<usize> = None;
let routines = postgres || mysql || sqlite || sql_server;
// The next statement starts at `$at`, with nothing open.
macro_rules! next_statement {
($at:expr) => {{
start = $at;
has_code = false;
(depth, declarations, block, package, script, defines) = (0, false, false, false, false, false);
(body, parens, last_semi) = (Body::None, 0, None);
}};
}
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
if !has_code {
return;
@@ -135,6 +171,33 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
while i < chars.len() {
let c = chars[i].1;
let next = chars.get(i + 1).map(|c| c.1);
// Lines the client reads itself instead of sending them.
let command = match c {
'G' | 'g' => sql_server,
'D' | 'd' => mysql && !has_code,
_ => false,
};
if command && state == State::Code && starts_line(&chars, i) {
if let Some(end) = go_line(&chars, i) {
// sqlcmd and SSMS send the batch so far.
push(&mut out, start, i, has_code);
next_statement!(end);
i = end;
continue;
}
if let Some((set, end)) = delimiter_line(&chars, i) {
delimiter = set;
next_statement!(end);
i = end;
continue;
}
}
if state == State::Code && delimiter != ";" && text[byte_at(i)..].starts_with(delimiter.as_str()) {
push(&mut out, start, i, has_code);
i += delimiter.chars().count();
next_statement!(i);
continue;
}
match state {
State::Code => match c {
_ if plsql && !has_code && c.is_alphabetic() => {
@@ -164,15 +227,37 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
// Re-read this character as code (it starts BEGIN / DECLARE).
continue;
}
';' if depth == 0 && !declarations && !package => {
push(&mut out, start, if block { i + 1 } else { i }, has_code);
start = i + 1;
has_code = false;
block = false;
script = false;
defines = false;
_ if routines && !has_code && c.is_alphabetic() => {
body = body_of(&chars, i, driver);
has_code = true;
// Re-read this character as code.
continue;
}
';' => {
let ends = delimiter == ";"
&& depth == 0
&& !declarations
&& !package
&& match body {
Body::None | Body::Blocks => true,
Body::Trigger => last_semi.is_some_and(|semi| only_end(&chars, semi + 1, i)),
Body::Batch => false,
};
if ends {
push(&mut out, start, if block { i + 1 } else { i }, has_code);
next_statement!(i + 1);
} else {
has_code = true;
last_semi = Some(i);
}
}
_ if body == Body::Blocks
&& parens == 0
&& ["BEGIN", "CASE", "END"].iter().any(|w| keyword_at(&chars, i, w)) =>
{
i = block_keyword(&chars, i, driver, &mut depth);
has_code = true;
}
';' => has_code = true,
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
_ if postgres && (c.is_alphabetic() || c == '_') => {
has_code = true;
@@ -208,6 +293,12 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
i = chars.partition_point(|&(offset, _)| offset < end);
continue;
}
// MySQL runs the code of `/*! … */` and MariaDB that of `/*M! … */`: mysqldump's
// SETs and triggers are statements made of them alone.
let after = |n: usize| chars.get(i + n).map(|&(_, c)| c);
if mysql && (after(2) == Some('!') || (after(2) == Some('M') && after(3) == Some('!'))) {
has_code = true;
}
state = State::BlockComment;
i += 1;
}
@@ -313,6 +404,14 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
i = closing.map_or(i + 3, |w| after + w.len()) - 1;
has_code = true;
}
'(' => {
parens += 1;
has_code = true;
}
')' => {
parens = parens.saturating_sub(1);
has_code = true;
}
c if !c.is_whitespace() => has_code = true,
_ => {}
},
@@ -367,7 +466,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
i += 1;
}
push(&mut out, start, chars.len(), has_code);
out
(out, delimiter)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -381,10 +480,10 @@ enum Unit {
Package,
}
/// What kind of PL/SQL unit, if any, a statement starting at `i` is.
fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
/// The first `n` words from `i`, upper-cased, as long as only whitespace separates them.
fn leading_words(chars: &[(usize, char)], mut i: usize, n: usize) -> Vec<String> {
let mut words: Vec<String> = Vec::new();
while words.len() < 6 {
while words.len() < n {
let word: String = chars[i.min(chars.len())..]
.iter()
.map(|&(_, c)| c)
@@ -396,6 +495,12 @@ fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
i = skip_ws(chars, i + word.chars().count());
words.push(word.to_ascii_uppercase());
}
words
}
/// What kind of PL/SQL unit, if any, a statement starting at `i` is.
fn plsql_unit(chars: &[(usize, char)], i: usize) -> Unit {
let words = leading_words(chars, i, 6);
let w = |n: usize| words.get(n).map_or("", String::as_str);
match w(0) {
"DECLARE" | "BEGIN" => return Unit::Block,
@@ -413,6 +518,168 @@ fn plsql_unit(chars: &[(usize, char)], mut i: usize) -> Unit {
}
}
/// The body a statement starting at `i` may hold, by the rule of the dialect's own client.
fn body_of(chars: &[(usize, char)], i: usize, driver: DbDriver) -> Body {
let words = leading_words(chars, i, 4);
let w = |n: usize| words.get(n).map_or("", String::as_str);
match driver {
// sqlite3: CREATE [TEMP | TEMPORARY] TRIGGER.
DbDriver::Sqlite => {
let n = if matches!(w(1), "TEMP" | "TEMPORARY") { 2 } else { 1 };
if w(0) == "CREATE" && w(n) == "TRIGGER" { Body::Trigger } else { Body::None }
}
// psql: CREATE [OR REPLACE] {FUNCTION | PROCEDURE}.
DbDriver::Postgres => {
let n = if (w(1), w(2)) == ("OR", "REPLACE") { 3 } else { 1 };
if w(0) == "CREATE" && matches!(w(n), "FUNCTION" | "PROCEDURE") { Body::Blocks } else { Body::None }
}
DbDriver::Mysql if mysql_routine(chars, i) => Body::Blocks,
// A routine must be alone in its batch, so SQL Server reads the rest of it as the body.
DbDriver::SqlServer => {
let n = match (w(0), w(1), w(2)) {
("CREATE", "OR", "ALTER") => 3,
("CREATE" | "ALTER", ..) => 1,
_ => return Body::Blocks,
};
if matches!(w(n), "PROC" | "PROCEDURE" | "FUNCTION" | "TRIGGER") { Body::Batch } else { Body::Blocks }
}
_ => Body::None,
}
}
/// Whether a MySQL statement at `i` creates a stored program:
/// `CREATE [OR REPLACE] [DEFINER = user] [AGGREGATE] {PROCEDURE | FUNCTION | TRIGGER | EVENT}`.
fn mysql_routine(chars: &[(usize, char)], mut i: usize) -> bool {
let word = |i: &mut usize| {
let word = leading_words(chars, *i, 1).pop().unwrap_or_default();
*i = skip_ws(chars, *i + word.chars().count());
word
};
if word(&mut i) != "CREATE" {
return false;
}
let mut next = word(&mut i);
if next == "OR" && word(&mut i) == "REPLACE" {
next = word(&mut i);
}
if next == "DEFINER" {
// `= 'name'@'host'`, `name@host`, `CURRENT_USER()`…: up to a blank outside quotes.
if chars.get(i).is_some_and(|&(_, c)| c == '=') {
i = skip_ws(chars, i + 1);
}
while let Some(&(_, c)) = chars.get(i)
&& !c.is_whitespace()
{
i += 1;
if matches!(c, '\'' | '"' | '`') {
i = chars[i..].iter().position(|&(_, q)| q == c).map_or(chars.len(), |n| i + n + 1);
}
}
i = skip_ws(chars, i);
next = word(&mut i);
}
if next == "AGGREGATE" {
next = word(&mut i);
}
matches!(next.as_str(), "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT")
}
/// [`word_at`] for a keyword, which a MySQL / T-SQL `@variable` or a qualified `t.end` is not.
fn keyword_at(chars: &[(usize, char)], i: usize, word: &str) -> bool {
word_at(chars, i, word) && chars[..i].last().is_none_or(|&(_, c)| c != '@' && c != '.')
}
/// Counts the BEGIN, CASE or END at `i` into the block `depth` of a body. Returns the index of
/// its last character, or of the word after END that belongs to it.
fn block_keyword(chars: &[(usize, char)], i: usize, driver: DbDriver, depth: &mut usize) -> usize {
if word_at(chars, i, "BEGIN") {
// T-SQL's BEGIN TRAN, BEGIN DIALOG… are statements.
let after = skip_ws(chars, i + 5);
let statement = driver == DbDriver::SqlServer
&& ["TRAN", "TRANSACTION", "DISTRIBUTED", "DIALOG", "CONVERSATION"]
.iter()
.any(|w| word_at(chars, after, w));
if !statement {
*depth += 1;
}
return i + 4;
}
if word_at(chars, i, "CASE") {
// Its END closes it, not the block; outside a block it holds no `;` (psql).
if *depth > 0 {
*depth += 1;
}
return i + 3;
}
// MySQL's END IF / LOOP / REPEAT / WHILE close statements that opened no block, and T-SQL's
// END CONVERSATION is a statement; END CASE / TRY / CATCH close what they name.
let (closing, neutral): (&[&str], &[&str]) = match driver {
DbDriver::Mysql => (&["CASE"], &["IF", "LOOP", "REPEAT", "WHILE"]),
DbDriver::SqlServer => (&["TRY", "CATCH"], &["CONVERSATION"]),
_ => (&[], &[]),
};
let after = skip_ws(chars, i + 3);
let named = closing.iter().chain(neutral).find(|w| word_at(chars, after, w));
if named.is_none_or(|w| !neutral.contains(w)) {
*depth = depth.saturating_sub(1);
}
named.map_or(i + 2, |w| after + w.len() - 1)
}
/// The end (`\n` or the end of the text) of a SQL Server `GO` line starting at `i`. As in sqlcmd, a
/// `--` comment may follow GO and `GO;` is SQL. A repeat count (`GO 2`) is not run here: the line
/// is left to the server.
fn go_line(chars: &[(usize, char)], i: usize) -> Option<usize> {
if !word_at(chars, i, "GO") {
return None;
}
let end = chars[i..].iter().position(|&(_, c)| c == '\n').map_or(chars.len(), |n| i + n);
let rest: String = chars[i + 2..end].iter().map(|&(_, c)| c).collect();
let rest = rest.trim_start();
(rest.is_empty() || rest.starts_with("--")).then_some(end)
}
/// The mysql client's `DELIMITER x` at `i`: the new delimiter and the end of its line, which the
/// command takes whole. An argument the client refuses (none, a backslash) leaves it SQL.
fn delimiter_line(chars: &[(usize, char)], i: usize) -> Option<(String, usize)> {
if !word_at(chars, i, "DELIMITER") {
return None;
}
let end = chars[i..].iter().position(|&(_, c)| c == '\n').map_or(chars.len(), |n| i + n);
let line: String = chars[i + "DELIMITER".len()..end].iter().map(|&(_, c)| c).collect();
let argument = line.strip_prefix([' ', '\t'])?.trim_start_matches([' ', '\t']);
let delimiter = match argument.chars().next()? {
quote @ ('\'' | '"' | '`') => argument[1..].split(quote).next().unwrap_or_default(),
_ => argument.split([' ', '\t', '\r']).next().unwrap_or_default(),
};
(!delimiter.is_empty() && !delimiter.contains('\\')).then(|| (delimiter.to_owned(), end))
}
/// Whether only END, blanks and comments lie in `from..to`: the `;` END `;` ending a SQLite trigger.
fn only_end(chars: &[(usize, char)], from: usize, to: usize) -> bool {
let at = past_blanks(chars, from, to);
word_at(chars, at, "END") && past_blanks(chars, at + 3, to) == to
}
/// The first index of `i..to` that is neither whitespace nor in a comment.
fn past_blanks(chars: &[(usize, char)], mut i: usize, to: usize) -> usize {
let starts = |i: usize, s: &str| chars[i..to].iter().map(|&(_, c)| c).take(2).eq(s.chars());
while i < to {
if chars[i].1.is_whitespace() {
i += 1;
} else if starts(i, "--") {
i = chars[i..to].iter().position(|&(_, c)| c == '\n').map_or(to, |n| i + n);
} else if starts(i, "/*") {
i = (i + 2..to.saturating_sub(1))
.find(|&j| chars[j].1 == '*' && chars[j + 1].1 == '/')
.map_or(to, |j| j + 2);
} else {
break;
}
}
i
}
/// Whether the characters at `i` are the keyword `word` (identifier bounds respected).
fn word_at(chars: &[(usize, char)], i: usize, word: &str) -> bool {
let (before, after) = (chars[..i].last().map(|&(_, c)| c), chars.get(i).map(|&(_, c)| c));
@@ -477,7 +744,17 @@ pub fn statement_at(text: &str, offset: u32, driver: DbDriver) -> Option<SqlStat
/// selected text itself, split.
pub fn statements_in(text: &str, from: u32, to: u32, driver: DbDriver) -> Vec<SqlStatement> {
let selected = utf16_slice(text, from, to);
split(selected, driver).into_iter().map(|s| SqlStatement { from: s.from + from, to: s.to + from, ..s }).collect()
// A DELIMITER above the selection still holds in it.
let delimiter = if driver == DbDriver::Mysql {
split_with(utf16_slice(text, 0, from), driver, ";".into()).1
} else {
";".into()
};
split_with(selected, driver, delimiter)
.0
.into_iter()
.map(|s| SqlStatement { from: s.from + from, to: s.to + from, ..s })
.collect()
}
fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
@@ -765,4 +1042,188 @@ mod tests {
vec!["select case when a then 1 end, b from t", "select 2"]
);
}
#[test]
fn sqlite_triggers_end_at_end_semicolon_like_sqlite3() {
let trigger = "CREATE TRIGGER a_ins AFTER INSERT ON a BEGIN\n INSERT INTO log VALUES ('inserted ' || NEW.id);\n \
UPDATE a SET n = n + 1 WHERE id = NEW.id;\nEND";
assert_eq!(
texts(&format!("CREATE TABLE log (msg TEXT);\n{trigger};\nINSERT INTO a VALUES (1, 0);"), DbDriver::Sqlite),
vec!["CREATE TABLE log (msg TEXT)", trigger, "INSERT INTO a VALUES (1, 0)"]
);
// Only `;` END `;` ends one, whatever CASE … END and comments it holds.
let temp = "create temp trigger t after insert on a begin\n select case when new.id > 0 then 1 end;\n \
select 2; -- ; END ;\n /* END; */ select 3;\nend\n";
assert_eq!(texts(&format!("{temp};select 4"), DbDriver::Sqlite), vec![temp.trim_end(), "select 4"]);
// Execute with the caret in the body runs the whole trigger.
let console = "CREATE TRIGGER users_gone AFTER DELETE ON users BEGIN\n INSERT INTO audit VALUES ('gone');\n \
DELETE FROM sessions WHERE expires < datetime('now');\nEND;";
let caret = console.find("FROM sessions").unwrap() as u32;
let whole = console.trim_end_matches(';');
assert_eq!(statement_at(console, caret, DbDriver::Sqlite).map(|s| s.text).as_deref(), Some(whole));
// A transaction's BEGIN … END is no body.
assert_eq!(texts("BEGIN; DELETE FROM a; END;", DbDriver::Sqlite), vec!["BEGIN", "DELETE FROM a", "END"]);
}
#[test]
fn postgres_begin_atomic_bodies_like_psql() {
let procedure = "CREATE PROCEDURE insert_data(a integer, b integer)\nLANGUAGE SQL\nBEGIN ATOMIC\n \
INSERT INTO tbl VALUES (a);\n INSERT INTO tbl VALUES (b);\nEND";
let function = "create or replace function classify(x integer) returns text language sql\nbegin atomic\n \
select case when x > 0 then 'pos' else 'neg' end;\nend";
assert_eq!(
texts(
&format!("CREATE TABLE tbl (n integer);\n{procedure};\n{function};\nCALL insert_data(1, 2);"),
DbDriver::Postgres
),
vec!["CREATE TABLE tbl (n integer)", procedure, function, "CALL insert_data(1, 2)"]
);
// Words in parentheses count for nothing, and other statements have no body.
let named = "CREATE FUNCTION f(begin int) RETURNS int LANGUAGE sql RETURN 1";
assert_eq!(texts(&format!("{named}; SELECT 2"), DbDriver::Postgres), vec![named, "SELECT 2"]);
assert_eq!(
texts("BEGIN; CALL insert_data(1, 2); END; SELECT case when true then 1 end", DbDriver::Postgres),
vec!["BEGIN", "CALL insert_data(1, 2)", "END", "SELECT case when true then 1 end"]
);
}
#[test]
fn mysql_delimiter_lines_set_the_terminator_like_the_mysql_client() {
let procedure = "CREATE PROCEDURE p()\nBEGIN\n SELECT 1;\n SELECT 2;\nEND";
assert_eq!(
texts(&format!("DELIMITER //\n{procedure} //\nDELIMITER ;\nCALL p();"), DbDriver::Mysql),
vec![procedure, "CALL p()"]
);
// mysqldump's `;;`, a quoted delimiter, a lower-case command and what follows the argument.
for (command, delimiter) in
[("DELIMITER ;;", ";;"), ("delimiter '$$'", "$$"), (" DELIMITER $$ -- the rest is ignored", "$$")]
{
assert_eq!(
texts(&format!("{command}\n{procedure}{delimiter}\nSELECT 3{delimiter}"), DbDriver::Mysql),
vec![procedure, "SELECT 3"],
"{command}"
);
}
// Only at the start of a statement; an empty or backslashed argument is no command.
for sql in ["SELECT 1\nDELIMITER //\n", "DELIMITER\n", "DELIMITER \\\\\n"] {
assert_eq!(texts(&format!("{sql}SELECT 2"), DbDriver::Mysql), vec![format!("{sql}SELECT 2")]);
}
// A selection between the DELIMITER lines runs with the delimiter set above it.
let script = format!("DELIMITER //\n{procedure} //\nSELECT 3 //\nDELIMITER ;");
let from = script.find("CREATE").unwrap() as u32;
let to = script.find("\nDELIMITER ;").unwrap() as u32;
let selected: Vec<_> = statements_in(&script, from, to, DbDriver::Mysql).into_iter().map(|s| s.text).collect();
assert_eq!(selected, vec![procedure, "SELECT 3"]);
}
#[test]
fn mysql_routine_bodies_keep_their_statements() {
let trigger =
"CREATE TRIGGER t_bi BEFORE INSERT ON t FOR EACH ROW BEGIN\n SET NEW.a = 1;\n SET NEW.b = 2;\nEND";
let procedure = "CREATE DEFINER=`root`@`%` PROCEDURE p(IN n INT)\nBEGIN\n DECLARE i INT DEFAULT 0;\n \
lbl: LOOP\n SET i = i + 1;\n IF i >= n THEN LEAVE lbl; END IF;\n END LOOP lbl;\n \
CASE WHEN i > 1 THEN SELECT 'many'; ELSE SELECT 'one'; END CASE;\n \
SELECT CASE WHEN i = 3 THEN 'three' END AS c;\nEND";
let event = "CREATE EVENT e ON SCHEDULE EVERY 1 HOUR ENDS NOW() + INTERVAL 1 DAY DO BEGIN DELETE FROM t; END";
let function = "CREATE DEFINER = CURRENT_USER() FUNCTION f() RETURNS INT DETERMINISTIC BEGIN\n \
SET @begin = 1;\n RETURN (SELECT t.end FROM t LIMIT 1);\nEND";
assert_eq!(
texts(
&format!("{trigger};\n{procedure};\n{event};\n{function};\nINSERT INTO t (id) VALUES (1);"),
DbDriver::Mysql
),
vec![trigger, procedure, event, function, "INSERT INTO t (id) VALUES (1)"]
);
// Outside a routine BEGIN starts a transaction.
assert_eq!(texts("BEGIN; DELETE FROM t; COMMIT", DbDriver::Mysql), vec!["BEGIN", "DELETE FROM t", "COMMIT"]);
}
#[test]
fn mysql_executable_comments_are_statements() {
// Lines of a mysqldump 8.4 dump: its SETs and triggers are code the server runs.
let trigger = "/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `orders_ai` AFTER INSERT \
ON `orders` FOR EACH ROW BEGIN\n UPDATE customers SET orders_count = orders_count + 1 WHERE id = \
NEW.customer_id;\nEND */";
let procedure = "CREATE DEFINER=`root`@`localhost` PROCEDURE `add_order`(IN p_id INT)\nBEGIN\n \
INSERT INTO orders (id) VALUES (p_id);\nEND";
let dump = format!(
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n\
INSERT INTO `orders` VALUES (10,1,'first; with a semicolon');\n\
/*!50003 SET character_set_client = latin1 */ ;\nDELIMITER ;;\n{trigger};;\nDELIMITER ;\n\
/*!50003 DROP PROCEDURE IF EXISTS `add_order` */;\nDELIMITER ;;\n{procedure} ;;\nDELIMITER ;\n\
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*M!100100 SET @x = 1 */;\n\
/* a note */;\n-- Dump completed\n"
);
assert_eq!(
texts(&dump, DbDriver::Mysql),
vec![
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */",
"INSERT INTO `orders` VALUES (10,1,'first; with a semicolon')",
"/*!50003 SET character_set_client = latin1 */",
trigger,
"/*!50003 DROP PROCEDURE IF EXISTS `add_order` */",
procedure,
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */",
"/*M!100100 SET @x = 1 */",
]
);
// The `;` inside one stays in it, also without DELIMITER.
let inline = "/*!50003 TRIGGER t BEFORE INSERT ON a FOR EACH ROW BEGIN SET NEW.n = 1; END */";
assert_eq!(texts(&format!("{inline};\nSELECT 2"), DbDriver::Mysql), vec![inline, "SELECT 2"]);
// Elsewhere they are comments.
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer] {
assert_eq!(texts("/*!40101 SET NAMES utf8 */;\nSELECT 2", driver), vec!["SELECT 2"]);
}
}
#[test]
fn sql_server_go_lines_end_batches_like_sqlcmd() {
let procedure = "CREATE PROCEDURE p AS\nBEGIN\n SET NOCOUNT ON;\n SELECT a FROM t;\nEND";
assert_eq!(
texts(&format!("CREATE TABLE t (a int)\nGO\n{procedure}\n go -- done\nEXEC p\nGo"), DbDriver::SqlServer),
vec!["CREATE TABLE t (a int)", procedure, "EXEC p"]
);
// GO in a string or comment, `GOTO`, `GO 2` (a repeat count) and `GO;` are left to the server.
for sql in ["SELECT 'a\nGO\n'", "/* a\nGO\n*/ SELECT 1", "SELECT 1\nGOTO x", "SELECT 1\nGO 2"] {
assert_eq!(texts(&format!("{sql}\nSELECT 2"), DbDriver::SqlServer), vec![format!("{sql}\nSELECT 2")]);
}
assert_eq!(texts("SELECT 1\nGO;\nSELECT 2", DbDriver::SqlServer), vec!["SELECT 1\nGO", "SELECT 2"]);
let script = format!("SELECT 0\nGO\n{procedure}\nGO\nSELECT 3");
let caret = script.find("SELECT a").unwrap() as u32;
assert_eq!(statement_at(&script, caret, DbDriver::SqlServer).map(|s| s.text).as_deref(), Some(procedure));
}
#[test]
fn sql_server_routines_run_to_the_end_of_their_batch() {
for routine in [
"CREATE PROCEDURE p AS SELECT 1 AS one; SELECT 2 AS two;",
"create or alter function f() returns int as begin declare @n int = 1; return @n; end;",
"ALTER PROC p AS SET NOCOUNT ON; SELECT 1",
"CREATE TRIGGER tr ON t AFTER INSERT AS INSERT INTO log VALUES (1); INSERT INTO log VALUES (2)",
] {
assert_eq!(texts(routine, DbDriver::SqlServer), vec![routine]);
assert_eq!(texts(&format!("{routine}\nGO\nEXEC p"), DbDriver::SqlServer), vec![routine, "EXEC p"]);
}
}
#[test]
fn sql_server_blocks_keep_their_statements() {
let block =
"IF OBJECT_ID('t') IS NOT NULL\nBEGIN\n INSERT INTO t VALUES (2);\n INSERT INTO t VALUES (3);\nEND";
let tried = "BEGIN TRY\n SELECT 1/0 AS boom;\nEND TRY\nBEGIN CATCH\n \
SELECT CASE WHEN ERROR_NUMBER() > 0 THEN 1 END;\n DECLARE @begin int = 1;\nEND CATCH";
assert_eq!(
texts(&format!("{block};\n{tried};\nBEGIN TRAN;\nINSERT INTO t VALUES (4);\nCOMMIT;"), DbDriver::SqlServer),
vec![block, tried, "BEGIN TRAN", "INSERT INTO t VALUES (4)", "COMMIT"]
);
}
#[test]
fn client_commands_and_bodies_of_other_dialects_are_sql() {
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::Clickhouse, DbDriver::Jdbc] {
assert_eq!(texts("SELECT 1\nGO\nSELECT 2", driver), vec!["SELECT 1\nGO\nSELECT 2"]);
assert_eq!(texts("DELIMITER //\nSELECT 1 //", driver), vec!["DELIMITER //\nSELECT 1 //"]);
assert_eq!(texts("CREATE PROCEDURE p AS SELECT 1; SELECT 2", driver).len(), 2);
}
}
}
+30
Переглянути файл
@@ -346,6 +346,36 @@ async fn submits_binary_keys_and_values_as_bytes_and_a_missed_key_fails() -> Ide
Ok(())
}
#[tokio::test]
async fn a_script_keeps_routine_bodies_and_delimiter_blocks_whole() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
let c = CancellationToken::new();
for stmt in ["DROP DATABASE IF EXISTS oi_split", "CREATE DATABASE oi_split"] {
db.execute("m", stmt, 1, &c).await?;
}
// A trigger written without DELIMITER, one as mysqldump writes it (in executable comments), then
// a procedure in the mysql client's DELIMITER form.
let script = "CREATE TABLE oi_split.t (id INT PRIMARY KEY, a INT, b INT);\n\
CREATE TABLE oi_split.log (id INT);\n\
CREATE TRIGGER oi_split.t_bi BEFORE INSERT ON oi_split.t FOR EACH ROW BEGIN\n \
SET NEW.a = 1;\n SET NEW.b = 2;\nEND;\nDELIMITER ;;\n\
/*!50003 CREATE*/ /*!50017 DEFINER=CURRENT_USER*/ /*!50003 TRIGGER oi_split.t_ai AFTER INSERT ON \
oi_split.t FOR EACH ROW BEGIN\n INSERT INTO oi_split.log VALUES (NEW.id);\nEND */;;\n\
DELIMITER //\nCREATE PROCEDURE oi_split.p()\nBEGIN\n \
INSERT INTO oi_split.t (id) VALUES (1);\n INSERT INTO oi_split.t (id) VALUES (2);\nEND //\n\
DELIMITER ;\nCALL oi_split.p();";
for statement in ide_db::split::split(script, DbDriver::Mysql) {
db.execute("m", &statement.text, 10, &c).await?;
}
let r = db
.execute("m", "SELECT count(*), sum(a), sum(b), (SELECT count(*) FROM oi_split.log) FROM oi_split.t", 1, &c)
.await?;
assert_eq!(r.rows, [[Some("2".into()), Some("2".into()), Some("4".into()), Some("2".into())]]);
db.execute("m", "DROP DATABASE oi_split", 1, &c).await?;
Ok(())
}
#[tokio::test]
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
+22
Переглянути файл
@@ -566,6 +566,28 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
async fn a_script_keeps_begin_atomic_bodies_whole() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
for cleanup in ["DROP PROCEDURE IF EXISTS oi_split_insert", "DROP TABLE IF EXISTS oi_split"] {
db.execute("p", cleanup, 1, &c).await?;
}
// The example of the CREATE PROCEDURE manual page, run statement by statement as the console does.
let script = "CREATE TABLE oi_split (n integer);\nCREATE PROCEDURE oi_split_insert(a integer, b integer)\n\
LANGUAGE SQL\nBEGIN ATOMIC\n INSERT INTO oi_split VALUES (a);\n INSERT INTO oi_split VALUES (b);\nEND;\n\
CALL oi_split_insert(1, 2);";
for statement in ide_db::split::split(script, DbDriver::Postgres) {
db.execute("p", &statement.text, 10, &c).await?;
}
assert_eq!(db.execute("p", "SELECT count(*) FROM oi_split", 1, &c).await?.rows, [[Some("2".into())]]);
for cleanup in ["DROP PROCEDURE oi_split_insert", "DROP TABLE oi_split"] {
db.execute("p", cleanup, 1, &c).await?;
}
Ok(())
}
#[tokio::test]
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
+32
Переглянути файл
@@ -448,6 +448,38 @@ async fn lists_triggers_and_their_ddl() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
async fn scripts_and_execute_at_the_caret_keep_trigger_bodies_whole() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
// A script runs its statements one by one, as the console and Run SQL Script do.
let script = "CREATE TABLE log (msg TEXT);\nCREATE TRIGGER users_added AFTER INSERT ON users BEGIN\n \
INSERT INTO log VALUES ('added ' || NEW.name);\n UPDATE users SET note = 'logged' WHERE id = NEW.id;\nEND;\n\
INSERT INTO users (name) VALUES ('dee');";
for statement in ide_db::split::split(script, DbDriver::Sqlite) {
db.execute("s1", &statement.text, 10, &c).await?;
}
let r = db
.execute("s1", "SELECT (SELECT group_concat(msg) FROM log), (SELECT note FROM users WHERE name = 'dee')", 1, &c)
.await?;
assert_eq!(r.rows, [[Some("added dee".into()), Some("logged".into())]]);
// Execute with the caret on the body's DELETE creates the trigger and deletes nothing.
let console = "CREATE TRIGGER users_gone AFTER DELETE ON users BEGIN\n DELETE FROM log;\nEND;";
let caret = console.find("FROM log").unwrap() as u32;
let statement = ide_db::split::statement_at(console, caret, DbDriver::Sqlite).unwrap();
db.execute("s1", &statement.text, 10, &c).await?;
let r = db
.execute(
"s1",
"SELECT (SELECT count(*) FROM log), (SELECT count(*) FROM sqlite_master WHERE type = 'trigger')",
1,
&c,
)
.await?;
assert_eq!(r.rows, [[Some("1".into()), Some("2".into())]]);
Ok(())
}
#[tokio::test]
async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeResult<()> {
let (tmp, db) = setup().await;
+38
Переглянути файл
@@ -158,6 +158,44 @@ async fn sqlserver_submits_binary_keys_and_values_as_bytes() {
db.execute("s", &format!("DROP TABLE dbo.{table}"), 1, &c).await.unwrap();
}
#[tokio::test]
async fn sqlserver_scripts_keep_go_batches_and_routine_bodies_whole() {
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let mut parts = server.splitn(4, ':');
let source = DataSource {
driver: DbDriver::SqlServer,
host: parts.next().unwrap().into(),
port: Some(parts.next().unwrap().parse().unwrap()),
user: parts.next().unwrap().into(),
database: "tempdb".into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let pool = Pool::connect(&source, parts.next(), None).await.unwrap();
let cancel = CancellationToken::new();
let (table, proc) =
(format!("dbo.oi_split_{}", std::process::id()), format!("dbo.oi_split_p_{}", std::process::id()));
// An SSMS-style script, run statement by statement as the console does.
let script = format!(
"CREATE TABLE {table} (a int)\nGO\nCREATE PROCEDURE {proc} AS\nBEGIN\n SET NOCOUNT ON;\n \
INSERT INTO {table} VALUES (1);\n INSERT INTO {table} VALUES (2);\nEND\nGO\nEXEC {proc}"
);
for statement in ide_db::split::split(&script, DbDriver::SqlServer) {
pool.execute(&statement.text, 10, &cancel).await.unwrap();
}
assert_eq!(pool.rows(&format!("SELECT count(*) FROM {table}"), 1).await.unwrap(), [[Some("2".into())]]);
// Without GO, SQL Server reads the rest of the batch as the body.
let body = format!("CREATE PROCEDURE {proc}_q AS SELECT 1 AS one; SELECT 2 AS two;");
for statement in ide_db::split::split(&body, DbDriver::SqlServer) {
pool.execute(&statement.text, 10, &cancel).await.unwrap();
}
let definition = pool.rows(&format!("SELECT OBJECT_DEFINITION(OBJECT_ID('{proc}_q'))"), 1).await.unwrap();
assert_eq!(definition, [[Some(body)]]);
pool.execute(&format!("DROP PROCEDURE {proc}; DROP PROCEDURE {proc}_q; DROP TABLE {table}"), 1, &cancel)
.await
.unwrap();
}
#[tokio::test]
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };