fix(database): run a SQL script's statements on one connection (#8213)

Run SQL Script, and any other run of several statements without a console (the object dialogs, for example), sent each statement to whichever pooled connection was free. A script's session state was missing for its next statement (a temporary table, BEGIN ... COMMIT, a SET), and a mysqldump file hung once the pool held several connections: LOCK TABLES ran on one connection and the INSERT after it waited for that lock on another.

Such a run now gets a script session (ConsoleId::script) that keeps one connection from its first statement on, as each database's own client runs a script, and runs in the data source's manual transaction if any rather than a console transaction. When the run ends, the session is released: what it left open is rolled back and its connection is closed instead of returning to the pool with the script's session state.

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

No files matched your search

+3 -1
Переглянути файл
@@ -163,6 +163,7 @@ pub(super) struct ConsoleSession {
impl ConsoleSession {
/// Runs `statement` on the console's connection; `None` when it has none and needs none.
/// `pinned`: a script's, which every statement needs.
#[allow(clippy::too_many_arguments)]
pub(super) async fn execute(
&self,
@@ -173,6 +174,7 @@ impl ConsoleSession {
max_rows: usize,
request: &CancellationToken,
schema: Option<&str>,
pinned: bool,
) -> IdeResult<Option<QueryResult>> {
let cancel = self.retired.child_token();
let mut slot = tokio::select! {
@@ -189,7 +191,7 @@ impl ConsoleSession {
}
let schema = schema.filter(|s| !s.is_empty());
if slot.open.is_none() {
if !needs_session(statement, pool.driver()) {
if !pinned && !needs_session(statement, pool.driver()) {
return Ok(None);
}
slot.open = Some(tokio::select! {
+13 -2
Переглянути файл
@@ -404,11 +404,21 @@ pub struct ConsoleId<'a> {
pub window: &'a str,
pub path: &'a str,
expected_manual: Option<bool>,
/// Keeps its connection from the first statement on, not from the first that needs one.
script: bool,
}
impl<'a> ConsoleId<'a> {
pub const fn new(window: &'a str, path: &'a str) -> Self {
Self { window, path, expected_manual: None }
Self { window, path, expected_manual: None, script: false }
}
/// A run of statements outside any console, `run` naming it uniquely in `window`. It runs on one
/// connection, as each database's own client runs a script, and releasing it with
/// [`DbManager::release_target_console`] closes that connection instead of returning it to the
/// pool with the session state the script left.
pub const fn script(window: &'a str, run: &'a str) -> Self {
Self { window, path: run, expected_manual: None, script: true }
}
pub fn expecting_manual(mut self, manual: Option<bool>) -> Self {
@@ -2226,7 +2236,8 @@ impl DbManager {
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
}
let editor = console.filter(|_| !matches!(&*pool, Pool::Snowflake(_)) && !pool.transaction_read_only());
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
// A script has no console transaction: it runs in the data source's manual transaction, if any.
let console = console.filter(|c| !c.script && matches!(&*pool, Pool::Postgres(_)));
let session = match console {
Some(console) => connection.console_transactions.session(console),
None => self.sessions.lock().get(id).cloned(),
+2 -1
Переглянути файл
@@ -208,7 +208,8 @@ impl ConsoleTransactions {
auto.entry(key(console)).or_default().clone()
};
// Boxed: the connect inside would double the size of every statement's future.
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema)).await
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema, console.script))
.await
}
pub(super) async fn release_auto(&self, console: ConsoleId<'_>) {
+167 -1
Переглянути файл
@@ -637,6 +637,10 @@ async fn execute_statements(
) -> IdeResult<()> {
let db = host.project(window)?.db.clone();
let (cancel, console) = console_request(host, window, request, console, console_manual)?;
// Without a console, several statements still share one connection and its session: what one
// sets, locks or begins holds for the next, and none of it is left on the pool afterwards.
let run = format!("\0script {request}");
let script = (console.is_none() && statements.len() > 1).then(|| ConsoleId::script(window, &run));
let result = async {
db.validate_console_script(id, &statements, console).await?;
for (index, statement) in statements.into_iter().enumerate() {
@@ -652,7 +656,7 @@ async fn execute_statements(
max_rows.max(1) as usize,
&cancel,
schema,
console,
console.or(script),
)
.await
{
@@ -676,6 +680,12 @@ async fn execute_statements(
Ok(())
}
.await;
// Rolls back what the script left open and closes its connection.
if let Some(script) = script
&& let Err(error) = db.release_target_console(script, Some(id)).await
{
tracing::warn!("closing the connection of a script on {id}: {}", error.message);
}
host.end_request(request);
result
}
@@ -1175,6 +1185,162 @@ mod tests {
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
}
/// What Run SQL Script sends: every statement of `script` in one run, without a console.
async fn run_script(host: &Host, request: u32, id: &str, driver: DbDriver, script: &str) -> Vec<StatementOutcome> {
let statements = ide_db::split::split(script, driver);
db_execute(host, "main", RequestId(request), id.into(), statements, 0, 10, None, None, None, None)
.await
.unwrap()
}
fn errors(outcomes: &[StatementOutcome]) -> Vec<String> {
outcomes.iter().filter_map(|o| o.error.clone()).collect()
}
fn cell(outcome: &StatementOutcome) -> Option<String> {
outcome.result.as_ref().and_then(|r| r.rows.first()?.first()?.clone())
}
/// Leaves `n` idle connections in `id`'s pool, as the database tree's loading does.
async fn warm_pool(host: &Host, id: &str, n: usize) {
let pool = host.project("main").unwrap().db.pool(id).await.unwrap();
let mut held = Vec::new();
for _ in 0..n {
held.push(ide_db::Held::acquire(&pool).await.unwrap());
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_script_runs_its_statements_on_one_connection() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let id = "test";
run_script(&host, 1, id, DbDriver::Sqlite, "CREATE TABLE items (n INTEGER)").await;
warm_pool(&host, id, 4).await;
// A temporary table, a transaction and a setting belong to their connection.
let outcomes = run_script(
&host,
2,
id,
DbDriver::Sqlite,
"CREATE TEMP TABLE scratch (n INTEGER); INSERT INTO scratch VALUES (7); BEGIN; \
INSERT INTO items SELECT n FROM scratch; COMMIT; PRAGMA cache_size = -1234; PRAGMA cache_size",
)
.await;
assert_eq!(errors(&outcomes), Vec::<String>::new());
assert_eq!(cell(outcomes.last().unwrap()).as_deref(), Some("-1234"));
let items = run_script(&host, 3, id, DbDriver::Sqlite, "SELECT n FROM items").await;
assert_eq!(cell(&items[0]).as_deref(), Some("7"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_script_leaves_no_session_state_on_the_pool() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let id = "test";
warm_pool(&host, id, 4).await;
let script = "PRAGMA cache_size = -1234; CREATE TEMP TABLE leftover (n INTEGER)";
assert_eq!(errors(&run_script(&host, 1, id, DbDriver::Sqlite, script).await), Vec::<String>::new());
// Each idle connection of the pool serves one of these in turn.
for request in 2..12 {
let probe = "PRAGMA cache_size; SELECT count(*) FROM sqlite_temp_master";
let outcomes = run_script(&host, request, id, DbDriver::Sqlite, probe).await;
assert_ne!(cell(&outcomes[0]).as_deref(), Some("-1234"), "request {request}");
assert_eq!(cell(&outcomes[1]).as_deref(), Some("0"), "request {request}");
}
}
/// A data source `id` on the server that `variable` (`host:port:user:password`) names.
async fn server_source(host: &Host, variable: &str, id: &str, driver: DbDriver, database: &str) -> bool {
let Ok(server) = std::env::var(variable) else { return false };
let mut parts = server.splitn(4, ':');
let source = DataSource {
id: id.into(),
name: id.into(),
driver,
host: parts.next().unwrap().into(),
port: Some(parts.next().unwrap().parse().unwrap()),
user: parts.next().unwrap().into(),
database: database.into(),
..Default::default()
};
// The SQL Server test containers have no certificate the driver accepts.
let source = if driver == DbDriver::SqlServer {
DataSource { ssl: ide_db::DbSslMode::Disable, ..source }
} else {
source
};
let mut sources = host.project("main").unwrap().db.sources().unwrap();
sources.push(source);
db_save_sources(host, "main", sources).await.unwrap();
db_set_password(host, "main", id.into(), parts.next().map(str::to_owned), false).await.unwrap();
true
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn server_scripts_keep_their_settings_to_themselves() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let mut failures = Vec::new();
for (variable, driver, database, set, show, value) in [
("OPENIDEA_TEST_POSTGRES", DbDriver::Postgres, "postgres", "SET work_mem = '7MB'", "SHOW work_mem", "7MB"),
(
"OPENIDEA_TEST_MYSQL",
DbDriver::Mysql,
"",
"SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION'",
"SELECT @@SESSION.sql_mode",
"NO_ENGINE_SUBSTITUTION",
),
("OPENIDEA_TEST_SQLSERVER", DbDriver::SqlServer, "tempdb", "SET DATEFIRST 3", "SELECT @@DATEFIRST", "3"),
] {
let id = format!("{driver:?}");
if !server_source(&host, variable, &id, driver, database).await {
continue;
}
warm_pool(&host, &id, 4).await;
let outcomes = run_script(&host, 1, &id, driver, &format!("{set};\n{show}")).await;
assert_eq!(errors(&outcomes), Vec::<String>::new(), "{driver:?}");
let next = cell(&outcomes[1]);
// Each idle connection of the pool serves one of these in turn.
let mut leaked = Vec::new();
for request in 2..12 {
if cell(&run_script(&host, request, &id, driver, show).await[0]).as_deref() == Some(value) {
leaked.push(request);
}
}
if next.as_deref() != Some(value) || !leaked.is_empty() {
failures.push(format!(
"{driver:?}: the script's next statement got {next:?}; requests {leaked:?} got {value}"
));
}
}
assert_eq!(failures, Vec::<String>::new());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_mysql_script_inserts_into_the_table_it_locked() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
if !server_source(&host, "OPENIDEA_TEST_MYSQL", "my", DbDriver::Mysql, "").await {
return;
}
let setup = "DROP DATABASE IF EXISTS oi_script_lock; CREATE DATABASE oi_script_lock; \
CREATE TABLE oi_script_lock.t (n INT)";
assert_eq!(errors(&run_script(&host, 1, "my", DbDriver::Mysql, setup).await), Vec::<String>::new());
warm_pool(&host, "my", 4).await;
// How mysqldump writes a table's rows.
let rows = "LOCK TABLES oi_script_lock.t WRITE; INSERT INTO oi_script_lock.t VALUES (1); UNLOCK TABLES";
let run = run_script(&host, 2, "my", DbDriver::Mysql, rows);
let outcomes = tokio::time::timeout(std::time::Duration::from_secs(15), run)
.await
.expect("the INSERT waited for the LOCK TABLES of its own script");
assert_eq!(errors(&outcomes), Vec::<String>::new());
let counted = run_script(&host, 3, "my", DbDriver::Mysql, "SELECT count(*) FROM oi_script_lock.t").await;
assert_eq!(cell(&counted[0]).as_deref(), Some("1"));
run_script(&host, 4, "my", DbDriver::Mysql, "DROP DATABASE oi_script_lock").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_page_with_a_cell_limit_carries_prefixes_and_each_whole_value_is_read_on_demand() {
let temp = tempfile::tempdir().unwrap();