From 644a2d5784100b1b20cff9076f3cd7bf4003a7dd Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:41:48 +0200 Subject: [PATCH] perf(db): page results without re-reading the skipped rows and cap the size of a cell (#5260) Every page re-ran the query and read and dropped all rows before it, and nothing capped a cell, so a page of wide values moved hundreds of MB to the UI. Paging forward now continues the statement's stream on its connection (SQLite, PostgreSQL, MySQL/MariaDB), bounded to one cursor per source and closed when its result tab closes, the source disconnects or a data-changing statement runs (also while a page is being read). Read-only queries cut cells to 8,192 UTF-16 units, marked truncated, and read the whole value when it is expanded, copied, edited or exported; a re-read is accepted only when the row count, uncut cells and each cut cell's length, prefix and hash still match. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- crates/ide-db/src/clickhouse.rs | 1 + crates/ide-db/src/conn.rs | 289 +++++++++-- crates/ide-db/src/conn/cursor.rs | 474 ++++++++++++++++++ crates/ide-db/src/jdbc/mod.rs | 1 + crates/ide-db/src/lib.rs | 57 ++- crates/ide-db/src/plan.rs | 1 + crates/ide-db/src/snowflake/mod.rs | 1 + crates/ide-db/tests/mysql.rs | 24 + crates/ide-db/tests/postgres.rs | 56 +++ crates/ide-host/src/ops/db.rs | 154 +++++- docs/en/guide/database.mdx | 3 +- docs/zh/guide/database.mdx | 3 +- src-tauri/tests/commands.snap | 2 + src/bindings.ts | 26 +- src/features/database/DataView.tsx | 133 +++-- src/features/database/Database.module.css | 17 + src/features/database/Grid.tsx | 45 +- src/features/database/ResultsView.tsx | 63 ++- src/features/database/cutCells.test.tsx | 289 +++++++++++ src/features/database/cutCells.ts | 133 +++++ src/features/database/database.test.ts | 1 + .../database/executeStream.fixture.ts | 4 +- .../database/inEditorResults.test.tsx | 63 +-- src/features/database/result-tabs.test.tsx | 1 + src/features/database/results-view.test.tsx | 189 +++---- src/features/database/store.ts | 60 ++- src/features/database/table-editor.test.tsx | 1 + src/platform/locales/text/en.json | 7 + src/platform/locales/text/zh.json | 7 + src/platform/remote.test.ts | 2 +- 30 files changed, 1851 insertions(+), 256 deletions(-) create mode 100644 crates/ide-db/src/conn/cursor.rs create mode 100644 src/features/database/cutCells.test.tsx create mode 100644 src/features/database/cutCells.ts diff --git a/crates/ide-db/src/clickhouse.rs b/crates/ide-db/src/clickhouse.rs index d1526af26e..550b1a419a 100644 --- a/crates/ide-db/src/clickhouse.rs +++ b/crates/ide-db/src/clickhouse.rs @@ -316,6 +316,7 @@ impl ClickhousePool { has_more, elapsed_ms: started.elapsed().as_secs_f64() * 1000.0, execution_ms, + truncated: Vec::new(), }) }; let result = tokio::select! { diff --git a/crates/ide-db/src/conn.rs b/crates/ide-db/src/conn.rs index 2d5a930c02..0845d400f4 100644 --- a/crates/ide-db/src/conn.rs +++ b/crates/ide-db/src/conn.rs @@ -48,6 +48,65 @@ pub struct QueryResult { pub elapsed_ms: f64, /// Until the server's first answer; the rest of `elapsed_ms` is fetching. pub execution_ms: f64, + /// Cells of `rows` cut short by [`QueryResult::cap_cells`], in row order. + pub truncated: Vec, +} + +/// A cell of a [`QueryResult`] whose text was cut to a prefix. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +#[serde(rename = "DbTruncatedCell")] +pub struct TruncatedCell { + pub row: u32, + pub column: u32, + /// Length of the whole value in UTF-16 code units (what a JavaScript string counts). + pub length: u32, + /// FNV-1a (32 bits) of the whole value's UTF-16 code units, each taken as one 16-bit step, + /// so a client that reads the value again can tell whether it is the one that was cut. + pub hash: u32, +} + +/// FNV-1a over UTF-16 code units, one step per unit (the same on the client: see `cutCells.ts`). +fn fnv1a_utf16(text: &str) -> u32 { + let mut hash: u32 = 0x811c_9dc5; + let mut pair = [0u16; 2]; + for ch in text.chars() { + for unit in ch.encode_utf16(&mut pair) { + hash = (hash ^ u32::from(*unit)).wrapping_mul(0x0100_0193); + } + } + hash +} + +impl QueryResult { + /// Cuts every cell longer than `limit` UTF-16 code units to its first `limit` (never inside a + /// surrogate pair) and lists it in `truncated`, so a page's size no longer depends on how + /// wide its values are. The full value is read again, one row at a time, when it is needed. + pub fn cap_cells(&mut self, limit: usize) { + for (r, row) in self.rows.iter_mut().enumerate() { + for (c, cell) in row.iter_mut().enumerate() { + let Some(text) = cell else { continue }; + // A UTF-16 length never exceeds the UTF-8 one. + if text.len() <= limit { + continue; + } + let mut units = 0; + let mut cut = text.len(); + for (at, ch) in text.char_indices() { + if units + ch.len_utf16() > limit && cut == text.len() { + cut = at; + } + units += ch.len_utf16(); + } + if units <= limit { + continue; + } + let hash = fnv1a_utf16(text); + text.truncate(cut); + self.truncated.push(TruncatedCell { row: r as u32, column: c as u32, length: units as u32, hash }); + } + } + } } /// Session context belongs to the physical connection, including across pool checkouts. @@ -486,6 +545,86 @@ fn result_columns(row: &R) -> Vec { .collect() } +/// How far a statement's stream has been read: the columns seen so far, and the row that +/// showed more were coming, which the next read starts with. +pub(crate) struct Reader { + columns: Vec, + carry: Option, +} + +impl Default for Reader { + fn default() -> Self { + Self { columns: Vec::new(), carry: None } + } +} + +#[cfg(test)] +thread_local! { + /// Rows pulled from statement streams on this thread (tests count what paging reads). + pub(crate) static ROWS_PULLED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Reads on from `stream`: past the next `skip` rows without decoding them, then keeping at +/// most `max` rows with their cells read as `mode`. `rows_affected` reads a command's count. +async fn drain( + stream: &mut S, + reader: &mut Reader, + skip: usize, + max: usize, + mode: Cells, + rows_affected: impl Fn(&D) -> u64, +) -> IdeResult +where + S: futures::Stream, sqlx::Error>> + Unpin, + R: Row, + usize: ColumnIndex, + String: sqlx::Type, + for<'r> String: Decode<'r, R::Database>, + for<'r> Vec: Decode<'r, R::Database>, +{ + let mut rows: Vec>> = Vec::new(); + let mut affected: Option = None; + let mut has_more = false; + let mut first: Option = None; + let mut to_skip = skip; + loop { + let item = match reader.carry.take() { + Some(row) => Ok(sqlx::Either::Right(row)), + None => match stream.next().await { + Some(item) => { + #[cfg(test)] + if matches!(item, Ok(sqlx::Either::Right(_))) { + ROWS_PULLED.with(|n| n.set(n.get() + 1)); + } + item + } + None => break, + }, + }; + first.get_or_insert_with(Instant::now); + match item { + Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + rows_affected(&done)), + Ok(sqlx::Either::Right(row)) => { + if reader.columns.is_empty() { + reader.columns = result_columns(&row); + } + if to_skip > 0 { + to_skip -= 1; + continue; + } + if rows.len() >= max { + reader.carry = Some(row); + has_more = true; + break; + } + rows.push((0..row.len()).map(|i| cell(&row, i, mode)).collect()); + } + Err(e) => return Err(db_err(e)), + } + } + Ok((reader.columns.clone(), rows, affected, has_more, first)) +} + /// Streams the results of `$sql` on executor `$exec`, reading past the first `$skip` /// rows without decoding them, then keeping at most `$max` rows with their cells read as `$mode`. macro_rules! fetch { @@ -493,44 +632,8 @@ macro_rules! fetch { fetch!($exec, $sql, 0usize, $max, $mode) }; ($exec:expr, $sql:expr, $skip:expr, $max:expr, $mode:expr) => {{ - use futures::StreamExt; let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec); - let mut columns: Vec = Vec::new(); - let mut rows: Vec>> = Vec::new(); - let mut affected: Option = None; - let mut has_more = false; - let mut failure = None; - let mut first: Option = None; - let mut to_skip: usize = $skip; - while let Some(item) = stream.next().await { - first.get_or_insert_with(Instant::now); - match item { - Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + done.rows_affected()), - Ok(sqlx::Either::Right(row)) => { - if columns.is_empty() { - columns = result_columns(&row); - } - if to_skip > 0 { - to_skip -= 1; - continue; - } - if rows.len() >= $max { - has_more = true; - break; - } - rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect()); - } - Err(e) => { - failure = Some(db_err(e)); - break; - } - } - } - drop(stream); - match failure { - Some(e) => Err(e), - None => Ok((columns, rows, affected, has_more, first)), - } + drain(&mut stream, &mut Reader::default(), $skip, $max, $mode, |done| done.rows_affected()).await }}; } @@ -586,6 +689,31 @@ macro_rules! backend_id { }}; } +mod cursor; +pub(crate) use cursor::{Cursors, Key as CursorKey}; + +/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that +/// leaves the session as it was. +pub(crate) fn cursor_statement(sql: &str) -> bool { + looks_like_query(sql) && !context_may_change(sql) +} + +/// A [`QueryResult`] of what `fetched` read of `sql`, run since `started`. +pub(crate) fn query_result(sql: &str, fetched: Fetched, started: Instant) -> QueryResult { + let (columns, rows, affected, has_more, first) = fetched; + let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0; + QueryResult { + statement: sql.to_owned(), + affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None }, + columns, + rows, + has_more, + elapsed_ms, + execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0), + truncated: Vec::new(), + } +} + // Session control, scripts and PostgreSQL set_config can invalidate the tracked context. fn context_may_change(sql: &str) -> bool { let text = sql.trim().trim_end_matches(';'); @@ -985,6 +1113,12 @@ impl Pool { } } + /// Whether a later page of a result can be read from a cursor instead of by running the statement + /// again: the drivers whose rows stream from one connection that can wait for the next page. + pub(crate) fn keeps_cursors(&self) -> bool { + matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_)) + } + /// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]). pub async fn rows(&self, sql: &str, max: usize) -> IdeResult>>> { if let Pool::Jdbc(p) = self { @@ -1403,17 +1537,7 @@ impl Held { Held::Clickhouse(_) | Held::Snowflake(..) => unreachable!(), }; self.after_statement(sql); - let (columns, rows, affected, has_more, first) = fetched; - let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0; - Ok(QueryResult { - statement: sql.to_owned(), - affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None }, - columns, - rows, - has_more, - elapsed_ms, - execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0), - }) + Ok(query_result(sql, fetched, started)) } } @@ -1439,6 +1563,75 @@ mod tests { use super::*; use crate::source::{DbOptions, DbProperty}; + fn rows(cells: Vec>>) -> QueryResult { + query_result("select", (Vec::new(), cells, None, false, None), Instant::now()) + } + + #[test] + fn capping_cells_bounds_a_page_and_reports_the_whole_length() { + let wide = "x".repeat(1_000_000); + let mut r = rows(vec![vec![Some("short".into()), Some(wide.clone()), None], vec![Some(wide), None, None]]); + r.cap_cells(100); + let size: usize = r.rows.iter().flatten().flatten().map(String::len).sum(); + assert_eq!(size, 5 + 100 + 100); + assert_eq!( + r.truncated, + [ + TruncatedCell { row: 0, column: 1, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) }, + TruncatedCell { row: 1, column: 0, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) } + ] + ); + assert_eq!(r.rows[0][0].as_deref(), Some("short")); + assert_eq!(r.rows[0][2], None); + } + + #[test] + fn a_cut_cell_is_hashed_by_its_utf16_units() { + // Fixed values: the client (`cutCells.ts`) computes the same hash to recognise a value it reads again. + assert_eq!(fnv1a_utf16(""), 2_166_136_261); + assert_eq!(fnv1a_utf16("a"), 3_826_002_220); + assert_eq!(fnv1a_utf16("a😀b"), 2_412_414_209); + assert_eq!(fnv1a_utf16("日本語日本語"), 2_778_669_755); + assert_ne!(fnv1a_utf16(&"x".repeat(100)), fnv1a_utf16(&format!("{}y", "x".repeat(99)))); + let mut r = rows(vec![vec![Some("a😀b".into())]]); + r.cap_cells(2); + assert_eq!(r.truncated[0].hash, 2_412_414_209); + } + + #[test] + fn capping_cells_keeps_values_at_or_under_the_limit_whole() { + let mut r = rows(vec![vec![Some("abcd".into()), Some("😀😀".into()), Some("ééé".into())]]); + // 4 units, 4 units (two pairs), 3 units in 6 bytes. + r.cap_cells(4); + assert!(r.truncated.is_empty()); + assert_eq!(r.rows[0][1].as_deref(), Some("😀😀")); + r.cap_cells(3); + assert_eq!( + r.truncated, + [ + TruncatedCell { row: 0, column: 0, length: 4, hash: fnv1a_utf16("abcd") }, + TruncatedCell { row: 0, column: 1, length: 4, hash: fnv1a_utf16("😀😀") } + ] + ); + assert_eq!(r.rows[0][2].as_deref(), Some("ééé")); + } + + #[test] + fn capping_cells_never_splits_a_character_or_a_surrogate_pair() { + // "a😀b": units a=1, 😀=2, b=1. A cut inside the pair falls back to before it. + let mut r = rows(vec![vec![Some("a😀b".into()), Some("日本語日本語".into())]]); + r.cap_cells(2); + assert_eq!(r.rows[0][0].as_deref(), Some("a")); + assert_eq!(r.rows[0][1].as_deref(), Some("日本")); + assert_eq!(r.truncated[0].length, 4); + assert_eq!(r.truncated[1].length, 6); + // What is kept is a prefix of the whole value, measured in UTF-16 units. + for (cut, whole) in [(&r.rows[0][0], "a😀b"), (&r.rows[0][1], "日本語日本語")] { + assert!(whole.starts_with(cut.as_deref().unwrap())); + assert!(cut.as_deref().unwrap().encode_utf16().count() <= 2); + } + } + #[test] fn prefer_retries_without_tls_only_after_a_failed_handshake() { use std::io; diff --git a/crates/ide-db/src/conn/cursor.rs b/crates/ide-db/src/conn/cursor.rs new file mode 100644 index 0000000000..464bf4adf0 --- /dev/null +++ b/crates/ide-db/src/conn/cursor.rs @@ -0,0 +1,474 @@ +//! Result paging that reads on from where the previous page stopped. +//! +//! A statement has no way to start at row N: its server sends the rows before it, and a +//! page that re-runs the query reads and drops all of them. The page after another one +//! continues the same stream instead, so paging forward costs one page per click. +//! +//! A cursor keeps its statement's stream, and so its connection, open, which holds +//! server resources (locks, a snapshot) for as long as it lives. That is bounded: +//! one cursor per target, a few overall, each closed after [`IDLE`] without a page, when +//! its tab is closed or its target disconnects, and before a statement that is not a +//! query runs on its target. A page that finds no cursor at its position (jumping +//! to another page, going back, a closed cursor) starts a new one. + +use super::{Cells, Fetched, Held, Pool, Reader, drain, looks_like_query, statement_columns}; +use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; +use parking_lot::Mutex; +use sqlx::{Executor, SqlSafeStr}; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::{mpsc, oneshot}; + +/// How long a cursor waits for its next page. +const IDLE: Duration = Duration::from_secs(30); +/// Cursors kept at once, over all targets (each holds a connection). +const MAX_CURSORS: usize = 4; + +/// What a cursor reads the pages of: one statement of one target, in a schema context. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Key { + target: String, + statement: String, + schema: Option, +} + +impl Key { + pub(crate) fn new(target: &str, statement: &str, schema: Option<&str>) -> Self { + Self { + target: target.to_owned(), + statement: statement.to_owned(), + schema: schema.filter(|s| !s.is_empty()).map(str::to_owned), + } + } +} + +/// A request for the next rows of a cursor's statement. +struct Read { + skip: usize, + max: usize, + cancel: CancellationToken, + reply: oneshot::Sender>, +} + +/// A live cursor: where its stream stands, and the channel to the task that owns it. +struct Slot { + id: u64, + key: Key, + /// The number of rows read from the start of the statement (skipped or returned). + next: usize, + /// A page is being read from it: it stays registered meanwhile, so a release finds it. + busy: bool, + reads: mpsc::Sender, +} + +/// Reads `max` rows after the first `skip` of a cursor's stream through `reads`; `None` when the cursor is gone. +async fn read( + reads: &mpsc::Sender, + skip: usize, + max: usize, + cancel: &CancellationToken, +) -> Option> { + let (reply, answer) = oneshot::channel(); + reads.send(Read { skip, max, cancel: cancel.clone(), reply }).await.ok()?; + answer.await.ok() +} + +#[derive(Default)] +struct Registry { + /// Oldest first. + slots: Vec, + issued: u64, +} + +#[derive(Default)] +pub(crate) struct Cursors { + registry: Mutex, +} + +impl Cursors { + /// The page at `skip` read from the cursor of `key` that stands there; `None` when + /// there is none (the caller starts one) or it failed (a lost connection: the caller + /// runs the statement again and reports whatever that returns). + pub(crate) async fn resume( + &self, + key: &Key, + skip: usize, + max: usize, + cancel: &CancellationToken, + ) -> Option> { + let (id, reads) = { + let mut registry = self.registry.lock(); + let slot = registry + .slots + .iter_mut() + .find(|s| s.key == *key && s.next == skip && !s.busy && !s.reads.is_closed())?; + slot.busy = true; + (slot.id, slot.reads.clone()) + }; + match read(&reads, 0, max, cancel).await { + Some(Ok(fetched)) => { + self.finish(id, &fetched); + Some(Ok(fetched)) + } + Some(Err(e)) if e.kind == ErrorKind::Cancelled => { + self.close(id); + Some(Err(e)) + } + _ => { + self.close(id); + None + } + } + } + + /// Runs the statement of `key` on `held`, returns the page at `skip` and keeps the + /// statement's stream for the page after it. `held` is taken out of `pool` (its + /// context applied); `pool` stops the statement on the server when `cancel` fires. + pub(crate) async fn start( + &self, + held: Held, + pool: Arc, + key: Key, + skip: usize, + max: usize, + cancel: &CancellationToken, + ) -> IdeResult { + let (reads, requests) = mpsc::channel(1); + tokio::spawn(serve(held, pool, key.statement.clone(), requests)); + let id = self.register(key, skip, reads.clone()); + let fetched = match read(&reads, skip, max, cancel).await { + Some(Ok(fetched)) => fetched, + other => { + self.close(id); + return other.unwrap_or_else(|| Err(IdeError::internal("the statement stopped before it answered"))); + } + }; + self.finish(id, &fetched); + Ok(fetched) + } + + /// Registers a cursor that is reading its first page. A target keeps one cursor (its + /// connection pool is small), and all together are bounded. + fn register(&self, key: Key, next: usize, reads: mpsc::Sender) -> u64 { + let mut registry = self.registry.lock(); + registry.issued += 1; + let id = registry.issued; + registry.slots.retain(|s| s.key.target != key.target && !s.reads.is_closed()); + registry.slots.push(Slot { id, key, next, busy: true, reads }); + if registry.slots.len() > MAX_CURSORS { + registry.slots.remove(0); + } + id + } + + /// Ready for the page after `fetched`, which cursor `id` just read, when more rows are waiting in its + /// stream; closed otherwise. A cursor released meanwhile is gone from the registry: the caller's + /// handle on its channel is the last, so the statement stops. + fn finish(&self, id: u64, fetched: &Fetched) { + let mut registry = self.registry.lock(); + let Some(at) = registry.slots.iter().position(|s| s.id == id) else { return }; + if fetched.3 { + let slot = &mut registry.slots[at]; + slot.next += fetched.1.len(); + slot.busy = false; + } else { + registry.slots.remove(at); + } + } + + fn close(&self, id: u64) { + self.registry.lock().slots.retain(|s| s.id != id); + } + + /// Closes the cursor of one statement of `target` (its result tab was closed), also when it is reading a page. + pub(crate) fn release(&self, key: &Key) { + self.registry.lock().slots.retain(|s| s.key != *key); + } + + /// Closes the cursors of `target`: it disconnects, or a statement that changes + /// data or schema is about to run there. + pub(crate) fn release_target(&self, target: &str) { + self.registry.lock().slots.retain(|s| s.key.target != target); + } +} + +/// Owns `held` and the stream of `sql` on it, answering reads until the stream ends, +/// nobody asks for [`IDLE`], or it is released (its channel closes). +async fn serve(mut held: Held, pool: Arc, sql: String, mut reads: mpsc::Receiver) { + let Some(first) = reads.recv().await else { return held.discard().await }; + // `$id`: the query naming the server process, `$kill`: how another connection stops it. + // Evaluates to whether the connection can go back to its pool (the stream was read to + // its end); otherwise it is closed rather than left to be drained. + macro_rules! serve { + ($conn:expr, $id:expr, $kill:expr) => {{ + let backend = match $id { + Some(q) => backend_id!(&mut **$conn, q), + None => None, + }; + let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).fetch_many(&mut **$conn); + let mut reader = Reader::default(); + let mut request = Some(first); + let mut last = None; + let mut reusable = false; + while let Some(Read { skip, max, cancel, reply }) = request.take() { + let read = tokio::select! { + r = drain(&mut stream, &mut reader, skip, max, Cells::Display, |done| done.rows_affected()) => r, + () = cancel.cancelled() => Err(IdeError::cancelled()), + }; + if cancel.is_cancelled() { + if let Some(b) = backend { + let _ = pool.rows(&$kill(b), 1).await; + } + let _ = reply.send(Err(IdeError::cancelled())); + break; + } + match read { + Ok(fetched) if fetched.3 => { + if reply.send(Ok(fetched)).is_err() { + break; + } + request = tokio::time::timeout(IDLE, reads.recv()).await.unwrap_or(None); + } + Ok(fetched) => { + last = Some((reply, fetched)); + reusable = true; + break; + } + Err(e) => { + let _ = reply.send(Err(e)); + reusable = true; + break; + } + } + } + drop(stream); + if let Some((reply, mut fetched)) = last { + if fetched.0.is_empty() && looks_like_query(&sql) { + fetched.0 = (&mut **$conn) + .prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str()) + .await + .map(|s| statement_columns(&s)) + .unwrap_or_default(); + } + let _ = reply.send(Ok(fetched)); + } + reusable + }}; + } + let reusable = match &mut held { + Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()), + Held::Postgres(c) => { + serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})")) + } + Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")), + _ => unreachable!("only the sqlx drivers keep cursors"), + }; + if !reusable { + held.discard().await; + } +} + +#[cfg(test)] +mod tests { + use super::super::ROWS_PULLED; + use crate::{DataSource, DbDriver, DbManager}; + use ide_core::{CancellationToken, error::ErrorKind}; + + const PAGE: usize = 100; + const ROWS: usize = 1000; + + /// A SQLite data source `s1` with a table `t` of `ROWS` rows (`id` 1..=ROWS). + async fn manager() -> (tempfile::TempDir, DbManager) { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().to_path_buf(); + std::fs::File::create(root.join("app.db")).unwrap(); + let ssh = std::sync::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); + db.save_sources(vec![DataSource { + id: "s1".into(), + name: "app".into(), + driver: DbDriver::Sqlite, + file: Some("app.db".into()), + ..Default::default() + }]) + .await + .unwrap(); + let cancel = CancellationToken::new(); + db.execute("s1", "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)", 0, &cancel).await.unwrap(); + db.execute( + "s1", + &format!( + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {ROWS}) \ + INSERT INTO t SELECT i, 'row ' || i FROM n" + ), + 0, + &cancel, + ) + .await + .unwrap(); + (tmp, db) + } + + const QUERY: &str = "SELECT id, name FROM t ORDER BY id"; + + /// The ids of page `page` of `QUERY`, and whether more rows follow. + async fn page(db: &DbManager, statement: &str, page: usize) -> (Vec, bool) { + let r = db.execute_from("s1", statement, page * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap(); + (r.rows.iter().map(|row| row[0].as_deref().unwrap().parse().unwrap()).collect(), r.has_more) + } + + fn ids(page: usize) -> Vec { + ((page * PAGE + 1) as i64..=((page + 1) * PAGE) as i64).collect() + } + + fn pulled() -> u64 { + ROWS_PULLED.with(std::cell::Cell::get) + } + + #[tokio::test] + async fn paging_forward_reads_each_row_once() { + let (_tmp, db) = manager().await; + let before = pulled(); + for p in 0..ROWS / PAGE { + let (rows, has_more) = page(&db, QUERY, p).await; + assert_eq!(rows, ids(p), "page {p}"); + assert_eq!(has_more, p + 1 < ROWS / PAGE, "page {p} has_more"); + } + // Running the query again for every page reads 1+2+…+10 pages (5500 rows); one pass reads ~1000. + assert!(pulled() - before < 2 * ROWS as u64, "read {} rows", pulled() - before); + } + + #[tokio::test] + async fn jumping_and_going_back_return_the_right_pages() { + let (_tmp, db) = manager().await; + for p in [5, 6, 2, 3, 9, 0, 1, 7, 7, 8] { + assert_eq!(page(&db, QUERY, p).await.0, ids(p), "page {p}"); + } + } + + #[tokio::test] + async fn reading_a_row_leaves_the_cursor_of_the_pages_alone() { + let (_tmp, db) = manager().await; + page(&db, QUERY, 1).await; + let row = db.read_row("s1", QUERY, 350, &CancellationToken::new(), None).await.unwrap(); + assert_eq!(row.rows, [[Some("351".to_owned()), Some("row 351".to_owned())]]); + assert_eq!(db.cursors.registry.lock().slots.len(), 1); + // The next page still continues the cursor: it reads one page, not 200 rows again. + let before = pulled(); + assert_eq!(page(&db, QUERY, 2).await.0, ids(2)); + assert!(pulled() - before <= PAGE as u64 + 1, "read {} rows", pulled() - before); + } + + #[tokio::test] + async fn pages_past_the_end_are_empty() { + let (_tmp, db) = manager().await; + page(&db, QUERY, 8).await; + let r = db.execute_from("s1", QUERY, 2 * ROWS, PAGE, &CancellationToken::new(), None).await.unwrap(); + assert!(r.rows.is_empty() && !r.has_more); + // The columns of an empty page still come from the statement. + assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::>(), ["id", "name"]); + } + + #[tokio::test] + async fn another_statement_does_not_continue_a_cursor() { + let (_tmp, db) = manager().await; + page(&db, QUERY, 1).await; + let other = "SELECT id, name FROM t ORDER BY id DESC"; + let r = db.execute_from("s1", other, 2 * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap(); + let first: i64 = r.rows[0][0].as_deref().unwrap().parse().unwrap(); + assert_eq!(first, (ROWS - 2 * PAGE) as i64); + } + + #[tokio::test] + async fn a_statement_that_changes_data_closes_the_cursor() { + let (_tmp, db) = manager().await; + page(&db, QUERY, 1).await; + assert_eq!(db.cursors.registry.lock().slots.len(), 1); + db.execute("s1", "DELETE FROM t WHERE id = 150", 0, &CancellationToken::new()).await.unwrap(); + assert_eq!(db.cursors.registry.lock().slots.len(), 0); + // The next page shows the change: row 150 is gone, so page 2 starts at 202. + assert_eq!(page(&db, QUERY, 2).await.0[0], 202); + } + + #[tokio::test] + async fn releasing_and_abandoning_cursors_gives_their_connections_back() { + let (_tmp, db) = manager().await; + // The pool has 4 connections: a leak would starve `execute` after a few rounds. + for _ in 0..8 { + page(&db, QUERY, 1).await; + db.release_result("s1", QUERY, None); + assert_eq!(db.cursors.registry.lock().slots.len(), 0); + assert_eq!(page(&db, "SELECT count(*) FROM t", 0).await.0, [ROWS as i64]); + } + // Finishing a result also frees its connection. + for _ in 0..8 { + for p in 1..ROWS / PAGE { + page(&db, QUERY, p).await; + } + } + assert_eq!(db.cursors.registry.lock().slots.len(), 0); + } + + #[tokio::test] + async fn a_cancelled_page_closes_its_cursor() { + let (_tmp, db) = manager().await; + page(&db, QUERY, 1).await; + let cancel = CancellationToken::new(); + cancel.cancel(); + let e = db.execute_from("s1", QUERY, 2 * PAGE, PAGE, &cancel, None).await.unwrap_err(); + assert_eq!(e.kind, ErrorKind::Cancelled); + assert_eq!(db.cursors.registry.lock().slots.len(), 0); + assert_eq!(page(&db, QUERY, 2).await.0, ids(2)); + } + + /// A closed result tab releases its cursor even when a page is being read from it: the + /// cursor is not put back afterwards and its statement stops. + #[tokio::test] + async fn releasing_a_cursor_in_the_middle_of_a_page_read_closes_it() { + use super::{Cursors, Key, Read}; + use std::sync::Arc; + use tokio::sync::{Notify, mpsc}; + + let cursors = Arc::new(Cursors::default()); + let key = Key::new("s1", QUERY, None); + let (reads, mut requests) = mpsc::channel::(1); + cursors.register(key.clone(), 0, reads.clone()); + let page = || (Vec::new(), vec![vec![Some("1".to_owned())]], None, true, None); + cursors.finish(1, &page()); + drop(reads); + + let in_read = Arc::new(Notify::new()); + let (release, announced) = (Arc::new(Notify::new()), in_read.clone()); + let server = tokio::spawn({ + let release = release.clone(); + async move { + let read = requests.recv().await.unwrap(); + announced.notify_one(); + release.notified().await; + let _ = read.reply.send(Ok(page())); + // The channel closes once nobody holds a handle on it. + requests.recv().await.is_none() + } + }); + let resumed = tokio::spawn({ + let (cursors, key) = (cursors.clone(), key.clone()); + async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() } + }); + in_read.notified().await; + cursors.release(&key); + release.notify_one(); + assert!(resumed.await.unwrap(), "the page that was being read is still returned"); + assert!(cursors.registry.lock().slots.is_empty(), "the released cursor is not put back"); + assert!(server.await.unwrap(), "the statement's task sees its channel close"); + } + + #[tokio::test] + async fn a_target_keeps_one_cursor_and_all_are_bounded() { + let (_tmp, db) = manager().await; + page(&db, QUERY, 1).await; + page(&db, "SELECT id, name FROM t WHERE id > 0 ORDER BY id", 1).await; + assert_eq!(db.cursors.registry.lock().slots.len(), 1); + // The first statement's cursor is gone: its next page is read again, and still right. + assert_eq!(page(&db, QUERY, 2).await.0, ids(2)); + } +} diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs index e58a7f2eb7..80a0988904 100644 --- a/crates/ide-db/src/jdbc/mod.rs +++ b/crates/ide-db/src/jdbc/mod.rs @@ -606,6 +606,7 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult { affected: (affected >= 0).then_some(affected as f64), elapsed_ms, execution_ms: elapsed_ms, + truncated: Vec::new(), }) } diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index 26314ee650..cdc1cec9fe 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -21,7 +21,7 @@ mod watch; pub use watch::SourcesWatch; pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog}; -pub use conn::{Held, Pool, QueryResult, ResultColumn}; +pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell}; pub use history::HistoryEntry; pub use plan::{PlanNode, PlanProperty}; pub use source::{ @@ -273,6 +273,8 @@ pub struct DbManager { /// Manual-commit data sources, each with the connection of its open /// transaction (taken by the first statement after a commit / rollback). sessions: Mutex>, + /// Result pages read on from where the previous page stopped, not by running the statement again. + cursors: conn::Cursors, /// The data sources as last read from disk, for [`DbManager::reconcile_sources`] /// (`None` until [`DbManager::watch_sources`]). on_disk: Mutex>>, @@ -432,6 +434,7 @@ impl DbManager { session_passwords: Mutex::default(), on_disk: Mutex::default(), sessions: Mutex::default(), + cursors: conn::Cursors::default(), } } @@ -975,6 +978,7 @@ impl DbManager { if let Some(s) = session { end_session(&s).await; } + self.cursors.release_target(id); let pool = self.pools.lock().remove(id); if let Some(p) = pool { p.close().await; @@ -1572,6 +1576,25 @@ impl DbManager { r } + /// Row number `row` (from 0) of the result of `statement`, whole: what a page shows cut + /// short. It leaves the cursor of the result's pages where it stands, and is not recorded + /// in the history (the statement already was). + pub async fn read_row( + &self, + id: &str, + statement: &str, + row: usize, + cancel: &CancellationToken, + schema: Option<&str>, + ) -> IdeResult { + self.run_paged(id, statement, row, 1, cancel, schema, false).await + } + + /// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed). + pub fn release_result(&self, id: &str, statement: &str, schema: Option<&str>) { + self.cursors.release(&conn::CursorKey::new(id, statement, schema)); + } + fn remember_statement(&self, id: &str, statement: &str) { let time = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -1643,12 +1666,44 @@ impl DbManager { max_rows: usize, cancel: &CancellationToken, schema: Option<&str>, + ) -> IdeResult { + self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await + } + + /// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`). + #[allow(clippy::too_many_arguments)] + async fn run_paged( + &self, + id: &str, + statement: &str, + skip: usize, + max_rows: usize, + cancel: &CancellationToken, + schema: Option<&str>, + paging: bool, ) -> IdeResult { let pool = self.pool(id).await?; if let Pool::Jdbc(p) = &*pool { return p.query_in_schema(statement, skip, max_rows, cancel, schema).await; } let session = self.sessions.lock().get(id).cloned(); + if !conn::cursor_statement(statement) { + // A cursor's open statement could keep this one waiting (a lock), and would show data from before it. + self.cursors.release_target(id); + } + if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) { + let key = conn::CursorKey::new(id, statement, schema); + let started = std::time::Instant::now(); + let page = match self.cursors.resume(&key, skip, max_rows, cancel).await { + Some(page) => page, + None => { + let mut held = Held::acquire(&pool).await?; + held.apply_context(schema).await?; + self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await + } + }; + return page.map(|fetched| conn::query_result(statement, fetched, started)); + } let Some(session) = session else { if schema.is_none() { return pool.execute_from(statement, skip, max_rows, cancel).await; diff --git a/crates/ide-db/src/plan.rs b/crates/ide-db/src/plan.rs index bce08ead7e..f1560145f4 100644 --- a/crates/ide-db/src/plan.rs +++ b/crates/ide-db/src/plan.rs @@ -283,6 +283,7 @@ mod tests { has_more: false, elapsed_ms: 0.0, execution_ms: 0.0, + truncated: Vec::new(), } } diff --git a/crates/ide-db/src/snowflake/mod.rs b/crates/ide-db/src/snowflake/mod.rs index da4fdb79df..67a9b6498c 100644 --- a/crates/ide-db/src/snowflake/mod.rs +++ b/crates/ide-db/src/snowflake/mod.rs @@ -892,6 +892,7 @@ impl SnowflakePool { has_more, elapsed_ms: started.elapsed().as_secs_f64() * 1000.0, execution_ms, + truncated: Vec::new(), }))) } diff --git a/crates/ide-db/tests/mysql.rs b/crates/ide-db/tests/mysql.rs index 616724d85e..be7fcfa8dc 100644 --- a/crates/ide-db/tests/mysql.rs +++ b/crates/ide-db/tests/mysql.rs @@ -298,3 +298,27 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> { } Ok(()) } + +#[tokio::test] +async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp, "").await else { return Ok(()) }; + let c = CancellationToken::new(); + let query = "WITH RECURSIVE n(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM n WHERE id < 1000) \ + SELECT id, REPEAT('x', 10) AS pad FROM n ORDER BY id"; + // Forward, back, and jumping: every page holds its own rows whichever cursor served it. + for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] { + let r = db.execute_from("m", query, page * 100, 100, &c, None).await?; + let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect(); + let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect(); + assert_eq!(ids, want, "page {page}"); + assert_eq!(r.has_more, page < 9, "page {page}"); + } + // A pool of 4 connections: cursors that were left open must not exhaust it. + for _ in 0..8 { + db.execute_from("m", query, 100, 100, &c, None).await?; + db.release_result("m", query, None); + assert_eq!(db.execute("m", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1")); + } + Ok(()) +} diff --git a/crates/ide-db/tests/postgres.rs b/crates/ide-db/tests/postgres.rs index f9441f5ee5..f4aac4315f 100644 --- a/crates/ide-db/tests/postgres.rs +++ b/crates/ide-db/tests/postgres.rs @@ -342,3 +342,59 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> { db.execute("p", "DROP DATABASE oi_restore", 1, &c).await?; Ok(()) } + +#[tokio::test] +async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp).await else { return Ok(()) }; + let c = CancellationToken::new(); + let query = "SELECT g AS id, repeat('x', 10) AS pad FROM generate_series(1, 1000) g ORDER BY g"; + // Forward, back, and jumping: every page holds its own rows whichever cursor served it. + for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] { + let r = db.execute_from("p", query, page * 100, 100, &c, None).await?; + let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect(); + let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect(); + assert_eq!(ids, want, "page {page}"); + assert_eq!(r.has_more, page < 9, "page {page}"); + } + // A pool of 4 connections: cursors that were left open must not exhaust it. + for _ in 0..8 { + db.execute_from("p", query, 100, 100, &c, None).await?; + db.release_result("p", query, None); + assert_eq!(db.execute("p", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1")); + } + Ok(()) +} + +#[tokio::test] +async fn cancelling_a_later_page_stops_its_statement_on_the_server() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp).await else { return Ok(()) }; + let marker = "oi_cursor_cancel_marker"; + let slow = format!("SELECT g, pg_sleep(0.05) AS {marker} FROM generate_series(1, 100000) g"); + let cancel = CancellationToken::new(); + let stop = cancel.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + stop.cancel(); + }); + let started = std::time::Instant::now(); + let e = db.execute_from("p", &slow, 5, 10, &cancel, None).await.unwrap_err(); + assert_eq!(e.kind, ide_core::error::ErrorKind::Cancelled); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + let c = CancellationToken::new(); + let active = format!( + "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query LIKE '%{marker}%' \ + AND query NOT LIKE '%pg_stat_activity%'" + ); + let mut running = 1; + for _ in 0..20 { + running = db.execute("p", &active, 1, &c).await?.rows[0][0].as_deref().unwrap().parse().unwrap(); + if running == 0 { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + assert_eq!(running, 0, "the cancelled statement still runs on the server"); + Ok(()) +} diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index e4ac760393..82d5df01e2 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -384,9 +384,12 @@ pub async fn db_execute( #[default] skip: u32, max_rows: u32, schema: Option, + // Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole. + #[default] cell_limit: Option, ) -> IdeResult> { let mut outcomes = Vec::new(); - execute_statements(host, window, request, &id, statements, skip, max_rows, schema.as_deref(), |event| { + 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); } @@ -396,6 +399,38 @@ pub async fn db_execute( 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. +#[command(trust = trusted)] +pub async fn db_result_row( + host: &Host, + window: &str, + request: RequestId, + id: String, + statement: SqlStatement, + row: u32, + schema: Option, +) -> IdeResult { + 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; + host.end_request(request); + result +} + +/// Closes what the pages of a result keep open on the server (its result tab was closed). +#[command(trust = trusted)] +pub fn db_release_result( + host: &Host, + window: &str, + id: String, + statement: String, + schema: Option, +) -> IdeResult<()> { + host.project(window)?.db.release_result(&id, &statement, schema.as_deref()); + Ok(()) +} + #[allow(clippy::too_many_arguments)] #[command(trust = trusted)] pub async fn db_execute_stream( @@ -406,9 +441,11 @@ pub async fn db_execute_stream( statements: Vec, max_rows: u32, schema: Option, + #[default] cell_limit: Option, on_progress: Channel, ) -> IdeResult<()> { - let result = execute_statements(host, window, request, &id, statements, 0, max_rows, schema.as_deref(), |event| { + 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) }) .await; @@ -416,6 +453,14 @@ pub async fn db_execute_stream( on_progress.send(ExecutionEvent::Done { error: result.err() }) } +/// What a run of statements returns of each result. +#[derive(Clone, Copy)] +struct Limits { + skip: u32, + max_rows: u32, + cell_limit: Option, +} + /// Runs in order on one request and stops on cancellation or the first error. #[allow(clippy::too_many_arguments)] async fn execute_statements( @@ -424,8 +469,7 @@ async fn execute_statements( request: RequestId, id: &str, statements: Vec, - skip: u32, - max_rows: u32, + Limits { skip, max_rows, cell_limit }: Limits, schema: Option<&str>, mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>, ) -> IdeResult<()> { @@ -441,7 +485,12 @@ async fn execute_statements( .execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema) .await { - Ok(result) => StatementOutcome { statement, result: Some(result), error: None }, + Ok(mut result) => { + if let Some(limit) = cell_limit { + result.cap_cells(limit as usize); + } + StatementOutcome { statement, result: Some(result), error: None } + } Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e), // The UI may retry a login failure only before any statement has completed. Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && index == 0 => return Err(e), @@ -620,6 +669,8 @@ ide_command::domain!( db_save_jdbc_driver, db_remove_jdbc_driver, db_object_ddl, + db_release_result, + db_result_row, db_remove_history, db_retain_catalog, db_save_source_visibility, @@ -647,9 +698,8 @@ mod tests { use crate::HostConfig; use ide_db::DbDriver; - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn a_reporting_error_stops_the_batch_and_releases_the_request() { - let temp = tempfile::tempdir().unwrap(); + /// A trusted project with an empty SQLite data source `test`. + async fn host_with_sqlite(temp: &tempfile::TempDir) -> Host { let base = dunce::canonicalize(temp.path()).unwrap(); let root = base.join("project"); std::fs::create_dir(&root).unwrap(); @@ -657,28 +707,44 @@ mod tests { let window = "main"; host.open_project(window, &root).unwrap(); host.set_project_trust(&root, true, false).await.unwrap(); - let id = "test"; let file = root.join("test.sqlite"); std::fs::File::create(&file).unwrap(); db_save_sources( &host, window, - vec![DataSource { id: id.into(), name: id.into(), file: Some(file.into()), ..Default::default() }], + vec![DataSource { id: "test".into(), name: "test".into(), file: Some(file.into()), ..Default::default() }], ) .await .unwrap(); + host + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_reporting_error_stops_the_batch_and_releases_the_request() { + let temp = tempfile::tempdir().unwrap(); + let host = host_with_sqlite(&temp).await; + let (window, id) = ("main", "test"); let statements = ide_db::split::split("CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1);", DbDriver::Sqlite); let request = RequestId(1); - let error = execute_statements(&host, window, request, id, statements, 0, 10, None, |event| match event { - ExecutionEvent::Started { index: 0 } => Ok(()), - ExecutionEvent::Completed { index: 0, outcome } => { - assert!(outcome.error.is_none(), "{:?}", outcome.error); - Err(IdeError::internal("cannot report result")) - } - _ => panic!("the failed callback must stop execution"), - }) + let error = execute_statements( + &host, + window, + request, + id, + statements, + Limits { skip: 0, max_rows: 10, cell_limit: None }, + None, + |event| match event { + ExecutionEvent::Started { index: 0 } => Ok(()), + ExecutionEvent::Completed { index: 0, outcome } => { + assert!(outcome.error.is_none(), "{:?}", outcome.error); + Err(IdeError::internal("cannot report result")) + } + _ => panic!("the failed callback must stop execution"), + }, + ) .await .unwrap_err(); assert_eq!(error.message, "cannot report result"); @@ -691,7 +757,57 @@ 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).await.unwrap(); + let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None).await.unwrap(); assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]); } + + #[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(); + let host = host_with_sqlite(&temp).await; + let (window, id) = ("main", "test"); + let wide = "😀é".repeat(50_000); + let setup = ide_db::split::split( + &format!( + "CREATE TABLE docs (n INTEGER, body TEXT); INSERT INTO docs VALUES (1, 'tiny'), (2, '{wide}'), (3, '{wide}');" + ), + DbDriver::Sqlite, + ); + db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, 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 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(); + assert!(size < 1_000, "{size} bytes"); + assert_eq!(page.rows[0][1].as_deref(), Some("tiny")); + let whole = 150_000; + // What the client checks a value it reads again against: FNV-1a over its UTF-16 units. + let hash = + wide.encode_utf16().fold(0x811c_9dc5_u32, |hash, unit| (hash ^ u32::from(unit)).wrapping_mul(0x0100_0193)); + assert_eq!( + page.truncated, + [ + ide_db::TruncatedCell { row: 1, column: 1, length: whole, hash }, + ide_db::TruncatedCell { row: 2, column: 1, length: whole, hash } + ] + ); + + // 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(); + assert!(one.truncated.is_empty()); + let full = one.rows[0][1].clone().unwrap(); + assert_eq!(full.encode_utf16().count(), whole as usize); + assert!(full.starts_with(page.rows[row as usize][1].as_deref().unwrap())); + } + + // 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 = all[0].result.as_ref().unwrap(); + assert!(all.truncated.is_empty()); + assert_eq!(all.rows[2][1].as_deref(), Some(wide.as_str())); + } } diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index 641c864f61..8b79528d7d 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -150,7 +150,8 @@ With focus on a result tab or inside a result, use `⇧⌘]` / `⇧⌘[` in the Closing a selected result activates its left neighbor, or its right neighbor if there is no result on the left. When no results remain, **Output** is selected. Closing an inactive result keeps the current selection. - **Table** or **Chart** view (bar or line, with X/Y columns and an aggregation). -- Paging with page sizes 10 to 1,000; click the row count to count all rows. +- Paging with page sizes 10 to 1,000; click the row count to count all rows. Paging forward continues the running query instead of reading the earlier rows again; a result you stop paging for 30 seconds, or close, releases it. +- A cell longer than 8,192 characters of a read-only query shows its start with a **truncated** tag. Copying it, editing it, opening it in the side panel (**Load whole value**) or exporting the page reads the whole value first. Local filter, search and sort see only the start. - **Search in results** and a per-column local filter on the loaded rows. - A side panel with **Record**, **Value** and **Aggregates** (count, distinct, nulls, sum, average, median, min, max). - JSON values get a JSON editor with **Reformat** and **Open in Window**. diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index bab3ec91c2..cc4c22dc5f 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -149,7 +149,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外 关闭当前选中的结果标签页时,优先选中左侧相邻的结果;没有左侧结果时,选中右侧相邻结果。没有剩余结果时,选中 **输出**。关闭未选中的结果不会改变当前选择。 - **表** 或 **图表** 视图(柱状图或折线图,可选 X/Y 列和聚合方式)。 -- 分页,每页 10 到 1,000 行;点击行数可以统计总行数。 +- 分页,每页 10 到 1,000 行;点击行数可以统计总行数。向后翻页会接着正在运行的查询继续读取,不再重复读取之前的行;停止翻页 30 秒或关闭结果后,查询会被释放。 +- 只读查询中超过 8,192 个字符的单元格只显示开头,并带有 **已截断** 标记。复制、编辑、在侧边栏中打开(**加载完整值**)或导出该页时,会先读取完整值。本地筛选、搜索和排序只作用于显示的开头部分。 - **在结果中搜索**,以及按列对已加载行进行本地筛选。 - 侧边面板:**记录**、**值** 和 **聚合**(计数、去重计数、空值数、求和、平均值、中位数、最小值、最大值)。 - JSON 值使用 JSON 编辑器,支持 **重新格式化** 和 **在窗口中打开**。 diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index dcae03101b..b04ebbdc25 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -122,8 +122,10 @@ 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_result trusted project_host bindings sync db_remove_history trusted project_host bindings async db_remove_jdbc_driver trusted project_host bindings sync +db_result_row trusted project_host bindings async db_retain_catalog trusted project_host bindings async db_run_tool trusted desktop bindings async db_save_jdbc_driver trusted project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index e6e674a253..ad0d59d6cb 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -339,8 +339,8 @@ export const commands = { dbDropDatabase: (id: string, database: string, statement: string) => typedError(__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(__TAURI_INVOKE("db_dump_info", { path })), - dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })), - dbExecuteStream: (request: RequestId, id: string, statements: SqlStatement[], maxRows: number, schema: string | null, onProgress: Channel) => typedError(__TAURI_INVOKE("db_execute_stream", { request, id, statements, maxRows, schema, onProgress })), + dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null, cellLimit: number | null) => typedError(__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) => typedError(__TAURI_INVOKE("db_execute_stream", { request, id, statements, maxRows, schema, cellLimit, onProgress })), dbExplain: (request: RequestId, id: string, statement: string, schema: string | null) => typedError(__TAURI_INVOKE("db_explain", { request, id, statement, schema })), /** * Writes exported result data (CSV, JSON, SQL…) to `path`. Stays in the @@ -353,8 +353,15 @@ export const commands = { dbJdbcDriverClasses: (jars: string[]) => typedError(__TAURI_INVOKE("db_jdbc_driver_classes", { jars })), dbJdbcDrivers: () => typedError(__TAURI_INVOKE("db_jdbc_drivers")), dbObjectDdl: (id: string, schema: string, kind: DbObjectKind, name: string) => typedError(__TAURI_INVOKE("db_object_ddl", { id, schema, kind, name })), + /** 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(__TAURI_INVOKE("db_release_result", { id, statement, schema })), dbRemoveHistory: (id: string, texts: string[] | null) => typedError(__TAURI_INVOKE("db_remove_history", { id, texts })), dbRemoveJdbcDriver: (id: string) => typedError(__TAURI_INVOKE("db_remove_jdbc_driver", { id })), + /** + * 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(__TAURI_INVOKE("db_result_row", { request, id, statement, row, schema })), dbRetainCatalog: (id: string, databases: string[]) => typedError(__TAURI_INVOKE("db_retain_catalog", { id, databases })), /** * Runs `job` against target `id` and streams the tool's output; returns its exit code. Stays @@ -5343,6 +5350,8 @@ export type DbQueryResult = { elapsedMs: number | null, /** Until the server's first answer; the rest of `elapsed_ms` is fetching. */ executionMs: number | null, + /** Cells of `rows` cut short by [`QueryResult::cap_cells`], in row order. */ + truncated: DbTruncatedCell[], }; export type DbResultColumn = { @@ -5522,6 +5531,19 @@ export type DbTriggerInfo = { events: string, }; +/** A cell of a [`QueryResult`] whose text was cut to a prefix. */ +export type DbTruncatedCell = { + row: number, + column: number, + /** Length of the whole value in UTF-16 code units (what a JavaScript string counts). */ + length: number, + /** + * FNV-1a (32 bits) of the whole value's UTF-16 code units, each taken as one 16-bit step, + * so a client that reads the value again can tell whether it is the one that was cut. + */ + hash: number, +}; + /** Transaction control of the data source's consoles. */ export type DbTxMode = "auto" | "manual"; diff --git a/src/features/database/DataView.tsx b/src/features/database/DataView.tsx index 29e5200614..f52cadf36c 100644 --- a/src/features/database/DataView.tsx +++ b/src/features/database/DataView.tsx @@ -100,6 +100,8 @@ export interface DataViewProps extends Pick< | "sort" | "onSort" | "rowMenu" + | "truncated" + | "loadFull" | "initialScrollLeft" | "onHorizontalScroll" > { @@ -234,6 +236,10 @@ export function DataView(props: DataViewProps) { columns={columns} rowCount={shown} value={(r, c) => value(at(r), c)} + truncated={props.truncated && ((r, c) => props.truncated!(at(r), c))} + loadFull={ + props.loadFull && ((cells) => props.loadFull!(cells.map(({ row, col }) => ({ row: at(row), col })))) + } rowState={props.rowState && ((r) => props.rowState!(at(r)))} isModified={props.isModified && ((r, c) => props.isModified!(at(r), c))} editable={props.editable} @@ -287,6 +293,10 @@ export function DataView(props: DataViewProps) { columns={columns} range={range} value={(r, c) => value(at(r), c)} + truncated={props.truncated && ((r, c) => props.truncated!(at(r), c))} + loadFull={ + props.loadFull && ((cells) => props.loadFull!(cells.map(({ row, col }) => ({ row: at(row), col })))) + } editable={!!props.editable && !!props.onEdit && !!range && props.rowState?.(at(range.lead.row)) !== "deleted"} onEdit={(r, c, v) => props.onEdit?.(at(r), c, v)} /> @@ -475,6 +485,8 @@ function SidePanel(props: { columns: readonly GridColumn[]; range: GridRange | null; value: (row: number, col: number) => Cell; + truncated?: GridProps["truncated"]; + loadFull?: GridProps["loadFull"]; editable: boolean; onEdit: (row: number, col: number, v: Cell) => void; }) { @@ -509,6 +521,8 @@ function SidePanel(props: { key={`${range.lead.row}:${range.lead.col}\u0000${value(range.lead.row, range.lead.col) ?? "\u0001"}`} column={columns[range.lead.col] ?? { name: "", type: "" }} cell={value(range.lead.row, range.lead.col)} + cut={props.truncated?.(range.lead.row, range.lead.col) ?? null} + onLoad={() => void props.loadFull?.([{ row: range.lead.row, col: range.lead.col }])} editable={props.editable} onCommit={(v) => props.onEdit(range.lead.row, range.lead.col, v)} /> @@ -525,6 +539,8 @@ function RecordView(props: { columns: readonly GridColumn[]; row: number; value: (row: number, col: number) => Cell; + truncated?: GridProps["truncated"]; + loadFull?: GridProps["loadFull"]; editable: boolean; onEdit: (row: number, col: number, v: Cell) => void; }) { @@ -536,6 +552,8 @@ function RecordView(props: { key={`${c.name}\u0000${props.value(props.row, i) ?? "\u0001"}`} column={c} cell={props.value(props.row, i)} + cut={props.truncated?.(props.row, i) ?? null} + onLoad={() => void props.loadFull?.([{ row: props.row, col: i }])} editable={props.editable} onCommit={(v) => props.onEdit(props.row, i, v)} /> @@ -544,50 +562,82 @@ function RecordView(props: { ); } -function RecordField(props: { column: GridColumn; cell: Cell; editable: boolean; onCommit: (v: Cell) => void }) { +/** What a value that is shown cut short offers: the whole value is read on request (until then it is read-only). */ +function CutNotice(props: { shown: number; total: number; onLoad: () => void }) { + const { shown, total } = props; + return ( +
+ {tx`Only the first ${shown} of ${total} characters are shown.`} + +
+ ); +} + +function RecordField(props: { + column: GridColumn; + cell: Cell; + cut: number | null; + onLoad: () => void; + editable: boolean; + onCommit: (v: Cell) => void; +}) { const [text, setText] = useState(props.cell ?? ""); const commit = () => { if (text !== (props.cell ?? "") || (props.cell === null && text !== "")) props.onCommit(text); }; const c = props.column; + const editable = props.editable && props.cut === null; return ( -