дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 17:21:13 +02:00
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 <[email protected]>
Цей коміт міститься в:
1 джерело
40c616e46d
коміт
644a2d5784
30 files changed
+1851
-256
No files matched your search
@@ -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! {
|
||||
|
||||
@@ -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<TruncatedCell>,
|
||||
}
|
||||
|
||||
/// 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<R: Row>(row: &R) -> Vec<ResultColumn> {
|
||||
.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<R> {
|
||||
columns: Vec<ResultColumn>,
|
||||
carry: Option<R>,
|
||||
}
|
||||
|
||||
impl<R> Default for Reader<R> {
|
||||
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<u64> = 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<S, D, R>(
|
||||
stream: &mut S,
|
||||
reader: &mut Reader<R>,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
mode: Cells,
|
||||
rows_affected: impl Fn(&D) -> u64,
|
||||
) -> IdeResult<Fetched>
|
||||
where
|
||||
S: futures::Stream<Item = Result<sqlx::Either<D, R>, sqlx::Error>> + Unpin,
|
||||
R: Row,
|
||||
usize: ColumnIndex<R>,
|
||||
String: sqlx::Type<R::Database>,
|
||||
for<'r> String: Decode<'r, R::Database>,
|
||||
for<'r> Vec<u8>: Decode<'r, R::Database>,
|
||||
{
|
||||
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
|
||||
let mut affected: Option<u64> = None;
|
||||
let mut has_more = false;
|
||||
let mut first: Option<Instant> = 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<ResultColumn> = Vec::new();
|
||||
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
|
||||
let mut affected: Option<u64> = None;
|
||||
let mut has_more = false;
|
||||
let mut failure = None;
|
||||
let mut first: Option<Instant> = 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<Vec<Vec<Option<String>>>> {
|
||||
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<Vec<Option<String>>>) -> 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;
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<IdeResult<Fetched>>,
|
||||
}
|
||||
|
||||
/// 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<Read>,
|
||||
}
|
||||
|
||||
/// 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<Read>,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<IdeResult<Fetched>> {
|
||||
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<Slot>,
|
||||
issued: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Cursors {
|
||||
registry: Mutex<Registry>,
|
||||
}
|
||||
|
||||
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<IdeResult<Fetched>> {
|
||||
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<Pool>,
|
||||
key: Key,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Fetched> {
|
||||
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<Read>) -> 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<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
|
||||
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<i64>, 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<i64> {
|
||||
((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::<Vec<_>>(), ["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::<Read>(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));
|
||||
}
|
||||
}
|
||||
@@ -606,6 +606,7 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
|
||||
affected: (affected >= 0).then_some(affected as f64),
|
||||
elapsed_ms,
|
||||
execution_ms: elapsed_ms,
|
||||
truncated: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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<HashMap<String, Session>>,
|
||||
/// 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<Option<Vec<DataSource>>>,
|
||||
@@ -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<QueryResult> {
|
||||
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<QueryResult> {
|
||||
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<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;
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -283,6 +283,7 @@ mod tests {
|
||||
has_more: false,
|
||||
elapsed_ms: 0.0,
|
||||
execution_ms: 0.0,
|
||||
truncated: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -892,6 +892,7 @@ impl SnowflakePool {
|
||||
has_more,
|
||||
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
execution_ms,
|
||||
truncated: Vec::new(),
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -384,9 +384,12 @@ pub async fn db_execute(
|
||||
#[default] skip: u32,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
// Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole.
|
||||
#[default] cell_limit: Option<u32>,
|
||||
) -> IdeResult<Vec<StatementOutcome>> {
|
||||
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<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;
|
||||
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<String>,
|
||||
) -> 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<SqlStatement>,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
#[default] cell_limit: Option<u32>,
|
||||
on_progress: Channel<ExecutionEvent>,
|
||||
) -> 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<u32>,
|
||||
}
|
||||
|
||||
/// 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<SqlStatement>,
|
||||
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()));
|
||||
}
|
||||
}
|
||||
@@ -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**.
|
||||
|
||||
@@ -149,7 +149,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
|
||||
关闭当前选中的结果标签页时,优先选中左侧相邻的结果;没有左侧结果时,选中右侧相邻结果。没有剩余结果时,选中 **输出**。关闭未选中的结果不会改变当前选择。
|
||||
|
||||
- **表** 或 **图表** 视图(柱状图或折线图,可选 X/Y 列和聚合方式)。
|
||||
- 分页,每页 10 到 1,000 行;点击行数可以统计总行数。
|
||||
- 分页,每页 10 到 1,000 行;点击行数可以统计总行数。向后翻页会接着正在运行的查询继续读取,不再重复读取之前的行;停止翻页 30 秒或关闭结果后,查询会被释放。
|
||||
- 只读查询中超过 8,192 个字符的单元格只显示开头,并带有 **已截断** 标记。复制、编辑、在侧边栏中打开(**加载完整值**)或导出该页时,会先读取完整值。本地筛选、搜索和排序只作用于显示的开头部分。
|
||||
- **在结果中搜索**,以及按列对已加载行进行本地筛选。
|
||||
- 侧边面板:**记录**、**值** 和 **聚合**(计数、去重计数、空值数、求和、平均值、中位数、最小值、最大值)。
|
||||
- JSON 值使用 JSON 编辑器,支持 **重新格式化** 和 **在窗口中打开**。
|
||||
|
||||
@@ -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
|
||||
|
||||
+24
-2
@@ -339,8 +339,8 @@ 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) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
|
||||
dbExecuteStream: (request: RequestId, id: string, statements: SqlStatement[], maxRows: number, schema: string | null, onProgress: Channel<ExecutionEvent>) => typedError<null, IdeError>(__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<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 })),
|
||||
/**
|
||||
* Writes exported result data (CSV, JSON, SQL…) to `path`. Stays in the
|
||||
@@ -353,8 +353,15 @@ 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 })),
|
||||
/** 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 })),
|
||||
dbRemoveJdbcDriver: (id: string) => typedError<null, IdeError>(__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<DbQueryResult, IdeError>(__TAURI_INVOKE("db_result_row", { request, id, statement, row, schema })),
|
||||
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
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<div className={styles.cutNotice} role="status">
|
||||
<span>{tx`Only the first ${shown} of ${total} characters are shown.`}</span>
|
||||
<Button size="small" onClick={props.onLoad}>
|
||||
<T>Load whole value</T>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<label className={styles.recordField}>
|
||||
<span className={styles.recordLabel}>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : c.foreignKey ? "db-column-fk" : "db-column"} size={16} />
|
||||
{c.name}
|
||||
{c.type && c.type !== "NULL" && <span className={styles.treeType}>{c.type}</span>}
|
||||
</span>
|
||||
{hasLineBreak(props.cell ?? "") ? (
|
||||
// A single-line field would drop the line breaks on the first edit.
|
||||
<textarea
|
||||
className={styles.recordText}
|
||||
rows={Math.min(8, (props.cell ?? "").split(/\r\n|\r|\n/).length)}
|
||||
value={text}
|
||||
readOnly={!props.editable}
|
||||
spellCheck={false}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={commit}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
mono
|
||||
value={text}
|
||||
readOnly={!props.editable}
|
||||
placeholder={props.cell === null ? "<null>" : undefined}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") commit();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
<>
|
||||
<label className={styles.recordField}>
|
||||
<span className={styles.recordLabel}>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : c.foreignKey ? "db-column-fk" : "db-column"} size={16} />
|
||||
{c.name}
|
||||
{c.type && c.type !== "NULL" && <span className={styles.treeType}>{c.type}</span>}
|
||||
</span>
|
||||
{hasLineBreak(props.cell ?? "") ? (
|
||||
// A single-line field would drop the line breaks on the first edit.
|
||||
<textarea
|
||||
className={styles.recordText}
|
||||
rows={Math.min(8, (props.cell ?? "").split(/\r\n|\r|\n/).length)}
|
||||
value={text}
|
||||
readOnly={!editable}
|
||||
spellCheck={false}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={commit}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
mono
|
||||
value={text}
|
||||
readOnly={!editable}
|
||||
placeholder={props.cell === null ? "<null>" : undefined}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") commit();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
{props.cut !== null && <CutNotice shown={props.cell?.length ?? 0} total={props.cut} onLoad={props.onLoad} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The Value panel's editor: plain text, or the JSON code editor for JSON cells (#2333). */
|
||||
function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; onCommit: (v: Cell) => void }) {
|
||||
function ValueView(props: {
|
||||
column: GridColumn;
|
||||
cell: Cell;
|
||||
cut: number | null;
|
||||
onLoad: () => void;
|
||||
editable: boolean;
|
||||
onCommit: (v: Cell) => void;
|
||||
}) {
|
||||
const name = props.column.name;
|
||||
const editable = props.editable && props.cut === null;
|
||||
const [json] = useState(() => isJsonValue(props.column.type, props.cell));
|
||||
const validate = isJsonColumn(props.column.type);
|
||||
// JSON opens pretty-printed; the panel applies what the editor shows.
|
||||
@@ -600,18 +650,19 @@ function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; o
|
||||
const editor = useRef<JsonEditorApi | null>(null);
|
||||
const dirty = text !== initial;
|
||||
const commit = () => {
|
||||
if (props.editable && dirty && !error && !pending) props.onCommit(text);
|
||||
if (editable && dirty && !error && !pending) props.onCommit(text);
|
||||
};
|
||||
const [windowOpen, setWindowOpen] = useState(false);
|
||||
return (
|
||||
<div className={styles.valueView}>
|
||||
{props.cut !== null && <CutNotice shown={props.cell?.length ?? 0} total={props.cut} onLoad={props.onLoad} />}
|
||||
{json ? (
|
||||
<>
|
||||
<JsonValueEditor
|
||||
initial={initial}
|
||||
validate={validate}
|
||||
emptyIsNull={props.cell === null}
|
||||
readOnly={!props.editable}
|
||||
readOnly={!editable}
|
||||
ariaLabel={tx`Value of ${name}`}
|
||||
onChange={(t, e, busy) => {
|
||||
setText(t);
|
||||
@@ -628,11 +679,7 @@ function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; o
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.filterButtons}>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!props.editable || !!error || pending}
|
||||
onClick={() => editor.current?.reformat()}
|
||||
>
|
||||
<Button size="small" disabled={!editable || !!error || pending} onClick={() => editor.current?.reformat()}>
|
||||
<T>Reformat</T>
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setWindowOpen(true)}>
|
||||
@@ -645,7 +692,7 @@ function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; o
|
||||
className={styles.valueText}
|
||||
aria-label={tx`Value of ${name}`}
|
||||
value={text}
|
||||
readOnly={!props.editable}
|
||||
readOnly={!editable}
|
||||
placeholder={props.cell === null ? "<null>" : undefined}
|
||||
spellCheck={false}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
@@ -654,7 +701,7 @@ function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; o
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{props.editable && (
|
||||
{editable && (
|
||||
<div className={styles.filterButtons}>
|
||||
<Button size="small" disabled={!dirty || !!error || pending} onClick={commit}>
|
||||
<T>Apply</T>
|
||||
@@ -676,7 +723,7 @@ function ValueView(props: { column: GridColumn; cell: Cell; editable: boolean; o
|
||||
baseline={initial}
|
||||
validate={validate}
|
||||
emptyIsNull={props.cell === null}
|
||||
readOnly={!props.editable}
|
||||
readOnly={!editable}
|
||||
onClose={() => setWindowOpen(false)}
|
||||
onApply={(t) => {
|
||||
props.onCommit(t);
|
||||
|
||||
@@ -108,6 +108,23 @@
|
||||
color: var(--fg-muted);
|
||||
font-style: italic;
|
||||
}
|
||||
/* A value the page carries only the start of: tagged before its text, which a column clips on the right. */
|
||||
.cellCutMark {
|
||||
flex: none;
|
||||
margin-right: var(--space-1-5);
|
||||
padding: 0 var(--space-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.cutNotice {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.lineBreak {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import clsx from "clsx";
|
||||
import { Checkbox, Dialog, Icon, lockDragCursor, Popup, SelectListbox, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { Checkbox, Dialog, Icon, lockDragCursor, Popup, SelectListbox, showContextMenu, T, type MenuItem } from "@/ui";
|
||||
import { parseDelimited, toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { initialJsonText, isJsonColumn, isJsonValue } from "./jsonValue";
|
||||
import { JsonValueWindow } from "./JsonValueEditor";
|
||||
@@ -67,6 +67,10 @@ export interface GridProps {
|
||||
rowCount: number;
|
||||
/** Displayed value (pending edits applied). */
|
||||
value: (row: number, col: number) => Cell;
|
||||
/** The whole length (UTF-16 units) of a cell shown cut short (a page carries only the start of a large value); `null` when it is whole. */
|
||||
truncated?: (row: number, col: number) => number | null;
|
||||
/** Reads the whole values of cut cells (the resolved values follow `cells`); `null` when they could not be read. */
|
||||
loadFull?: (cells: ReadonlyArray<{ row: number; col: number }>) => Promise<Cell[] | null>;
|
||||
/** The format plain ⌘C copies in (the toolbar's extractor; TSV by default). */
|
||||
copyFormat?: CopyFormat;
|
||||
rowState?: (row: number) => "deleted" | "inserted" | null;
|
||||
@@ -281,13 +285,23 @@ export function Grid(props: GridProps) {
|
||||
return Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i);
|
||||
};
|
||||
|
||||
const copy = (format: CopyFormat, header: boolean, wholeRows = false) => {
|
||||
const copy = async (format: CopyFormat, header: boolean, wholeRows = false) => {
|
||||
if (!sel) return;
|
||||
const n = norm(sel);
|
||||
const cols = wholeRows
|
||||
? columns.map((_, i) => i)
|
||||
: Array.from({ length: n.right - n.left + 1 }, (_, i) => n.left + i);
|
||||
const rows = selectedRows().map((r) => cols.map((c) => value(r, c)));
|
||||
const picked = selectedRows();
|
||||
const rows = picked.map((r) => cols.map((c) => value(r, c)));
|
||||
// A cut cell copies as its whole value.
|
||||
const cut = picked.flatMap((row, i) =>
|
||||
cols.flatMap((col, j) => (props.truncated?.(row, col) != null ? [{ row, col, i, j }] : [])),
|
||||
);
|
||||
if (cut.length) {
|
||||
const full = await props.loadFull?.(cut);
|
||||
if (!full) return;
|
||||
cut.forEach(({ i, j }, k) => (rows[i]![j] = full[k]!));
|
||||
}
|
||||
const head = header ? cols.map((c) => columns[c]!.name) : null;
|
||||
const text =
|
||||
format === "onerow"
|
||||
@@ -325,7 +339,15 @@ export function Grid(props: GridProps) {
|
||||
/** `maximized` (⇧Enter): the multi-line editor, which multi-line and long values always use. */
|
||||
const startEdit = (row: number, col: number, maximized = false) => {
|
||||
if (!editable || props.rowState?.(row) === "deleted") return;
|
||||
const cell = value(row, col);
|
||||
// A cut value is read whole first: editing its start would write that back.
|
||||
if (props.truncated?.(row, col) != null) {
|
||||
void props.loadFull?.([{ row, col }]).then((full) => full && openEditor(row, col, full[0]!, maximized));
|
||||
return;
|
||||
}
|
||||
openEditor(row, col, value(row, col), maximized);
|
||||
};
|
||||
|
||||
const openEditor = (row: number, col: number, cell: Cell, maximized: boolean) => {
|
||||
const text = cell ?? "";
|
||||
// JSON cells (type or content) edit in the JSON value editor when the dialog opens (#2333).
|
||||
const json = isJsonValue(columns[col]?.type ?? "", cell);
|
||||
@@ -806,6 +828,8 @@ export function Grid(props: GridProps) {
|
||||
);
|
||||
}
|
||||
const val = value(r, c);
|
||||
const cut = props.truncated?.(r, c) ?? null;
|
||||
const [shown, total] = [val?.length ?? 0, cut ?? 0];
|
||||
// Boolean cells show a checkbox while the grid is editable (DataGrip); Space toggles too.
|
||||
const lit =
|
||||
editable && onEdit && bools[c] && state !== "deleted" ? booleanLiterals(props.driver) : null;
|
||||
@@ -828,8 +852,19 @@ export function Grid(props: GridProps) {
|
||||
if (dragging.current) setSel((s) => (s ? { ...s, r1: r, c1: c } : s));
|
||||
}}
|
||||
onDoubleClick={() => startEdit(r, c)}
|
||||
title={val != null && val.length > 40 ? val.slice(0, 2000) : undefined}
|
||||
title={
|
||||
cut !== null
|
||||
? tx`Only the first ${shown} of ${total} characters are shown. Double-click to load the whole value.`
|
||||
: val != null && val.length > 40
|
||||
? val.slice(0, 2000)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{cut !== null && (
|
||||
<span className={styles.cellCutMark}>
|
||||
<T>truncated</T>
|
||||
</span>
|
||||
)}
|
||||
{lit ? (
|
||||
<>
|
||||
<span
|
||||
|
||||
@@ -26,6 +26,7 @@ import { notifications } from "@/workbench/contributions";
|
||||
import { ToolWindowContentTabs } from "@/workbench/toolwindows/ToolWindows";
|
||||
import { ChartView } from "./ChartView";
|
||||
import { ColumnsPopup } from "./ColumnsPopup";
|
||||
import { cellOf, cutLength, hasCutCells, loadCells, loadPage, rowsOf, useCutCells } from "./cutCells";
|
||||
import { DataView, ExtractorSelect, PanelToggle, copyFormatOf, exportMenu, type DataPanel } from "./DataView";
|
||||
import type { ExportData, ExportFormat } from "./export";
|
||||
import { buildRowEdits, emptyEdits, hasEdits, splitTarget, type Cell, type PendingEdits } from "./model";
|
||||
@@ -340,16 +341,38 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
};
|
||||
const loaded = r?.rows.length ?? 0;
|
||||
const rowCount = loaded + edits.inserts.length;
|
||||
// Cells the page carries only the start of are read whole on demand and re-render the grid.
|
||||
const wholeCells = useCutCells();
|
||||
const value = useCallback(
|
||||
(row: number, col: number): Cell => {
|
||||
const name = resultNames[col]!;
|
||||
if (row >= loaded) return edits.inserts[row - loaded]?.get(name) ?? null;
|
||||
const upd = edits.updates.get(row);
|
||||
if (upd?.has(name)) return upd.get(name)!;
|
||||
return r?.rows[row]?.[col] ?? null;
|
||||
return r ? cellOf(r, row, col) : null;
|
||||
},
|
||||
[r, resultNames, loaded, edits],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- `wholeCells` changes when a cut cell is read
|
||||
[r, resultNames, loaded, edits, wholeCells],
|
||||
);
|
||||
const truncated = useCallback(
|
||||
(row: number, col: number) => (r && row < loaded ? cutLength(r, row, col) : null),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- `wholeCells` changes when a cut cell is read
|
||||
[r, loaded, wholeCells],
|
||||
);
|
||||
/** Reads cut cells whole (failing with a notification: `null`). */
|
||||
const loadFull = async (cells: ReadonlyArray<{ row: number; col: number }>): Promise<Cell[] | null> => {
|
||||
try {
|
||||
return await loadCells(tab, cells);
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot read the whole value",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
key: "db-whole-value",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const onEdit = (row: number, col: number, v: Cell) => {
|
||||
if (!editable || busy || !sources[col]) return; // an aliased or computed column
|
||||
@@ -362,7 +385,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
next.inserts[row - loaded] = ins;
|
||||
} else {
|
||||
const upd = new Map(next.updates.get(row));
|
||||
if ((r?.rows[row]?.[col] ?? null) === v) upd.delete(name);
|
||||
if ((r ? cellOf(r, row, col) : null) === v) upd.delete(name);
|
||||
else upd.set(name, v);
|
||||
if (upd.size) next.updates.set(row, upd);
|
||||
else next.updates.delete(row);
|
||||
@@ -400,8 +423,13 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
const submit = async () => {
|
||||
if (!r || !target || !pk || !editable || busy || submittingResults.has(r)) return;
|
||||
setSubmittingResult(r, true);
|
||||
const list = buildRowEdits(resultNames, r.rows, pk, edits);
|
||||
try {
|
||||
// The key of a row identifies it by its whole value.
|
||||
const keyCells = [...edits.updates.keys(), ...edits.deletes].flatMap((row) =>
|
||||
pk.map((name) => ({ row, col: resultNames.indexOf(name) })).filter((c) => cutLength(r, c.row, c.col) !== null),
|
||||
);
|
||||
if (keyCells.length) await loadCells(tab, keyCells);
|
||||
const list = buildRowEdits(resultNames, rowsOf(r), pk, edits);
|
||||
// The Output log shows what the submit is about to change.
|
||||
for (const s of editStatements(driver, target.schema ?? "", target.table, list)) log("statement", s);
|
||||
const n = await withConnection(tab.sourceId, () =>
|
||||
@@ -425,16 +453,31 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
const showExport = (at: { x: number; y: number }) =>
|
||||
r &&
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
if (!r) return;
|
||||
// What is exported or copied is the whole values, not the starts the page carries.
|
||||
if (hasCutCells(r)) {
|
||||
try {
|
||||
await loadPage(tab);
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot read the whole values",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
key: "db-whole-value",
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
showContextMenu(
|
||||
at,
|
||||
exportMenu(
|
||||
{ columns, rows: r.rows, driver, table: queryTable(text, { driver }) },
|
||||
{ columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) },
|
||||
queryTable(text, { driver }),
|
||||
extractor,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
// Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor.
|
||||
const canSubmit = editable && dirty && !busy;
|
||||
@@ -474,7 +517,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
enabled: () => true,
|
||||
run: () => {
|
||||
const rect = viewRef.current?.querySelector("[data-db-export]")?.getBoundingClientRect();
|
||||
if (rect) showExport({ x: rect.left, y: rect.bottom });
|
||||
if (rect) void showExport({ x: rect.left, y: rect.bottom });
|
||||
},
|
||||
},
|
||||
deleteRows: { enabled: (rows) => rowsEditable && rows.length > 0, run: deleteRows },
|
||||
@@ -564,7 +607,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
title="Export Data"
|
||||
shortcut={shortcutLabel("db.exportData")}
|
||||
data-db-export=""
|
||||
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
|
||||
onClick={(e) => void showExport({ x: e.clientX, y: e.clientY })}
|
||||
/>
|
||||
{view === "table" && <PanelToggle panel={panel} onChange={setPanel} />}
|
||||
{onClose && <IconButton icon="close" title="Close" onClick={onClose} />}
|
||||
@@ -587,6 +630,8 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
fixedRows={loaded}
|
||||
driver={driver}
|
||||
value={value}
|
||||
truncated={truncated}
|
||||
loadFull={loadFull}
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
copyFormat={copyFormatOf(extractor)}
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DbDriver, DbQueryResult, DbTableDetails } from "@/platform/ipc";
|
||||
import { provideToolWindowService } from "@/workbench/contributions";
|
||||
import { cellOf, cutLength, hasCutCells, hashOf, loadCells, loadPage } from "./cutCells";
|
||||
import { ResultsView } from "./ResultsView";
|
||||
import { CELL_LIMIT, closeResult, executeConsole, useDatabase, type ResultTab } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
driver: "postgres" as DbDriver,
|
||||
details: vi.fn(),
|
||||
execute: vi.fn(),
|
||||
resultRow: vi.fn(),
|
||||
release: vi.fn(),
|
||||
statements: vi.fn(),
|
||||
connected: vi.fn(),
|
||||
writeClipboardText: vi.fn(async (_text: string) => {}),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
dbTableDetails: backend.details,
|
||||
dbExecute: backend.execute,
|
||||
dbResultRow: backend.resultRow,
|
||||
dbReleaseResult: backend.release,
|
||||
dbStatements: backend.statements,
|
||||
dbConnected: backend.connected,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/clipboard", () => ({ writeClipboardText: backend.writeClipboardText }));
|
||||
vi.mock("@tanstack/react-virtual", () => ({
|
||||
useVirtualizer: ({ count }: { count: number }) => ({
|
||||
getTotalSize: () => count * 24,
|
||||
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
|
||||
scrollToIndex: () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const details: DbTableDetails = {
|
||||
columns: [
|
||||
{ name: "id", dataType: "int4", primaryKey: true, nullable: false, default: null },
|
||||
{ name: "body", dataType: "text", primaryKey: false, nullable: false, default: null },
|
||||
],
|
||||
indexes: [],
|
||||
foreignKeys: [],
|
||||
triggers: [],
|
||||
};
|
||||
|
||||
/** Page 2 of 10 rows: row 1 of it (row 21 of the result) has a body of `whole.length` characters. */
|
||||
const whole = "😀é".repeat(5000);
|
||||
const start = Array.from(whole).slice(0, 4000).join("");
|
||||
const shown = [start];
|
||||
const length = whole.length;
|
||||
const hash = hashOf(whole);
|
||||
|
||||
function page(): DbQueryResult {
|
||||
return {
|
||||
statement: "SELECT id, body FROM docs",
|
||||
columns: [
|
||||
{ name: "id", typeName: "int4" },
|
||||
{ name: "body", typeName: "text" },
|
||||
],
|
||||
rows: [
|
||||
["20", "short"],
|
||||
["21", shown[0]!],
|
||||
],
|
||||
affected: null,
|
||||
hasMore: false,
|
||||
elapsedMs: 1,
|
||||
executionMs: 1,
|
||||
truncated: [{ row: 1, column: 1, length, hash }],
|
||||
};
|
||||
}
|
||||
|
||||
const text = "SELECT id, body FROM docs";
|
||||
|
||||
function show(): ResultTab {
|
||||
const tab: ResultTab = {
|
||||
id: 1,
|
||||
title: "Result 1",
|
||||
path: "console.sql",
|
||||
sourceId: "pg",
|
||||
outcome: { statement: { from: 0, to: text.length, text }, result: page(), error: null },
|
||||
page: 2,
|
||||
pageSize: 10,
|
||||
};
|
||||
useDatabase.setState({
|
||||
sources: [{ id: "pg", name: "Local", driver: backend.driver }],
|
||||
completion: {
|
||||
pg: {
|
||||
defaultSchema: "public",
|
||||
tables: [{ schema: "public", name: "docs", kind: "table", columns: [] }],
|
||||
foreignKeys: [],
|
||||
},
|
||||
},
|
||||
results: [tab],
|
||||
activeResult: tab.id,
|
||||
output: [],
|
||||
details: {},
|
||||
consoleSchemas: {},
|
||||
});
|
||||
return tab;
|
||||
}
|
||||
|
||||
const rowReply = (body = whole) => {
|
||||
const r = page();
|
||||
return Promise.resolve({ status: "ok", data: { ...r, rows: [["21", body]], truncated: [] } });
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
provideToolWindowService({ show: () => {} } as never);
|
||||
vi.clearAllMocks();
|
||||
backend.details.mockResolvedValue({ status: "ok", data: details });
|
||||
backend.resultRow.mockImplementation(() => rowReply());
|
||||
backend.release.mockResolvedValue({ status: "ok", data: null });
|
||||
backend.connected.mockResolvedValue({ status: "ok", data: ["pg"] });
|
||||
backend.statements.mockImplementation((_id: unknown, t: string) =>
|
||||
Promise.resolve({ status: "ok", data: [{ from: 0, to: t.length, text: t }] }),
|
||||
);
|
||||
});
|
||||
|
||||
describe("cut cells", () => {
|
||||
it("read their whole value from the row of the result, not from the page", async () => {
|
||||
const tab = show();
|
||||
const r = tab.outcome.result!;
|
||||
expect(cutLength(r, 1, 1)).toBe(length);
|
||||
expect(hasCutCells(r)).toBe(true);
|
||||
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(cellOf(r, 1, 1)).toBe(whole);
|
||||
expect(cutLength(r, 1, 1)).toBeNull();
|
||||
expect(hasCutCells(r)).toBe(false);
|
||||
// Read once: a second request does not ask the backend again.
|
||||
await loadCells(tab, [{ row: 1, col: 1 }]);
|
||||
expect(backend.resultRow).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("refuse a row that is no longer the one the page showed", async () => {
|
||||
const tab = show();
|
||||
backend.resultRow.mockImplementationOnce(() => rowReply("x".repeat(length)));
|
||||
await expect(loadCells(tab, [{ row: 1, col: 1 }])).rejects.toThrow("The result changed");
|
||||
backend.resultRow.mockImplementationOnce(() => rowReply(whole + "!"));
|
||||
await expect(loadCells(tab, [{ row: 1, col: 1 }])).rejects.toThrow("The result changed");
|
||||
expect(cellOf(tab.outcome.result!, 1, 1)).toBe(shown[0]);
|
||||
});
|
||||
|
||||
it("refuse a value that differs from the one that was cut anywhere, not only in its start or length", async () => {
|
||||
const tab = show();
|
||||
// Same length, same start the page shows: only the end differs.
|
||||
backend.resultRow.mockImplementationOnce(() => rowReply(whole.slice(0, -1) + "!"));
|
||||
await expect(loadCells(tab, [{ row: 1, col: 1 }])).rejects.toThrow("The result changed");
|
||||
expect(cellOf(tab.outcome.result!, 1, 1)).toBe(shown[0]);
|
||||
expect(hasCutCells(tab.outcome.result!)).toBe(true);
|
||||
});
|
||||
|
||||
it("refuse a read that returns fewer rows than were asked for", async () => {
|
||||
const tab = show();
|
||||
backend.resultRow.mockImplementationOnce(() =>
|
||||
Promise.resolve({ status: "ok", data: { ...page(), rows: [], truncated: [] } }),
|
||||
);
|
||||
await expect(loadCells(tab, [{ row: 1, col: 1 }])).rejects.toThrow("The result changed");
|
||||
expect(cellOf(tab.outcome.result!, 1, 1)).toBe(shown[0]);
|
||||
|
||||
const r = tab.outcome.result!;
|
||||
const many = Array.from({ length: 12 }, (_, i) => i);
|
||||
r.rows = many.map((i) => [String(i), shown[0]!]);
|
||||
r.truncated = many.map((row) => ({ row, column: 1, length, hash }));
|
||||
backend.execute.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
status: "ok",
|
||||
data: [
|
||||
{
|
||||
statement: tab.outcome.statement,
|
||||
error: null,
|
||||
result: { ...r, rows: many.slice(0, 11).map((i) => [String(i), whole]), truncated: [] },
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
await expect(loadPage(tab)).rejects.toThrow("The result changed");
|
||||
expect(hasCutCells(r)).toBe(true);
|
||||
});
|
||||
|
||||
it("hash a value as the backend does", () => {
|
||||
// The same values as the Rust test of the backend's hash.
|
||||
expect(hashOf("")).toBe(2166136261);
|
||||
expect(hashOf("a")).toBe(3826002220);
|
||||
expect(hashOf("a😀b")).toBe(2412414209);
|
||||
expect(hashOf("日本語日本語")).toBe(2778669755);
|
||||
});
|
||||
|
||||
it("read a page that has many cut rows with one request", async () => {
|
||||
const tab = show();
|
||||
const r = tab.outcome.result!;
|
||||
const many = Array.from({ length: 12 }, (_, i) => i);
|
||||
r.rows = many.map((i) => [String(i), shown[0]!]);
|
||||
r.truncated = many.map((row) => ({ row, column: 1, length, hash }));
|
||||
backend.execute.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
status: "ok",
|
||||
data: [
|
||||
{
|
||||
statement: tab.outcome.statement,
|
||||
error: null,
|
||||
result: { ...r, rows: many.map((i) => [String(i), whole]), truncated: [] },
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
await loadPage(tab);
|
||||
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(hasCutCells(r)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the grid", () => {
|
||||
it("marks a cut cell and copies and edits its whole value", async () => {
|
||||
show();
|
||||
await act(async () => render(<ResultsView />));
|
||||
const cells = screen.getAllByRole("gridcell");
|
||||
// id, body of the first row, then of the second.
|
||||
expect(cells[1]!.textContent).not.toContain("truncated");
|
||||
expect(cells[3]!.textContent).toContain("truncated");
|
||||
expect(cells[3]!.getAttribute("title")).toContain(`first ${shown[0]!.length} of ${length}`);
|
||||
|
||||
fireEvent.mouseDown(cells[3]!, { button: 0 });
|
||||
await act(async () => fireEvent.keyDown(screen.getByRole("grid"), { key: "c", metaKey: true }));
|
||||
expect(backend.writeClipboardText).toHaveBeenCalledWith(whole);
|
||||
|
||||
// Once read, the cell is whole.
|
||||
expect(screen.getAllByRole("gridcell")[3]!.textContent).not.toContain("truncated");
|
||||
expect(backend.resultRow).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("edits the whole value of a cut cell, never its start", async () => {
|
||||
show();
|
||||
await act(async () => render(<ResultsView />));
|
||||
await act(async () => fireEvent.doubleClick(screen.getAllByRole("gridcell")[3]!));
|
||||
expect(backend.resultRow).toHaveBeenCalledTimes(1);
|
||||
const editor = (await screen.findByRole("textbox", { name: /body/ })) as HTMLTextAreaElement;
|
||||
expect(editor.value).toBe(whole);
|
||||
});
|
||||
|
||||
it("does not open the editor on the start of a value it could not read", async () => {
|
||||
show();
|
||||
backend.resultRow.mockImplementation(() => rowReply("x".repeat(length)));
|
||||
await act(async () => render(<ResultsView />));
|
||||
await act(async () => fireEvent.doubleClick(screen.getAllByRole("gridcell")[3]!));
|
||||
expect(screen.queryByRole("textbox", { name: "Edit body" })).toBeNull();
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(screen.getAllByRole("gridcell")[3]!.textContent).toContain("truncated");
|
||||
});
|
||||
});
|
||||
|
||||
describe("running queries", () => {
|
||||
it("cap the cells of a query that is safe to run again, and only of such queries", async () => {
|
||||
useDatabase.setState({ sources: [{ id: "pg", name: "Local", driver: "postgres" }], consoles: { "a.sql": "pg" } });
|
||||
backend.execute.mockImplementation((_r: unknown, _id: unknown, statements: Array<{ text: string }>) =>
|
||||
Promise.resolve({ status: "ok", data: statements.map((s) => ({ statement: s, result: null, error: "x" })) }),
|
||||
);
|
||||
await executeConsole("a.sql", "SELECT 1", 0, 8);
|
||||
expect(backend.execute.mock.calls.at(-1)![6]).toBe(CELL_LIMIT);
|
||||
await executeConsole("a.sql", "DELETE FROM docs RETURNING body", 0, 30);
|
||||
expect(backend.execute.mock.calls.at(-1)![6]).toBeNull();
|
||||
await executeConsole("a.sql", "WITH d AS (DELETE FROM docs RETURNING body) SELECT * FROM d", 0, 59);
|
||||
expect(backend.execute.mock.calls.at(-1)![6]).toBeNull();
|
||||
});
|
||||
|
||||
it("release the cursor of a result when its tab closes, not before", async () => {
|
||||
show();
|
||||
const other: ResultTab = { ...useDatabase.getState().results[0]!, id: 2 };
|
||||
useDatabase.setState((s) => ({ results: [...s.results, other] }));
|
||||
closeResult(2);
|
||||
// The other tab still shows the same statement.
|
||||
expect(backend.release).not.toHaveBeenCalled();
|
||||
closeResult(1);
|
||||
expect(backend.release).toHaveBeenCalledExactlyOnceWith("pg", text, "public");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Cells a result page carries only the start of. The backend cuts a cell longer than
|
||||
* `CELL_LIMIT` and lists it in the result's `truncated`, so a page of wide values stays small;
|
||||
* the whole value is read again when it is needed (the grid's copy, edit and value panel, the
|
||||
* export) and kept beside the result for as long as it lives.
|
||||
*/
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { DbQueryResult } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { Cell } from "./model";
|
||||
import { readResultPage, readResultRow, type ResultTab } from "./store";
|
||||
|
||||
/** Rows with cut cells beyond which the page is read once instead of row by row. */
|
||||
const ROWWISE_LIMIT = 8;
|
||||
|
||||
const key = (row: number, col: number) => `${row}:${col}`;
|
||||
|
||||
/** The whole text of cut cells that were read, by result. */
|
||||
const whole = new WeakMap<DbQueryResult, Map<string, string>>();
|
||||
const listeners = new Set<() => void>();
|
||||
let version = 0;
|
||||
|
||||
/** Re-renders what reads the cells of results when one is loaded. */
|
||||
export function useCutCells(): number {
|
||||
return useSyncExternalStore(
|
||||
(listener) => {
|
||||
listeners.add(listener);
|
||||
return () => void listeners.delete(listener);
|
||||
},
|
||||
() => version,
|
||||
);
|
||||
}
|
||||
|
||||
/** The cells of `r` the backend cut (an older remote host sends none). */
|
||||
const cutOf = (r: DbQueryResult) => r.truncated ?? [];
|
||||
|
||||
/** The text of cell (`row`, `col`) of `r`: its whole value once read. */
|
||||
export function cellOf(r: DbQueryResult, row: number, col: number): Cell {
|
||||
return whole.get(r)?.get(key(row, col)) ?? r.rows[row]?.[col] ?? null;
|
||||
}
|
||||
|
||||
/** The cut cell (`row`, `col`) of `r` while it shows only its start; else `null`. */
|
||||
function cutCell(r: DbQueryResult, row: number, col: number) {
|
||||
if (whole.get(r)?.has(key(row, col))) return null;
|
||||
return cutOf(r).find((c) => c.row === row && c.column === col) ?? null;
|
||||
}
|
||||
|
||||
/** The whole length (UTF-16 units) of cell (`row`, `col`) of `r` while it shows only its start; else `null`. */
|
||||
export const cutLength = (r: DbQueryResult, row: number, col: number): number | null =>
|
||||
cutCell(r, row, col)?.length ?? null;
|
||||
|
||||
/** FNV-1a over the UTF-16 units of `text`, one step per unit: what the backend hashes a cut value with. */
|
||||
export function hashOf(text: string): number {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193);
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
/** Whether `r` still has a cell that shows only its start. */
|
||||
export const hasCutCells = (r: DbQueryResult): boolean =>
|
||||
cutOf(r).some((c) => !whole.get(r)?.has(key(c.row, c.column)));
|
||||
|
||||
/** The rows of `r` with the cells that were read whole. */
|
||||
export function rowsOf(r: DbQueryResult): Cell[][] {
|
||||
return r.rows.map((cells, row) => cells.map((_, col) => cellOf(r, row, col)));
|
||||
}
|
||||
|
||||
class ResultChanged extends Error {
|
||||
constructor() {
|
||||
super(tx("The result changed since this page was read. Run the query again."));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the whole cells of `fresh`, the `count` rows read again from row `at` of the page `r`,
|
||||
* once they are the rows the page showed: as many rows, every other cell the same, and each cut
|
||||
* cell a value of the length and hash the backend cut it from, starting with what the page shows.
|
||||
*/
|
||||
function adopt(r: DbQueryResult, at: number, count: number, fresh: DbQueryResult) {
|
||||
const kept = whole.get(r) ?? new Map<string, string>();
|
||||
const names = r.columns.map((c) => c.name);
|
||||
if (fresh.columns.length !== names.length || fresh.columns.some((c, i) => c.name !== names[i]))
|
||||
throw new ResultChanged();
|
||||
if (fresh.rows.length !== count || at + count > r.rows.length) throw new ResultChanged();
|
||||
const found = new Map<string, string>();
|
||||
fresh.rows.forEach((cells, i) => {
|
||||
const row = at + i;
|
||||
if (cells.length !== names.length) throw new ResultChanged();
|
||||
cells.forEach((text, col) => {
|
||||
const cut = cutCell(r, row, col);
|
||||
if (cut === null) {
|
||||
if (text !== cellOf(r, row, col)) throw new ResultChanged();
|
||||
} else if (
|
||||
text === null ||
|
||||
text.length !== cut.length ||
|
||||
hashOf(text) !== cut.hash ||
|
||||
!text.startsWith(r.rows[row]![col] ?? "")
|
||||
)
|
||||
throw new ResultChanged();
|
||||
else found.set(key(row, col), text);
|
||||
});
|
||||
});
|
||||
for (const [k, text] of found) kept.set(k, text);
|
||||
whole.set(r, kept);
|
||||
version++;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
/** Where the rows of `tab`'s page start among the rows of its whole result. */
|
||||
const firstRow = (tab: ResultTab) => (tab.page ?? 0) * (tab.pageSize ?? 0);
|
||||
|
||||
/**
|
||||
* Reads the whole values of the cut cells among `cells` of the page `tab` shows (what `adopt`
|
||||
* checks against the page); each result row comes back by itself unless many rows are involved.
|
||||
* The text of every requested cell follows, cut or not.
|
||||
*/
|
||||
export async function loadCells(tab: ResultTab, cells: ReadonlyArray<{ row: number; col: number }>): Promise<Cell[]> {
|
||||
const r = tab.outcome.result!;
|
||||
const cut = cells.filter((c) => cutLength(r, c.row, c.col) !== null);
|
||||
const rows = [...new Set(cut.map((c) => c.row))].sort((a, b) => a - b);
|
||||
if (rows.length > ROWWISE_LIMIT) adopt(r, 0, r.rows.length, await readResultPage(tab));
|
||||
else for (const row of rows) adopt(r, row, 1, await readResultRow(tab, firstRow(tab) + row));
|
||||
return cells.map((c) => cellOf(r, c.row, c.col));
|
||||
}
|
||||
|
||||
/** Reads every cut cell of the page `tab` shows (before it is exported). */
|
||||
export async function loadPage(tab: ResultTab): Promise<void> {
|
||||
const r = tab.outcome.result!;
|
||||
const cells = cutOf(r)
|
||||
.filter((c) => cutLength(r, c.row, c.column) !== null)
|
||||
.map((c) => ({ row: c.row, col: c.column }));
|
||||
if (cells.length) await loadCells(tab, cells);
|
||||
}
|
||||
@@ -453,6 +453,7 @@ describe("closing result tabs", () => {
|
||||
hasMore: false,
|
||||
elapsedMs: 1,
|
||||
executionMs: 1,
|
||||
truncated: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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, channel) => {
|
||||
return async (request, id, statements, maxRows, schema, cellLimit, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
const reply = await execute(request, id, statements, 0, maxRows, schema);
|
||||
const reply = await execute(request, id, statements, 0, maxRows, schema, cellLimit);
|
||||
if (reply.status === "error") channel.onmessage({ type: "done", error: reply.error });
|
||||
else {
|
||||
reply.data.forEach((outcome, index) => {
|
||||
|
||||
@@ -56,6 +56,7 @@ function queryOutcome(statement: SqlStatement, value: string, elapsedMs: number)
|
||||
hasMore: false,
|
||||
elapsedMs,
|
||||
executionMs: elapsedMs,
|
||||
truncated: [],
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
@@ -174,22 +175,24 @@ describe("statements in flight", () => {
|
||||
});
|
||||
let finish!: () => void;
|
||||
const gate = new Promise<void>((resolve) => (finish = resolve));
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({ type: "completed", index: 0, outcome: queryOutcome(statements[0]!, "first", 500) });
|
||||
channel.onmessage({ type: "started", index: 1 });
|
||||
await gate;
|
||||
const update = queryOutcome(statements[1]!, "", 2500);
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 1,
|
||||
outcome: { ...update, result: { ...update.result!, columns: [], rows: [], affected: 1 } },
|
||||
});
|
||||
channel.onmessage({ type: "started", index: 2 });
|
||||
channel.onmessage({ type: "completed", index: 2, outcome: queryOutcome(statements[2]!, "third", 1000) });
|
||||
channel.onmessage({ type: "done", error: null });
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({ type: "completed", index: 0, outcome: queryOutcome(statements[0]!, "first", 500) });
|
||||
channel.onmessage({ type: "started", index: 1 });
|
||||
await gate;
|
||||
const update = queryOutcome(statements[1]!, "", 2500);
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 1,
|
||||
outcome: { ...update, result: { ...update.result!, columns: [], rows: [], affected: 1 } },
|
||||
});
|
||||
channel.onmessage({ type: "started", index: 2 });
|
||||
channel.onmessage({ type: "completed", index: 2, outcome: queryOutcome(statements[2]!, "third", 1000) });
|
||||
channel.onmessage({ type: "done", error: null });
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
const cells = () => useDatabase.getState().results.map((r) => r.outcome.result?.rows[0]?.[0]);
|
||||
const highlighted = () => [...view.dom.querySelectorAll(".cm-openidea-db-executing")].map((e) => e.textContent);
|
||||
const times = () =>
|
||||
@@ -243,20 +246,22 @@ describe("statements in flight", () => {
|
||||
}));
|
||||
let cancel!: () => void;
|
||||
backend.stream.mockImplementationOnce(streamExecution(backend.execute));
|
||||
backend.stream.mockImplementationOnce(async (request, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({ type: "completed", index: 0, outcome: queryOutcome(statements[0]!, "new", 500) });
|
||||
channel.onmessage({ type: "started", index: 1 });
|
||||
await new Promise<void>((resolve) => {
|
||||
cancel = resolve;
|
||||
backend.cancel.mockImplementationOnce(async (id) => {
|
||||
expect(id).toBe(request);
|
||||
cancel();
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (request, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({ type: "completed", index: 0, outcome: queryOutcome(statements[0]!, "new", 500) });
|
||||
channel.onmessage({ type: "started", index: 1 });
|
||||
await new Promise<void>((resolve) => {
|
||||
cancel = resolve;
|
||||
backend.cancel.mockImplementationOnce(async (id) => {
|
||||
expect(id).toBe(request);
|
||||
cancel();
|
||||
});
|
||||
});
|
||||
});
|
||||
channel.onmessage({ type: "done", error: { kind: "cancelled", message: "Cancelled", data: null } });
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
channel.onmessage({ type: "done", error: { kind: "cancelled", message: "Cancelled", data: null } });
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
const ok = () => view.dom.querySelectorAll(".cm-openidea-db-run-ok");
|
||||
const error = () => view.dom.querySelectorAll(".cm-openidea-db-run-error");
|
||||
const banner = () => view.dom.querySelector(".cm-openidea-db-banner");
|
||||
|
||||
@@ -56,6 +56,7 @@ function result(id: number, title: string, path: string, sourceId: string, value
|
||||
hasMore: false,
|
||||
elapsedMs: 1,
|
||||
executionMs: 1,
|
||||
truncated: [],
|
||||
},
|
||||
error: null,
|
||||
},
|
||||
|
||||
@@ -94,6 +94,7 @@ const result = (columns: Array<{ name: string }>, rows: (string | null)[][]): Db
|
||||
hasMore: false,
|
||||
elapsedMs: 1,
|
||||
executionMs: 1,
|
||||
truncated: [],
|
||||
});
|
||||
|
||||
let nextId = 1;
|
||||
@@ -246,7 +247,7 @@ describe("editable result grid", () => {
|
||||
useDatabase.setState({ consoles: { "console.sql": "pg" }, consoleSchemas: { "console.sql": schema } });
|
||||
await executeConsole("console.sql", "SELECT * FROM users", 0, 0);
|
||||
const expected = schema || "public";
|
||||
expect(backend.execute.mock.calls.at(-1)?.at(-1)).toBe(expected);
|
||||
expect(backend.execute.mock.calls.at(-1)?.[5]).toBe(expected);
|
||||
expect(useDatabase.getState().results.at(-1)?.schema).toBe(expected);
|
||||
});
|
||||
|
||||
@@ -416,7 +417,7 @@ describe("editable result grid", () => {
|
||||
expect(backend.applyEdits).toHaveBeenCalledWith("pg", "s2", "users", [
|
||||
{ kind: "update", key: [{ column: "id", value: "1" }], values: [{ column: "name", value: "Changed" }] },
|
||||
]);
|
||||
expect(backend.execute.mock.calls.at(-1)?.at(-1)).toBe("s2");
|
||||
expect(backend.execute.mock.calls.at(-1)?.[5]).toBe("s2");
|
||||
});
|
||||
|
||||
it("preserves pending edits and shows the error when submit fails", async () => {
|
||||
@@ -811,24 +812,26 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
|
||||
pinResult(pinned, true);
|
||||
let sendDone!: () => void;
|
||||
let acknowledge!: () => void;
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
const completed = [
|
||||
{ ...result([], []), affected: 3 },
|
||||
{ ...result([], []), affected: 0 },
|
||||
result([{ name: "v" }], [["first"]]),
|
||||
];
|
||||
completed.forEach((query, index) => {
|
||||
channel.onmessage({ type: "started", index });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index,
|
||||
outcome: { statement: statements[index]!, result: query, error: null },
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
const completed = [
|
||||
{ ...result([], []), affected: 3 },
|
||||
{ ...result([], []), affected: 0 },
|
||||
result([{ name: "v" }], [["first"]]),
|
||||
];
|
||||
completed.forEach((query, index) => {
|
||||
channel.onmessage({ type: "started", index });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index,
|
||||
outcome: { statement: statements[index]!, result: query, error: null },
|
||||
});
|
||||
});
|
||||
});
|
||||
sendDone = () => channel.onmessage({ type: "done", error: null });
|
||||
await new Promise<void>((resolve) => (acknowledge = resolve));
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
sendDone = () => channel.onmessage({ type: "done", error: null });
|
||||
await new Promise<void>((resolve) => (acknowledge = resolve));
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
vi.useFakeTimers();
|
||||
const pending = runIn("a.sql", "UPDATE t SET n = 3; CREATE TABLE saved (id INT); SELECT first; SELECT missing");
|
||||
const affected = () => useDatabase.getState().output.filter((line) => line.text === "3 rows affected in 1 ms");
|
||||
@@ -871,29 +874,31 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
|
||||
useDatabase.setState({ manualCommit: new Set(["pg"]) });
|
||||
let acknowledge!: () => void;
|
||||
let sendDone!: () => void;
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0]!, result: { ...result([], []), affected: 3 }, error: null },
|
||||
});
|
||||
channel.onmessage({ type: "started", index: 1 });
|
||||
sendDone = () => {
|
||||
if (!cancelled)
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 1,
|
||||
outcome: { statement: statements[1]!, result: result([{ name: "v" }], [["actual"]]), error: null },
|
||||
});
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({
|
||||
type: "done",
|
||||
error: cancelled ? { kind: "cancelled", message: "Cancelled", data: null } : null,
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0]!, result: { ...result([], []), affected: 3 }, error: null },
|
||||
});
|
||||
};
|
||||
await new Promise<void>((resolve) => (acknowledge = resolve));
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
channel.onmessage({ type: "started", index: 1 });
|
||||
sendDone = () => {
|
||||
if (!cancelled)
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 1,
|
||||
outcome: { statement: statements[1]!, result: result([{ name: "v" }], [["actual"]]), error: null },
|
||||
});
|
||||
channel.onmessage({
|
||||
type: "done",
|
||||
error: cancelled ? { kind: "cancelled", message: "Cancelled", data: null } : null,
|
||||
});
|
||||
};
|
||||
await new Promise<void>((resolve) => (acknowledge = resolve));
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
const pending = runIn("a.sql", "UPDATE t SET n = 3; SELECT n FROM t");
|
||||
try {
|
||||
await vi.waitFor(() => expect(acknowledge).toBeTypeOf("function"));
|
||||
@@ -932,19 +937,21 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
|
||||
"keeps the completed write and reports transaction state after cancellation $label",
|
||||
async ({ started, terminal, pending }) => {
|
||||
useDatabase.setState({ manualCommit: new Set(["pg"]) });
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0]!, result: { ...result([], []), affected: 3 }, error: null },
|
||||
});
|
||||
if (started) channel.onmessage({ type: "started", index: 1 });
|
||||
const error = { kind: "cancelled", message: "Cancelled", data: null };
|
||||
if (!terminal) return { status: "error", error };
|
||||
channel.onmessage({ type: "done", error });
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
channel.onmessage({ type: "started", index: 0 });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0]!, result: { ...result([], []), affected: 3 }, error: null },
|
||||
});
|
||||
if (started) channel.onmessage({ type: "started", index: 1 });
|
||||
const error = { kind: "cancelled", message: "Cancelled", data: null };
|
||||
if (!terminal) return { status: "error", error };
|
||||
channel.onmessage({ type: "done", error });
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
await runIn("a.sql", "UPDATE t SET n = 3; SELECT n FROM t");
|
||||
const output = useDatabase.getState().output.map((line) => line.text);
|
||||
expect(output.filter((line) => line === "3 rows affected in 1 ms")).toHaveLength(1);
|
||||
@@ -960,19 +967,21 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
|
||||
const texts = Array.from({ length: 16 }, (_, i) => `SELECT ${i}`);
|
||||
const text = texts.join("; ");
|
||||
let finish!: () => void;
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
statements.forEach((statement, index) => {
|
||||
channel.onmessage({ type: "started", index });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index,
|
||||
outcome: { statement, result: result([{ name: "v" }], [[String(index)]]), error: null },
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
statements.forEach((statement, index) => {
|
||||
channel.onmessage({ type: "started", index });
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index,
|
||||
outcome: { statement, result: result([{ name: "v" }], [[String(index)]]), error: null },
|
||||
});
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => (finish = resolve));
|
||||
channel.onmessage({ type: "done", error: null });
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
await new Promise<void>((resolve) => (finish = resolve));
|
||||
channel.onmessage({ type: "done", error: null });
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
const publish = vi.fn();
|
||||
const pending = executeConsole("a.sql", text, 0, text.length, undefined, publish);
|
||||
try {
|
||||
@@ -991,19 +1000,21 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
|
||||
|
||||
it("ignores results from a superseded request after an early invocation reply", async () => {
|
||||
let stale!: () => void;
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
const emit = (event: ExecutionEvent) => channel.onmessage(event);
|
||||
emit({ type: "started", index: 0 });
|
||||
stale = () => {
|
||||
emit({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0]!, result: result([{ name: "v" }], [["stale"]]), error: null },
|
||||
});
|
||||
emit({ type: "done", error: null });
|
||||
};
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
const emit = (event: ExecutionEvent) => channel.onmessage(event);
|
||||
emit({ type: "started", index: 0 });
|
||||
stale = () => {
|
||||
emit({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0]!, result: result([{ name: "v" }], [["stale"]]), error: null },
|
||||
});
|
||||
emit({ type: "done", error: null });
|
||||
};
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
const superseded = runIn("a.sql", "SELECT stale; SELECT later");
|
||||
await vi.waitFor(() => expect(stale).toBeTypeOf("function"));
|
||||
const oldRequest = useDatabase.getState().running["a.sql"];
|
||||
@@ -1026,16 +1037,18 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
|
||||
it("syncs a lost connection reported by a superseded run", async () => {
|
||||
useDatabase.setState({ connected: new Set(["pg"]) });
|
||||
let finish!: () => void;
|
||||
backend.stream.mockImplementationOnce(async (_r, _id, statements: SqlStatement[], _max, _schema, channel) => {
|
||||
await new Promise<void>((resolve) => (finish = resolve));
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0], result: null, error: "Connection lost" },
|
||||
});
|
||||
channel.onmessage({ type: "done", error: null });
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
backend.stream.mockImplementationOnce(
|
||||
async (_r, _id, statements: SqlStatement[], _max, _schema, _limit, channel) => {
|
||||
await new Promise<void>((resolve) => (finish = resolve));
|
||||
channel.onmessage({
|
||||
type: "completed",
|
||||
index: 0,
|
||||
outcome: { statement: statements[0], result: null, error: "Connection lost" },
|
||||
});
|
||||
channel.onmessage({ type: "done", error: null });
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
);
|
||||
const older = runIn("a.sql", "SELECT old; SELECT untouched");
|
||||
try {
|
||||
await vi.waitFor(() => expect(finish).toBeTypeOf("function"));
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type DbObjectKind,
|
||||
type DbPlanNode,
|
||||
type DbSchemaObjects,
|
||||
type DbQueryResult,
|
||||
type DbStatementOutcome,
|
||||
type DbTableDetails,
|
||||
type DbTableInfo,
|
||||
@@ -75,6 +76,11 @@ const CONSOLE_SCHEMAS_KEY = "openidea.database.consoleSchemas";
|
||||
const VIEW_OPTIONS_KEY = "openidea.database.viewOptions";
|
||||
const MAX_TABS = 12;
|
||||
const RESULT_DELIVERY_TIMEOUT_MS = 15_000;
|
||||
/**
|
||||
* The longest cell text (UTF-16 units) a page of a result carries. A cut cell shows a marker
|
||||
* and its whole value is read when it is expanded, copied, exported or edited.
|
||||
*/
|
||||
export const CELL_LIMIT = 8192;
|
||||
|
||||
export interface ResultTab {
|
||||
id: number;
|
||||
@@ -301,6 +307,23 @@ export const useDatabase = create<DatabaseState>(() => ({
|
||||
pendingTx: new Set(),
|
||||
}));
|
||||
|
||||
/**
|
||||
* A result's later pages continue a cursor the backend keeps open on the server; it closes when
|
||||
* no result tab shows the statement any more (the backend also closes idle ones).
|
||||
*/
|
||||
const resultKey = (tab: ResultTab) =>
|
||||
JSON.stringify([tab.sourceId, tab.outcome.statement.text, tab.schema ?? consoleSchema(tab.path)]);
|
||||
useDatabase.subscribe((state, previous) => {
|
||||
if (state.results === previous.results && state.inline === previous.inline) return;
|
||||
const shown = [...state.results, ...state.inline];
|
||||
const keys = new Set(shown.map(resultKey));
|
||||
for (const tab of [...previous.results, ...previous.inline]) {
|
||||
if (tab.plan || keys.has(resultKey(tab))) continue;
|
||||
const schema = tab.schema ?? consoleSchema(tab.path);
|
||||
void call(commands.dbReleaseResult(tab.sourceId, tab.outcome.statement.text, schema || null)).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
export function toggleSeparateProceduresAndFunctions() {
|
||||
const separateProceduresAndFunctions = !useDatabase.getState().separateProceduresAndFunctions;
|
||||
useDatabase.setState({ separateProceduresAndFunctions });
|
||||
@@ -1209,15 +1232,18 @@ async function run(
|
||||
): Promise<DbStatementOutcome[]> {
|
||||
const current = databaseRequest(id);
|
||||
const wasConnected = useDatabase.getState().connected.has(id);
|
||||
// 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 execute = async () => {
|
||||
progress?.emit({ type: "started", index: 0 });
|
||||
const outcomes = await call(commands.dbExecute(request, id, statements, skip, maxRows, schema || null)).catch(
|
||||
(error: unknown) => {
|
||||
if (isCancelled(error)) progress?.onStatementCancelled();
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
const outcomes = await call(
|
||||
commands.dbExecute(request, id, statements, skip, maxRows, schema || null, cellLimit),
|
||||
).catch((error: unknown) => {
|
||||
if (isCancelled(error)) progress?.onStatementCancelled();
|
||||
throw error;
|
||||
});
|
||||
outcomes.forEach((outcome, index) => progress?.emit({ type: "completed", index, outcome }));
|
||||
return outcomes;
|
||||
};
|
||||
@@ -1253,7 +1279,7 @@ 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, channel));
|
||||
await call(commands.dbExecuteStream(request, id, statements, maxRows, schema || null, cellLimit, channel));
|
||||
acknowledged = true;
|
||||
waitForDelivery();
|
||||
const result = await done;
|
||||
@@ -1736,6 +1762,26 @@ export function pageable(tab: ResultTab): boolean {
|
||||
return !tab.plan && isReadOnlyQuery(tab.outcome.statement.text, sourceById(tab.sourceId)?.driver ?? "sqlite");
|
||||
}
|
||||
|
||||
/** 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)),
|
||||
);
|
||||
}
|
||||
|
||||
/** The rows of the page result tab `tab` shows, with their cells whole. */
|
||||
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)),
|
||||
);
|
||||
if (!outcome?.result) throw new Error(outcome?.error ?? "The statement returned no result");
|
||||
return outcome.result;
|
||||
}
|
||||
|
||||
/** Result tab `tabId`, in the Services view or in an editor. */
|
||||
export function findResult(tabId: number): ResultTab | undefined {
|
||||
const st = useDatabase.getState();
|
||||
|
||||
@@ -45,6 +45,7 @@ const page: DbTablePage = {
|
||||
hasMore: false,
|
||||
elapsedMs: 1,
|
||||
executionMs: 1,
|
||||
truncated: [],
|
||||
},
|
||||
details: {
|
||||
columns: [
|
||||
|
||||
@@ -3799,6 +3799,13 @@
|
||||
"Next Rows": "Next Rows",
|
||||
"Previous Columns": "Previous Columns",
|
||||
"Next Columns": "Next Columns",
|
||||
"truncated": "truncated",
|
||||
"Only the first {shown} of {total} characters are shown.": "Only the first {shown} of {total} characters are shown.",
|
||||
"Only the first {shown} of {total} characters are shown. Double-click to load the whole value.": "Only the first {shown} of {total} characters are shown. Double-click to load the whole value.",
|
||||
"Load whole value": "Load whole value",
|
||||
"Cannot read the whole value": "Cannot read the whole value",
|
||||
"Cannot read the whole values": "Cannot read the whole values",
|
||||
"The result changed since this page was read. Run the query again.": "The result changed since this page was read. Run the query again.",
|
||||
"View Options": "View Options",
|
||||
"Visible columns": "Visible columns",
|
||||
"Install Ruff to optimize imports in Python files": "Install Ruff to optimize imports in Python files",
|
||||
|
||||
@@ -10034,6 +10034,13 @@
|
||||
"Next Rows": "下一组行",
|
||||
"Previous Columns": "上一组列",
|
||||
"Next Columns": "下一组列",
|
||||
"truncated": "已截断",
|
||||
"Only the first {shown} of {total} characters are shown.": "仅显示前 {shown} 个字符,共 {total} 个。",
|
||||
"Only the first {shown} of {total} characters are shown. Double-click to load the whole value.": "仅显示前 {shown} 个字符,共 {total} 个。双击以加载完整值。",
|
||||
"Load whole value": "加载完整值",
|
||||
"Cannot read the whole value": "无法读取完整值",
|
||||
"Cannot read the whole values": "无法读取完整值",
|
||||
"The result changed since this page was read. Run the query again.": "自读取此页以来结果已更改,请重新运行查询。",
|
||||
"Install Ruff to optimize imports in Python files": "安装 Ruff 以优化 Python 文件的导入",
|
||||
"Optimize Imports (Ruff)": "优化导入(Ruff)",
|
||||
"Uses the language server or a tool such as Ruff to organize imports.": "使用语言服务器或 Ruff 等工具优化导入。",
|
||||
|
||||
@@ -46,7 +46,7 @@ describe("remote invoke", () => {
|
||||
const progress = vi.fn();
|
||||
const channel = new Channel<ExecutionEvent>(progress);
|
||||
try {
|
||||
expect(await call(commands.dbExecuteStream(1, "test-db", [], 10, null, channel))).toBeNull();
|
||||
expect(await call(commands.dbExecuteStream(1, "test-db", [], 10, null, null, channel))).toBeNull();
|
||||
expect(unregisterCallback).toHaveBeenCalledExactlyOnceWith(channel.id);
|
||||
expect(progress).toHaveBeenCalledExactlyOnceWith(done);
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Заблокувати користувача