fix(database): isolate ClickHouse console sessions (#6455)

The built-in ClickHouse HTTP driver gives each SQL console its own named session: a second console finishes while the first one runs, and repeated statements in one console keep their SET values and temporary tables. Result paging, Explain and Stop use the same console identity, and closing the console's last editor or result releases it. Requests without a console stay stateless and can run concurrently. The PR also carries the TODO layout and bookmarks fixture fixes from #6507/#6458.

Closes #6433

Co-authored-by: principalwater <[email protected]>
Цей коміт міститься в:
Vladislav Kuzmin authored and GitHub committed 2026-11-28 05:50:23 +08:00
1 джерело b2998cb37a
коміт 75a15b7eed
16 files changed
+652 -135

No files matched your search

+223 -73
Переглянути файл
@@ -1,11 +1,13 @@
use crate::ConsoleId;
use crate::conn::{QueryResult, ResultColumn, Setup};
use crate::source::{DataSource, DbSslMode, DbTxMode};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::RwLock;
use reqwest::{Client, RequestBuilder, StatusCode, Url};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::sync::{Mutex, MutexGuard};
#[derive(Clone)]
pub struct ClickhousePool(Arc<State>);
@@ -18,11 +20,17 @@ struct State {
database: String,
settings: Vec<(String, String)>,
read_only: bool,
session: Mutex<Session>,
connect_timeout: Duration,
startup_statements: Vec<String>,
use_http_session: bool,
session: SessionSlot,
console_sessions: parking_lot::Mutex<HashMap<(String, String), Arc<SessionSlot>>>,
closed: CancellationToken,
}
#[derive(Default)]
type SessionSlot = Mutex<Option<Session>>;
#[derive(Clone, Default)]
struct Session {
id: Option<String>,
initialized: bool,
@@ -136,79 +144,126 @@ impl ClickhousePool {
database: database.into(),
settings,
read_only: source.read_only,
session: Mutex::new(Session {
id: use_http_session.then(|| uuid::Uuid::new_v4().to_string()),
..Session::default()
}),
connect_timeout: timeout,
startup_statements: setup.statements,
use_http_session,
session: Mutex::new(None),
console_sessions: parking_lot::Mutex::new(HashMap::new()),
closed: CancellationToken::new(),
}));
let cancel = CancellationToken::new();
let initialize = async {
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
let Some(setting) = rejected_driver_setting(&error) else {
return Err(error);
};
if !use_http_session {
if setting == "readonly" {
return Err(error);
}
if !source.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
pool.0.session.lock().await.strict_read_only = true;
pool.execute("SELECT 1", 1, &cancel).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session.
{
let mut session = pool.0.session.lock().await;
// The rejected probe may have opened a session on a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
}
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
}
}
// The HTTP database parameter applies to one request. A named session needs
// USE once so later queries inherit the selection (and may change it).
if use_http_session && !database.is_empty() {
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, database);
pool.execute(&format!("USE {name}"), 0, &cancel).await?;
}
for sql in setup.statements {
pool.execute(&sql, 0, &cancel).await?;
}
Ok(pool.clone())
if let Err(error) = pool.session(&pool.0.session, &cancel).await {
pool.close();
return Err(error);
}
Ok(pool)
}
async fn session<'a>(
&self,
slot: &'a SessionSlot,
cancel: &CancellationToken,
) -> IdeResult<MutexGuard<'a, Option<Session>>> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
session = slot.lock() => session,
};
tokio::pin!(initialize);
tokio::select! {
result = &mut initialize => {
if result.is_err() {
pool.close();
if slot.is_none() {
let mut session =
Session { id: self.0.use_http_session.then(|| uuid::Uuid::new_v4().to_string()), ..Session::default() };
{
let cancel = cancel.child_token();
let initialize = self.initialize(&mut session, &cancel);
tokio::pin!(initialize);
tokio::select! {
result = &mut initialize => result?,
() = tokio::time::sleep(self.0.connect_timeout) => {
cancel.cancel();
let _ = initialize.await;
return Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"));
}
}
}
*slot = Some(session);
}
Ok(slot)
}
async fn initialize(&self, session: &mut Session, cancel: &CancellationToken) -> IdeResult<()> {
if let Err(error) = self.execute_request("SELECT 1", 0, 1, cancel, session).await {
let Some(setting) = rejected_driver_setting(&error) else {
return Err(error);
};
if session.id.is_none() {
if setting == "readonly" {
return Err(error);
}
if !self.0.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
session.strict_read_only = true;
self.execute_request("SELECT 1", 0, 1, cancel, session).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session. The rejected probe may have used a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
let result = self.execute_request("SELECT getSetting('readonly')", 0, 1, cancel, session).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
result
},
() = tokio::time::sleep(timeout) => {
cancel.cancel();
let _ = initialize.await;
pool.close();
Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"))
}
}
// A named session needs USE once so later queries inherit the database and may change it.
if session.id.is_some() && !self.0.database.is_empty() {
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, &self.0.database);
self.execute_request(&format!("USE {name}"), 0, 0, cancel, session).await?;
}
for sql in &self.0.startup_statements {
if transaction_statement(sql) {
return Err(transaction_error());
}
self.execute_request(sql, 0, 0, cancel, session).await?;
}
Ok(())
}
pub async fn ping(&self) -> IdeResult<()> {
let cancel = CancellationToken::new();
if !self.0.use_http_session {
return self.execute("SELECT 1", 1, &cancel).await.map(|_| ());
}
let mut result = Ok(());
let consoles = self.0.console_sessions.lock().values().cloned().collect::<Vec<_>>();
let sessions = std::iter::once(&self.0.session).chain(consoles.iter().map(Arc::as_ref));
for slot in sessions {
// A running query already keeps its session active.
if let Ok(mut slot) = slot.try_lock()
&& let Some(session) = slot.as_mut()
&& let Err(error) = self.execute_request("SELECT 1", 0, 1, &cancel, session).await
{
result = result.and(Err(error));
}
}
result
}
pub fn release_console(&self, console: ConsoleId<'_>) {
self.0.console_sessions.lock().remove(&(console.window.into(), console.path.into()));
}
pub fn close(&self) {
self.0.closed.cancel();
self.0.console_sessions.lock().clear();
self.0.client.write().take();
}
@@ -261,19 +316,51 @@ impl ClickhousePool {
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
self.execute_in_console(sql, skip, max_rows, cancel, None).await
}
pub async fn execute_in_console(
&self,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
if transaction_statement(sql) {
return Err(transaction_error());
}
let mut session = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
session = self.0.session.lock() => session,
};
let console_slot = console.filter(|_| self.0.use_http_session).map(|console| {
self.0.console_sessions.lock().entry((console.window.into(), console.path.into())).or_default().clone()
});
let slot = console_slot.as_deref().unwrap_or(&self.0.session);
let mut session = self.session(slot, cancel).await?;
let state = session.as_mut().expect("session was initialized");
if self.0.use_http_session {
self.execute_request(sql, skip, max_rows, cancel, state).await
} else {
// Stateless requests use the setup's read-only flags, and have no server session to lock.
let mut request = state.clone();
drop(session);
self.execute_request(sql, skip, max_rows, cancel, &mut request).await
}
}
async fn execute_request(
&self,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
session: &mut Session,
) -> IdeResult<QueryResult> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let client = self.client()?;
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
let started = Instant::now();
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
@@ -333,7 +420,7 @@ impl ClickhousePool {
result
}
None => {
let killed = self.kill(&client, &query_id, &session).await;
let killed = self.kill(&client, &query_id, session).await;
match killed {
Ok(()) => Err(IdeError::cancelled()),
Err(error) => Err(IdeError::new(
@@ -1151,6 +1238,69 @@ mod tests {
requests.await.unwrap();
}
#[tokio::test]
async fn console_sessions_have_distinct_http_ids() {
let (port, requests) = server(vec![("200 OK", "", ONE); 8]).await;
let Pool::Clickhouse(pool) = Pool::connect(&source(port), None, None).await.unwrap() else { unreachable!() };
let first = ConsoleId { window: "main", path: "console.sql" };
let second = ConsoleId { window: "main", path: "console_1.sql" };
let cancel = CancellationToken::new();
for console in [first, second, first] {
pool.execute_in_console("SELECT 2", 0, 1, &cancel, Some(console)).await.unwrap();
}
pool.release_console(second);
pool.ping().await.unwrap();
let requests = requests.await.unwrap();
let ids = requests
.iter()
.map(|request| query_value(&request_url(request), "session_id").unwrap())
.collect::<Vec<_>>();
assert_ne!(ids[0], ids[1]);
assert_ne!(ids[1], ids[3]);
assert_eq!(ids[1], ids[2]);
assert_eq!(ids[3], ids[4]);
assert_eq!(ids[1], ids[5]);
assert_eq!(ids[0], ids[6]);
assert_eq!(ids[1], ids[7]);
}
#[tokio::test]
async fn stateless_queries_do_not_wait_for_a_shared_session() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
let (mut first, _) = listener.accept().await.unwrap();
let first_request = read_request(&mut first).await;
started.send(()).unwrap();
let (mut second, _) = listener.accept().await.unwrap();
let second_request = read_request(&mut second).await;
reply(&mut second, "200 OK", "", ONE).await;
reply(&mut first, "200 OK", "", ONE).await;
(first_request, second_request)
});
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
let first = pool.execute("SELECT 1", 1, &cancel);
let second = async {
received.await.unwrap();
pool.execute("SELECT 2", 1, &cancel).await
};
let (first, second) = tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(first, second) })
.await
.expect("both requests should reach the server");
first.unwrap();
second.unwrap();
let (first, second) = server.await.unwrap();
for request in [first, second] {
assert_eq!(query_value(&request_url(&request), "session_id"), None);
}
}
#[tokio::test]
async fn cancellation_sends_kill_outside_the_busy_session() {
for stateless in [false, true] {
+1
Переглянути файл
@@ -1000,6 +1000,7 @@ impl Pool {
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
Pool::Clickhouse(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
+62 -7
Переглянути файл
@@ -336,6 +336,13 @@ pub struct DbManager {
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
/// A SQL editor's connection identity within the owning project's lifetime.
#[derive(Clone, Copy)]
pub struct ConsoleId<'a> {
pub window: &'a str,
pub path: &'a str,
}
const MAX_META_ROWS: usize = 100_000;
/// Completion columns of the default schema, which are read without the shared cap.
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
@@ -1632,7 +1639,22 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, skip, max_rows, cancel, schema).await;
self.execute_in_console(id, statement, skip, max_rows, cancel, schema, None).await
}
/// Executes with the originating editor's named HTTP session when supported by the driver.
#[allow(clippy::too_many_arguments)]
pub async fn execute_in_console(
&self,
id: &str,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, skip, max_rows, cancel, schema, console).await;
let ran = match &r {
Ok(_) => true,
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
@@ -1654,7 +1676,19 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, false).await
self.read_console_row(id, statement, row, cancel, schema, None).await
}
pub async fn read_console_row(
&self,
id: &str,
statement: &str,
row: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, console, false).await
}
/// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed).
@@ -1691,6 +1725,17 @@ impl DbManager {
statement: &str,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<Vec<PlanNode>> {
self.explain_in_console(id, statement, cancel, schema, None).await
}
pub async fn explain_in_console(
&self,
id: &str,
statement: &str,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<Vec<PlanNode>> {
let driver = self.pool(id).await?.driver();
if driver == DbDriver::Jdbc {
@@ -1713,18 +1758,21 @@ impl DbManager {
MAX_META_ROWS,
cancel,
schema,
None,
)
.await?;
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None).await?;
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None, None).await?;
let nodes = plan::parse(driver, &result);
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None).await;
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
return nodes;
}
let result =
self.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema).await?;
let result = self
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
.await?;
plan::parse(driver, &result)
}
#[allow(clippy::too_many_arguments)]
async fn run(
&self,
id: &str,
@@ -1733,8 +1781,9 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
self.run_paged(id, statement, skip, max_rows, cancel, schema, console, true).await
}
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
@@ -1747,12 +1796,18 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
paging: bool,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
if let Pool::Jdbc(p) = &*pool {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
}
if let Pool::Clickhouse(p) = &*pool
&& console.is_some()
{
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
}
let session = self.sessions.lock().get(id).cloned();
let protected = pool.transaction_read_only();
let cursor = protected || conn::cursor_statement(statement);
+9
Переглянути файл
@@ -227,6 +227,15 @@ impl DbManager {
}
}
/// Retires a closed editor's named sessions without opening any data sources.
pub fn release_console(&self, console: crate::ConsoleId<'_>) {
for connection in self.pools.lock().values().filter_map(|slot| slot.value.get()) {
if let Pool::Clickhouse(pool) = &*connection.pool {
pool.release_console(console);
}
}
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
+91 -1
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -134,3 +134,93 @@ async fn clickhouse_cloud_manager_catalogs_and_session_table() -> IdeResult<()>
cleanup?;
Ok(())
}
#[tokio::test]
#[ignore = "requires a disposable loopback ClickHouse console fixture"]
async fn clickhouse_named_console_sessions_run_concurrently_and_preserve_state() -> IdeResult<()> {
use std::time::Duration;
let port = std::env::var("CLICKHOUSE_CONSOLE_TEST_PORT")
.expect("set the disposable loopback console fixture's port")
.parse()
.expect("numeric console fixture port");
let password = std::env::var("CLICKHOUSE_CONSOLE_TEST_PASSWORD").expect("set the console fixture password");
let tmp = tempfile::tempdir()?;
let root = tmp.path().to_path_buf();
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
let source = DataSource {
id: "clickhouse".into(),
name: "ClickHouse console fixture".into(),
driver: DbDriver::Clickhouse,
host: "127.0.0.1".into(),
port: Some(port),
user: "console_fixture".into(),
database: "default".into(),
..Default::default()
};
let observer = DataSource { id: "observer".into(), ..source.clone() };
db.save_sources(vec![source, observer]).await?;
for id in ["clickhouse", "observer"] {
db.set_password(id, Some(password.clone()), false).await?;
db.execute(id, "SELECT 1", 1, &CancellationToken::new()).await?;
}
let a = ConsoleId { window: "window-a", path: "/console.sql" };
let b = ConsoleId { window: "window-a", path: "/console_1.sql" };
let other_window = ConsoleId { window: "window-b", path: "/console.sql" };
let idle = CancellationToken::new();
let run = |console, sql, cancel| db.execute_in_console("clickhouse", sql, 0, 1, cancel, None, Some(console));
run(b, "SELECT 1", &idle).await?;
run(a, "SET max_threads = 2", &idle).await?;
run(a, "CREATE TEMPORARY TABLE console_state (id UInt8)", &idle).await?;
run(a, "INSERT INTO console_state VALUES (17)", &idle).await?;
let cancel = CancellationToken::new();
let long_sql = "SELECT sum(sleepEachRow(1)) FROM numbers(12) SETTINGS max_block_size=1";
let running = run(a, long_sql, &cancel);
let other = async {
let checked = tokio::time::timeout(Duration::from_secs(4), async {
loop {
let observed = db
.execute(
"observer",
"SELECT count() FROM system.processes WHERE startsWith(query, 'SELECT sum(sleepEachRow(1))')",
1,
&idle,
)
.await?;
if observed.rows[0][0].as_deref() == Some("1") {
break;
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
run(b, "SELECT 2", &idle).await
})
.await;
cancel.cancel();
checked.map_err(|_| IdeError::invalid("console B did not complete while console A was active"))?
};
let (cancelled, other) = tokio::time::timeout(Duration::from_secs(17), async { tokio::join!(running, other) })
.await
.expect("console queries and cancellation should drain");
assert_eq!(other?.rows, vec![vec![Some("2".into())]]);
assert_eq!(cancelled.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
let first = run(a, "SELECT getSetting('max_threads'), id FROM console_state", &idle).await?;
assert_eq!(first.rows, vec![vec![Some("2".into()), Some("17".into())]]);
for console in [b, other_window] {
let second = run(console, "SELECT id FROM console_state", &idle).await;
assert!(second.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
}
run(b, "CREATE TEMPORARY TABLE console_state (id UInt8)", &idle).await?;
db.release_console(a);
let reopened = run(a, "SELECT id FROM console_state", &idle).await;
assert!(reopened.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
assert!(run(b, "SELECT id FROM console_state", &idle).await?.rows.is_empty());
db.disconnect_source("clickhouse").await;
let reset = run(b, "SELECT id FROM console_state", &idle).await;
assert!(reset.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
Ok(())
}
+77 -23
Переглянути файл
@@ -5,11 +5,11 @@
use super::Channel;
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::{
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -348,6 +348,18 @@ pub async fn db_object_ddl(
db.object_ddl(&id, &schema, kind, &name).await
}
fn console_request<'a>(
host: &Host,
window: &'a str,
request: RequestId,
path: Option<&'a str>,
) -> (CancellationToken, Option<ConsoleId<'a>>) {
match path {
Some(path) => (host.begin_project_request(window, request), Some(ConsoleId { window, path })),
None => (host.begin_request(request), None),
}
}
#[command(trust = trusted)]
pub async fn db_explain(
host: &Host,
@@ -356,11 +368,12 @@ pub async fn db_explain(
id: String,
statement: String,
schema: Option<String>,
#[default] console: Option<String>,
) -> IdeResult<Vec<PlanNode>> {
// Explain Plan: the execution plan of `statement` on `id`, without running it.
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let result = db.explain(&id, &statement, &cancel, schema.as_deref()).await;
let (cancel, console) = console_request(host, window, request, console.as_deref());
let result = db.explain_in_console(&id, &statement, &cancel, schema.as_deref(), console).await;
host.end_request(request);
result
}
@@ -418,21 +431,33 @@ pub async fn db_execute(
schema: Option<String>,
// Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole.
#[default] cell_limit: Option<u32>,
#[default] console: Option<String>,
) -> IdeResult<Vec<StatementOutcome>> {
let mut outcomes = Vec::new();
let limits = Limits { skip, max_rows, cell_limit };
execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
if let ExecutionEvent::Completed { outcome, .. } = event {
outcomes.push(outcome);
}
Ok(())
})
execute_statements(
host,
window,
request,
&id,
statements,
limits,
schema.as_deref(),
console.as_deref(),
|event| {
if let ExecutionEvent::Completed { outcome, .. } = event {
outcomes.push(outcome);
}
Ok(())
},
)
.await?;
Ok(outcomes)
}
/// Row `row` (from 0) of the result of `statement`, whole: what a page of a run with a
/// `cell_limit` shows cut short.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn db_result_row(
host: &Host,
@@ -442,10 +467,11 @@ pub async fn db_result_row(
statement: SqlStatement,
row: u32,
schema: Option<String>,
#[default] console: Option<String>,
) -> IdeResult<QueryResult> {
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let result = db.read_row(&id, &statement.text, row as usize, &cancel, schema.as_deref()).await;
let (cancel, console) = console_request(host, window, request, console.as_deref());
let result = db.read_console_row(&id, &statement.text, row as usize, &cancel, schema.as_deref(), console).await;
host.end_request(request);
result
}
@@ -463,6 +489,12 @@ pub fn db_release_result(
Ok(())
}
#[command(trust = trusted)]
pub fn db_release_console(host: &Host, window: &str, console: String) -> IdeResult<()> {
host.project(window)?.db.release_console(ConsoleId { window, path: &console });
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn db_execute_stream(
@@ -475,11 +507,20 @@ pub async fn db_execute_stream(
schema: Option<String>,
#[default] cell_limit: Option<u32>,
on_progress: Channel<ExecutionEvent>,
#[default] console: Option<String>,
) -> IdeResult<()> {
let limits = Limits { skip: 0, max_rows, cell_limit };
let result = execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
on_progress.send(event)
})
let result = execute_statements(
host,
window,
request,
&id,
statements,
limits,
schema.as_deref(),
console.as_deref(),
|event| on_progress.send(event),
)
.await;
// The invocation reply can reach the viewer before a large result frame.
on_progress.send(ExecutionEvent::Done { error: result.err() })
@@ -503,10 +544,11 @@ async fn execute_statements(
statements: Vec<SqlStatement>,
Limits { skip, max_rows, cell_limit }: Limits,
schema: Option<&str>,
console: Option<&str>,
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
) -> IdeResult<()> {
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let (cancel, console) = console_request(host, window, request, console);
let result = async {
db.validate_script(id, &statements).await?;
for (index, statement) in statements.into_iter().enumerate() {
@@ -515,7 +557,15 @@ async fn execute_statements(
}
emit(ExecutionEvent::Started { index: index as u32 })?;
let outcome = match db
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
.execute_in_console(
id,
&statement.text,
skip as usize,
max_rows.max(1) as usize,
&cancel,
schema,
console,
)
.await
{
Ok(mut result) => {
@@ -713,6 +763,7 @@ ide_command::domain!(
db_remove_jdbc_driver,
db_object_ddl,
db_release_result,
db_release_console,
db_result_row,
db_remove_history,
db_retain_catalog,
@@ -782,6 +833,7 @@ mod tests {
statements,
Limits { skip: 0, max_rows: 10, cell_limit: None },
None,
None,
|event| match event {
ExecutionEvent::Started { index: 0 } => Ok(()),
ExecutionEvent::Completed { index: 0, outcome } => {
@@ -803,7 +855,8 @@ mod tests {
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
DbDriver::Sqlite,
);
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None).await.unwrap();
let outcomes =
db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None, None).await.unwrap();
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
}
@@ -819,10 +872,11 @@ mod tests {
),
DbDriver::Sqlite,
);
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None).await.unwrap();
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None, None).await.unwrap();
let query = || ide_db::split::split("SELECT n, body FROM docs ORDER BY n", DbDriver::Sqlite);
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100)).await.unwrap();
let capped =
db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100), None).await.unwrap();
let page = capped[0].result.as_ref().unwrap();
// The page no longer carries more than the limit of each cell.
let size: usize = page.rows.iter().flatten().flatten().map(String::len).sum();
@@ -843,7 +897,7 @@ mod tests {
// The row of a cut cell, read alone and without a limit, is the whole value.
for row in [1, 2] {
let statement = query().remove(0);
let one = db_result_row(&host, window, RequestId(3), id.into(), statement, row, None).await.unwrap();
let one = db_result_row(&host, window, RequestId(3), id.into(), statement, row, None, None).await.unwrap();
assert!(one.truncated.is_empty());
let full = one.rows[0][1].clone().unwrap();
assert_eq!(full.encode_utf16().count(), whole as usize);
@@ -851,7 +905,7 @@ mod tests {
}
// Without a limit nothing is cut or listed.
let all = db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None).await.unwrap();
let all = db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None, None).await.unwrap();
let all = all[0].result.as_ref().unwrap();
assert!(all.truncated.is_empty());
assert_eq!(all.rows[2][1].as_deref(), Some(wide.as_str()));
+3 -6
Переглянути файл
@@ -7,15 +7,12 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
const todoModule = "/src/features/todo/store.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { useTodos } = await import(/* @vite-ignore */ todoModule);
const { setLiveTodos } = await import(/* @vite-ignore */ todoModule);
const { showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const directory = "src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing";
const path = `${useProject.getState().project.root}/${directory}/orders.ts`;
useTodos.setState({
scannedOnce: true,
error: null,
scanned: new Map([[path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]]]),
});
// The browser's startup scan clears the scan cache.
setLiveTodos(path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]);
showToolWindow("todo", true);
});
+1
Переглянути файл
@@ -131,6 +131,7 @@ db_history trusted project_host bin
db_jdbc_driver_classes trusted project_host bindings async
db_jdbc_drivers trusted project_host bindings sync
db_object_ddl trusted project_host bindings async
db_release_console trusted project_host bindings sync
db_release_result trusted project_host bindings sync
db_remove_history trusted project_host bindings async
db_remove_jdbc_driver trusted project_host bindings sync
+5 -4
Переглянути файл
@@ -368,9 +368,9 @@ export const commands = {
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null, cellLimit: number | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema, cellLimit })),
dbExecuteStream: (request: RequestId, id: string, statements: SqlStatement[], maxRows: number, schema: string | null, cellLimit: number | null, onProgress: Channel<ExecutionEvent>) => typedError<null, IdeError>(__TAURI_INVOKE("db_execute_stream", { request, id, statements, maxRows, schema, cellLimit, onProgress })),
dbExplain: (request: RequestId, id: string, statement: string, schema: string | null) => typedError<DbPlanNode[], IdeError>(__TAURI_INVOKE("db_explain", { request, id, statement, schema })),
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null, cellLimit: number | null, console: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema, cellLimit, console })),
dbExecuteStream: (request: RequestId, id: string, statements: SqlStatement[], maxRows: number, schema: string | null, cellLimit: number | null, onProgress: Channel<ExecutionEvent>, console: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("db_execute_stream", { request, id, statements, maxRows, schema, cellLimit, onProgress, console })),
dbExplain: (request: RequestId, id: string, statement: string, schema: string | null, console: string | null) => typedError<DbPlanNode[], IdeError>(__TAURI_INVOKE("db_explain", { request, id, statement, schema, console })),
/**
* Writes exported result data (CSV, JSON, SQL…) to `path`. Stays in the
* desktop shell: the path comes from a local save dialog, and a remote
@@ -382,6 +382,7 @@ export const commands = {
dbJdbcDriverClasses: (jars: string[]) => typedError<string[], IdeError>(__TAURI_INVOKE("db_jdbc_driver_classes", { jars })),
dbJdbcDrivers: () => typedError<DbJdbcDriver_Serialize[], IdeError>(__TAURI_INVOKE("db_jdbc_drivers")),
dbObjectDdl: (id: string, schema: string, kind: DbObjectKind, name: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_object_ddl", { id, schema, kind, name })),
dbReleaseConsole: (console: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_release_console", { console })),
/** Closes what the pages of a result keep open on the server (its result tab was closed). */
dbReleaseResult: (id: string, statement: string, schema: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("db_release_result", { id, statement, schema })),
dbRemoveHistory: (id: string, texts: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("db_remove_history", { id, texts })),
@@ -390,7 +391,7 @@ export const commands = {
* Row `row` (from 0) of the result of `statement`, whole: what a page of a run with a
* `cell_limit` shows cut short.
*/
dbResultRow: (request: RequestId, id: string, statement: SqlStatement, row: number, schema: string | null) => typedError<DbQueryResult, IdeError>(__TAURI_INVOKE("db_result_row", { request, id, statement, row, schema })),
dbResultRow: (request: RequestId, id: string, statement: SqlStatement, row: number, schema: string | null, console: string | null) => typedError<DbQueryResult, IdeError>(__TAURI_INVOKE("db_result_row", { request, id, statement, row, schema, console })),
dbRetainCatalog: (id: string, databases: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("db_retain_catalog", { id, databases })),
/**
* Runs `job` against target `id` and streams the tool's output; returns its exit code. Stays
+2 -2
Переглянути файл
@@ -133,7 +133,7 @@ describe("cut cells", () => {
const [full] = await loadCells(tab, [{ row: 1, col: 1 }]);
expect(full).toBe(whole);
// Page 2 of 10 rows: the second row of the page is row 21 of the result.
expect(backend.resultRow).toHaveBeenCalledWith(expect.any(Number), "pg", tab.outcome.statement, 21, "public");
expect(backend.resultRow).toHaveBeenCalledWith(expect.any(Number), "pg", tab.outcome.statement, 21, "public", null);
expect(cellOf(r, 1, 1)).toBe(whole);
expect(cutLength(r, 1, 1)).toBeNull();
expect(hasCutCells(r)).toBe(false);
@@ -218,7 +218,7 @@ describe("cut cells", () => {
expect(backend.resultRow).not.toHaveBeenCalled();
expect(backend.execute).toHaveBeenCalledTimes(1);
// The page is read whole (no cell limit) from its own first row.
expect(backend.execute.mock.calls[0]!.slice(3)).toEqual([20, 12, "public", null]);
expect(backend.execute.mock.calls[0]!.slice(3)).toEqual([20, 12, "public", null, null]);
expect(hasCutCells(r)).toBe(false);
});
});
+2 -2
Переглянути файл
@@ -2,9 +2,9 @@ import type { commands } from "@/platform/ipc";
/** Lets tests share their fixtures for batched and single execution. */
export function streamExecution(execute: typeof commands.dbExecute): typeof commands.dbExecuteStream {
return async (request, id, statements, maxRows, schema, cellLimit, channel) => {
return async (request, id, statements, maxRows, schema, cellLimit, channel, console) => {
channel.onmessage({ type: "started", index: 0 });
const reply = await execute(request, id, statements, 0, maxRows, schema, cellLimit);
const reply = await execute(request, id, statements, 0, maxRows, schema, cellLimit, console);
if (reply.status === "error") channel.onmessage({ type: "done", error: reply.error });
else {
reply.data.forEach((outcome, index) => {
+2
Переглянути файл
@@ -60,6 +60,7 @@ import {
openHistory,
openSourceDialog,
useDatabase,
watchClickhouseConsoles,
watchIdleConnections,
} from "./store";
@@ -284,6 +285,7 @@ export function activate(): () => void {
setFileDecorations("database", consoleDecorations(s));
}),
() => setFileDecorations("database", new Map()),
watchClickhouseConsoles(),
watchIdleConnections(),
installTableEditorFocus(),
installValueEditorActions(),
+82
Переглянути файл
@@ -17,15 +17,23 @@ import { ResultsView } from "./ResultsView";
import { streamExecution } from "./executeStream.fixture";
import {
cancelConsole,
closeResult,
countResult,
executeConsole,
explainConsole,
loadResultPage,
pinResult,
readResultPage,
readResultRow,
rerunResult,
runSql,
useDatabase,
watchClickhouseConsoles,
type ResultTab,
} from "./store";
import { registerResultTabActions } from "./resultTabActions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import * as contributions from "@/workbench/contributions";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({
@@ -34,6 +42,8 @@ const backend = vi.hoisted(() => ({
details: vi.fn(),
applyEdits: vi.fn(),
execute: vi.fn(),
resultRow: vi.fn(),
releaseConsole: vi.fn(),
stream: vi.fn(),
cancel: vi.fn(),
connected: vi.fn(),
@@ -51,6 +61,8 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
dbTableDetails: backend.details,
dbApplyEdits: backend.applyEdits,
dbExecute: backend.execute,
dbResultRow: backend.resultRow,
dbReleaseConsole: backend.releaseConsole,
dbExecuteStream: backend.stream,
cancelRequest: backend.cancel,
dbConnected: backend.connected,
@@ -1158,6 +1170,76 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
},
);
it("routes ClickHouse runs and result operations through the originating SQL editor", async () => {
const first = "/project/console.sql";
const second = "/project/console_1.sql";
useDatabase.setState({
sources: [{ id: "pg", name: "Local", driver: "clickhouse", readOnly: false }],
});
backend.resultRow.mockResolvedValue({ status: "ok", data: result([{ name: "v" }], [["1"]]) });
backend.explain.mockResolvedValue({ status: "ok", data: [] });
await runIn(first, "SELECT 1");
expect(backend.execute.mock.lastCall?.[7]).toBe(first);
await runIn(second, "SELECT 2");
expect(backend.execute.mock.lastCall?.[7]).toBe(second);
const firstResult = useDatabase.getState().results.find((tab) => tab.path === first)!;
await loadResultPage(firstResult.id, 1, 1);
expect(backend.execute.mock.lastCall?.[7]).toBe(first);
await countResult(firstResult.id);
expect(backend.execute.mock.lastCall?.[7]).toBe(first);
await readResultPage(firstResult);
expect(backend.execute.mock.lastCall?.[7]).toBe(first);
await readResultRow(firstResult, 1);
expect(backend.resultRow.mock.lastCall?.[5]).toBe(first);
await explainConsole(second, "SELECT 2", 0, 0);
expect(backend.explain.mock.lastCall?.[4]).toBe(second);
const plan = useDatabase.getState().results.find((tab) => !!tab.plan)!;
await rerunResult(plan.id);
expect(backend.explain.mock.lastCall?.[4]).toBe(second);
await runSql("pg", ["SELECT 3"]);
expect(backend.execute.mock.lastCall?.[7]).toBeNull();
let paths = [first, second];
let tabsChanged!: () => void;
let released!: () => void;
backend.releaseConsole.mockImplementationOnce(
() => new Promise((resolve) => (released = () => resolve({ status: "ok", data: null }))),
);
const editor = vi.spyOn(contributions, "maybeEditorService").mockReturnValue({
openPaths: () => paths,
onOpenTabsChange: (listener) => {
tabsChanged = listener;
return () => {};
},
} as contributions.EditorService);
const stopWatching = watchClickhouseConsoles();
try {
paths = [second];
tabsChanged();
expect(backend.releaseConsole).not.toHaveBeenCalled();
closeResult(firstResult.id);
expect(backend.releaseConsole).toHaveBeenCalledExactlyOnceWith(first);
paths = [first, second];
tabsChanged();
const before = backend.execute.mock.calls.length;
const reopened = runIn(first, "SELECT 4");
await vi.waitFor(() => expect(useDatabase.getState().running[first]).toBeDefined());
expect(backend.execute).toHaveBeenCalledTimes(before);
released();
await reopened;
expect(backend.execute.mock.lastCall?.[7]).toBe(first);
} finally {
released?.();
stopWatching();
editor.mockRestore();
}
});
it("never replaces the Query Plan from a run, and appends a new plan beside a pinned one", async () => {
backend.explain.mockResolvedValue({ status: "ok", data: [] });
await explainConsole("a.sql", "SELECT 1", 0, 0);
+83 -13
Переглянути файл
@@ -1257,6 +1257,8 @@ export async function revealOpened(): Promise<void> {
const completionLoads = new Map<string, { current: () => boolean; promise: Promise<DbCompletion | null> }>();
const preparingConsoles = new Map<string, RequestId>();
const clickhouseConsoles = new Set<string>();
const closingClickhouseConsoles = new Map<string, Promise<unknown>>();
const stopResultDelivery = new Map<RequestId, () => void>();
const incompleteResultDelivery = Symbol("incomplete SQL result delivery");
const streamingResultTabs = new Set<number>();
@@ -1292,6 +1294,8 @@ useProject.subscribe((state, previous) => {
sourceMutations.clear();
completionLoads.clear();
preparingConsoles.clear();
clickhouseConsoles.clear();
closingClickhouseConsoles.clear();
lastUsed.clear();
if (useDatabase.getState().pausedConsoleMetadata.size) useDatabase.setState({ pausedConsoleMetadata: new Set() });
});
@@ -1505,6 +1509,51 @@ async function syncDropped(id: string) {
log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`);
}
/** Keep a named session while its editor or an operation on its results can use it. */
export function watchClickhouseConsoles(): () => void {
const editor = maybeEditorService();
const release = () => {
const paths = editor?.openPaths?.();
if (!paths || !clickhouseConsoles.size) return;
const { results, inline } = useDatabase.getState();
const retained = new Set([...paths, ...results.map((tab) => tab.path), ...inline.map((tab) => tab.path)]);
for (const path of clickhouseConsoles) {
if (retained.has(path)) continue;
clickhouseConsoles.delete(path);
preparingConsoles.delete(path);
cancelConsole(path);
const closing = call(commands.dbReleaseConsole(path)).catch(() => {});
closingClickhouseConsoles.set(path, closing);
void closing.then(() => {
if (closingClickhouseConsoles.get(path) === closing) closingClickhouseConsoles.delete(path);
});
}
};
const offTabs = editor?.onOpenTabsChange?.(release);
const offResults = useDatabase.subscribe((state, previous) => {
if (state.results !== previous.results || state.inline !== previous.inline) release();
});
return () => {
offTabs?.();
offResults();
};
}
function withConsoleConnection<T>(id: string, path: string | undefined, op: (console: string | null) => Promise<T>) {
const current = databaseRequest(id);
return withConnection(id, async () => {
const console = sourceById(id)?.driver === "clickhouse" && path ? path : null;
if (console) {
// A reopened editor waits for the previous session's release before using the same path.
const closing = closingClickhouseConsoles.get(console);
if (closing) await closing;
if (!current()) throw new IpcError({ kind: "cancelled", message: tx("Cancelled") });
clickhouseConsoles.add(console);
}
return op(console);
});
}
async function run(
id: string,
statements: SqlStatement[],
@@ -1512,6 +1561,7 @@ async function run(
maxRows = useDatabase.getState().maxRows,
skip = 0,
schema?: string,
path?: string,
progress?: {
emit: (event: StatementProgress) => void;
current: () => boolean;
@@ -1524,11 +1574,11 @@ async function run(
// Only a query that is safe to run again has its cells cut: the whole value is read by running it again.
const driver = sourceById(id)?.driver ?? "sqlite";
const cellLimit = statements.every((s) => isReadOnlyQuery(s.text, driver)) ? CELL_LIMIT : null;
const outcomes = await withConnection(id, async () => {
const outcomes = await withConsoleConnection(id, path, async (console) => {
const execute = async () => {
progress?.emit({ type: "started", index: 0 });
const outcomes = await call(
commands.dbExecute(request, id, statements, skip, maxRows, schema || null, cellLimit),
commands.dbExecute(request, id, statements, skip, maxRows, schema || null, cellLimit, console),
).catch((error: unknown) => {
if (isCancelled(error)) progress?.onStatementCancelled();
throw error;
@@ -1568,7 +1618,9 @@ async function run(
});
try {
// Large channel frames can arrive after the reply. Bound only this delivery wait.
await call(commands.dbExecuteStream(request, id, statements, maxRows, schema || null, cellLimit, channel));
await call(
commands.dbExecuteStream(request, id, statements, maxRows, schema || null, cellLimit, channel, console),
);
acknowledged = true;
waitForDelivery();
const result = await done;
@@ -1861,7 +1913,7 @@ export async function executeConsole(
};
let outcomes: DbStatementOutcome[];
try {
outcomes = await run(id, statements, request, pageSize, 0, schema, {
outcomes = await run(id, statements, request, pageSize, 0, schema, path, {
emit,
current: ownsRun,
onStatementCancelled: () => {
@@ -2001,9 +2053,14 @@ function showPlan(path: string, id: string, statement: SqlStatement, plan: DbPla
showServiceView(RESULTS_VIEW, false);
}
async function explain(id: string, statement: SqlStatement, schema?: string): Promise<DbPlanNode[]> {
const plan = await withConnection(id, () =>
call(commands.dbExplain(nextRequestId(), id, statement.text, schema || null)),
async function explain(
id: string,
statement: SqlStatement,
schema: string | undefined,
path: string,
): Promise<DbPlanNode[]> {
const plan = await withConsoleConnection(id, path, (console) =>
call(commands.dbExplain(nextRequestId(), id, statement.text, schema || null, console)),
);
log("statement", `explain ${statement.text}`, `${schema || promptOf(id)}>`);
log("result", `${plan.length} plan node${plan.length === 1 ? "" : "s"}`);
@@ -2021,7 +2078,7 @@ export async function explainConsole(path: string, text: string, from: number, t
path,
id,
statement,
await explain(id, statement, useDatabase.getState().consoleSchemas[path] || undefined),
await explain(id, statement, useDatabase.getState().consoleSchemas[path] || undefined, path),
);
} catch (e) {
if (isCancelled(e)) return;
@@ -2069,7 +2126,7 @@ export async function rerunResult(tabId: number): Promise<void> {
patchResult(tabId, { busy: true });
try {
patchResult(tabId, {
plan: await explain(tab.sourceId, tab.outcome.statement, tab.schema ?? consoleSchema(tab.path)),
plan: await explain(tab.sourceId, tab.outcome.statement, tab.schema ?? consoleSchema(tab.path), tab.path),
busy: false,
});
} catch (e) {
@@ -2089,8 +2146,8 @@ export function pageable(tab: ResultTab): boolean {
/** Row `row` (from 0, over all pages) of result tab `tab`'s query, with its cells whole. */
export async function readResultRow(tab: ResultTab, row: number): Promise<DbQueryResult> {
const schema = tab.schema ?? consoleSchema(tab.path);
return withConnection(tab.sourceId, () =>
call(commands.dbResultRow(nextRequestId(), tab.sourceId, tab.outcome.statement, row, schema || null)),
return withConsoleConnection(tab.sourceId, tab.path, (console) =>
call(commands.dbResultRow(nextRequestId(), tab.sourceId, tab.outcome.statement, row, schema || null, console)),
);
}
@@ -2099,8 +2156,19 @@ export async function readResultPage(tab: ResultTab): Promise<DbQueryResult> {
const schema = tab.schema ?? consoleSchema(tab.path);
const rows = Math.max(tab.outcome.result?.rows.length ?? 0, 1);
const { skip } = pageFetch(tab.page ?? 0, tab.pageSize ?? rows);
const [outcome] = await withConnection(tab.sourceId, () =>
call(commands.dbExecute(nextRequestId(), tab.sourceId, [tab.outcome.statement], skip, rows, schema || null, null)),
const [outcome] = await withConsoleConnection(tab.sourceId, tab.path, (console) =>
call(
commands.dbExecute(
nextRequestId(),
tab.sourceId,
[tab.outcome.statement],
skip,
rows,
schema || null,
null,
console,
),
),
);
if (!outcome?.result) throw new Error(outcome?.error ?? "The statement returned no result");
return outcome.result;
@@ -2137,6 +2205,7 @@ export async function loadResultPage(tabId: number, page: number, pageSize: numb
maxRows,
skip,
tab.schema ?? consoleSchema(tab.path),
tab.path,
);
const r = outcome?.result;
if (r) {
@@ -2184,6 +2253,7 @@ export async function countResult(tabId: number): Promise<number | null> {
1,
0,
tab.schema ?? consoleSchema(tab.path),
tab.path,
);
const total = Number(outcome?.result?.rows[0]?.[0]);
const known = outcome?.error || !Number.isFinite(total) ? null : total;
+4 -2
Переглянути файл
@@ -111,20 +111,22 @@ describe("bookmarks in a notebook", () => {
const host = document.createElement("div");
document.body.appendChild(host);
const view = new EditorView({ doc: "a\nb\n", parent: host });
const cell = new EditorView({ doc: "x = 1\n", parent: host });
const handle = { view, ctx: { doc: 1, path: "/p/a.ts", language: "", uiMode: null, readOnly: false } };
_setActiveEditor(handle as TextEditorHandle);
try {
expect(caretLine()?.path).toBe("/p/a.ts");
const cell = new EditorView({ doc: "x = 1\n", parent: host });
cell.focus();
_setFocusedCellEditor(cell);
expect(caretLine()).toBeNull();
_setFocusedCellEditor(null);
expect(caretLine()?.path).toBe("/p/a.ts");
} finally {
_setFocusedCellEditor(null);
_setActiveEditor(null);
cell.destroy();
view.destroy();
view.dom.remove();
host.remove();
}
});
});
+5 -2
Переглянути файл
@@ -31,7 +31,8 @@ describe("remote invoke", () => {
async invoke(command: string, call: { cmd: string; args: string; onChannel: Channel<ChannelFrame> }) {
expect(command).toBe("remote_invoke");
expect(call.cmd).toBe("db_execute_stream");
const { onProgress } = JSON.parse(call.args) as { onProgress: { $channel: number } };
const { onProgress, console } = JSON.parse(call.args) as { onProgress: { $channel: number }; console: string };
expect(console).toBe("/remote/console.sql");
call.onChannel.onmessage({ id: onProgress.$channel, data: JSON.stringify(done) });
return "null";
},
@@ -46,7 +47,9 @@ describe("remote invoke", () => {
const progress = vi.fn();
const channel = new Channel<ExecutionEvent>(progress);
try {
expect(await call(commands.dbExecuteStream(1, "test-db", [], 10, null, null, channel))).toBeNull();
expect(
await call(commands.dbExecuteStream(1, "test-db", [], 10, null, null, channel, "/remote/console.sql")),
).toBeNull();
expect(unregisterCallback).toHaveBeenCalledExactlyOnceWith(channel.id);
expect(progress).toHaveBeenCalledExactlyOnceWith(done);
} finally {