feat(database): join tables across saved data sources in a query workspace (#6265)

Query Workspace, opened from the Database tree, runs a single SELECT joining two to eight tables from saved PostgreSQL, ClickHouse, SQLite and file-backed DuckDB sources. Typing # picks a saved source without connecting; table and key completion fetch that source's metadata, and optional aliases disambiguate duplicate names. The project host reads the projected columns and join keys on independent read-only connections, complete or failing, within per-input and total row/byte limits, and joins them in the installed DuckDB JDBC driver. Run executes the statement at the caret or the selected statements in order and Execute Script runs the editor; each statement keeps its timing, result tab and page, and Stop or the first error ends the batch.

Closes #6177

Co-authored-by: principalwater <[email protected]>
Цей коміт міститься в:
Vladislav Kuzmin authored and GitHub committed 2026-11-29 16:14:39 +08:00
1 джерело 5a92145ad9
коміт 5cbc4134a1
34 files changed
+5862 -570

No files matched your search

+136 -12
Переглянути файл
@@ -287,19 +287,56 @@ impl ClickhousePool {
}
/// `max_rows`: the rows the server may send (the skipped ones included).
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
fn request(
&self,
client: &Client,
query_id: &str,
max_rows: usize,
session: &Session,
workspace_bytes: Option<usize>,
) -> RequestBuilder {
let mut request = client
.post(self.0.endpoint.clone())
.basic_auth(&self.0.user, Some(&self.0.password))
.header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8")
.query(&self.0.settings)
.query(&[("query_id", query_id), ("default_format", FORMAT)]);
if workspace_bytes.is_some() && !session.strict_read_only {
let settings: Vec<_> = self
.0
.settings
.iter()
.filter(|(name, _)| !matches!(name.as_str(), "read_overflow_mode" | "timeout_overflow_mode"))
.collect();
request = request.query(&settings);
} else {
request = request.query(&self.0.settings);
}
if !session.strict_read_only {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
if let Some(bytes) = workspace_bytes {
request = request.query(&[
("max_result_rows", max_rows.to_string()),
("result_overflow_mode", "throw".into()),
("read_overflow_mode", "throw".into()),
("timeout_overflow_mode", "throw".into()),
]);
for (name, value) in [
("max_result_bytes", bytes),
("max_execution_time", 20),
("cancel_http_readonly_queries_on_client_close", 1),
("max_rows_to_read", 1_000_000),
("max_bytes_to_read", 268_435_456),
] {
if !self.0.settings.iter().any(|(setting, _)| setting == name) {
request = request.query(&[(name, value)]);
}
}
} else {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
}
}
if let Some(session_id) = &session.id {
request = request.query(&[("session_id", session_id.as_str()), ("session_timeout", "3600")]);
@@ -376,7 +413,8 @@ impl ClickhousePool {
));
}
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
let request =
self.request(&client, &query_id, skip.saturating_add(max_rows), session, None).body(sql.to_owned());
let started = Instant::now();
let request_error = |error: reqwest::Error| {
if error.is_timeout() && !error.is_connect() {
@@ -402,7 +440,7 @@ impl ClickhousePool {
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
});
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
let body = response.bytes().await.map_err(request_error)?;
let body = response_prefix(response).await.map_err(request_error)?;
return Err(self.server_error(status, exception_code.as_deref(), &body));
}
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
@@ -458,6 +496,66 @@ impl ClickhousePool {
}
}
/// Dedicated workspace sessions consume the response before any grid truncation or formatting.
pub(crate) async fn workspace_rows(
&self,
sql: &str,
max_rows: usize,
max_bytes: usize,
cancel: &CancellationToken,
mut consume: impl FnMut(&[u8]) -> IdeResult<()>,
) -> IdeResult<()> {
let mut slot = self.session(&self.0.session, cancel).await?;
let state = slot.as_mut().expect("session was initialized");
let mut stateless;
let session = if self.0.use_http_session {
state
} else {
stateless = state.clone();
drop(slot);
&mut stateless
};
let client = self.client()?;
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, max_rows, session, Some(max_bytes)).body(sql.to_owned());
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
let status = response.status();
let metadata = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok());
let code = metadata("X-ClickHouse-Exception-Code").map(str::to_owned);
if !status.is_success() || code.as_deref().is_some_and(|code| code != "0") {
let body = response_prefix(response).await.map_err(http_error)?;
return Err(self.server_error(status, code.as_deref(), &body));
}
if metadata("X-ClickHouse-Format").is_some_and(|format| format != FORMAT) {
return Err(IdeError::invalid("ClickHouse did not return the workspace response format"));
}
let mut received = 0;
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
received += chunk.len();
if received > max_bytes {
return Err(IdeError::invalid("Workspace input exceeds the source byte limit"));
}
consume(&chunk)?;
}
Ok(())
};
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => Err(IdeError::cancelled()),
() = tokio::time::sleep(Duration::from_secs(25)) =>
Err(IdeError::new(ErrorKind::TimedOut, "Workspace ClickHouse source read timed out")),
result = fetch => result,
};
if result.is_ok() {
session.initialized = true;
} else {
let _ = self.kill(&client, &query_id, session).await;
}
result.map_err(|e| self.redact_error(e))
}
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
let mut request = client
.post(self.0.endpoint.clone())
@@ -474,7 +572,7 @@ impl ClickhousePool {
.get("X-ClickHouse-Exception-Code")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let body = response.bytes().await.map_err(http_error)?;
let body = response_prefix(response).await.map_err(http_error)?;
if status.is_success() && !code.as_deref().is_some_and(|code| code != "0") && !body.starts_with(b"Code:") {
Ok(())
} else {
@@ -503,6 +601,17 @@ impl ClickhousePool {
}
}
async fn response_prefix(mut response: reqwest::Response) -> Result<Vec<u8>, reqwest::Error> {
const LIMIT: usize = 16_384;
let mut body = Vec::new();
while body.len() < LIMIT {
let Some(chunk) = response.chunk().await? else { break };
let remaining = LIMIT - body.len();
body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
}
Ok(body)
}
type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
@@ -1448,6 +1557,15 @@ mod tests {
#[tokio::test]
async fn stateless_queries_do_not_wait_for_a_shared_session() {
assert_stateless_requests_overlap(false).await;
}
#[tokio::test]
async fn stateless_workspace_reads_do_not_block_queries() {
assert_stateless_requests_overlap(true).await;
}
async fn assert_stateless_requests_overlap(workspace: bool) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
@@ -1465,9 +1583,15 @@ mod tests {
(first_request, second_request)
});
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let Pool::Clickhouse(pool) = Pool::connect(&source, None, None).await.unwrap() else { unreachable!() };
let cancel = CancellationToken::new();
let first = pool.execute("SELECT 1", 1, &cancel);
let first = async {
if workspace {
pool.workspace_rows("SELECT 1", 1, 1024, &cancel, |_| Ok(())).await
} else {
pool.execute("SELECT 1", 1, &cancel).await.map(drop)
}
};
let second = async {
received.await.unwrap();
pool.execute("SELECT 2", 1, &cancel).await
+65
Переглянути файл
@@ -1330,6 +1330,71 @@ impl Pool {
Ok(conn.finish_read_only(owned, result).await?.1)
}
pub(crate) async fn read_workspace_postgres(
&self,
request: &crate::workspace_input::WorkspaceInputRequest,
selection: Option<&[&str]>,
cancel: &CancellationToken,
) -> IdeResult<crate::workspace_input::WorkspaceInput> {
let Pool::Postgres(pool) = self else {
return Err(IdeError::internal("Expected a PostgreSQL workspace connection"));
};
let mut conn = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
result = pool.get() => result?,
};
let mut backend = None;
let read = async {
if conn.options.read_only == PgReadOnly::Transaction {
conn.start_read_only().await?;
} else {
sqlx::raw_sql("BEGIN READ ONLY").execute(&mut **conn).await.map_err(db_err)?;
}
let row = sqlx::raw_sql(
"SELECT pg_catalog.pg_backend_pid(), pg_catalog.current_setting('transaction_read_only') = 'on'",
)
.fetch_one(&mut **conn)
.await
.map_err(db_err)?;
backend = Some(row.try_get::<i32, _>(0).map_err(db_err)?);
if !row.try_get::<bool, _>(1).map_err(db_err)? {
return Err(IdeError::new(
ErrorKind::PermissionDenied,
"Workspace PostgreSQL transaction is not read-only",
));
}
crate::workspace_input::read_postgres(&mut conn, request, selection).await
};
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(IdeError::cancelled()),
() = tokio::time::sleep(Duration::from_secs(30)) =>
Err(IdeError::new(ErrorKind::TimedOut, "Workspace PostgreSQL source read timed out")),
result = read => result,
};
if result.is_ok() {
// Do not send a PID-based cancel once a pooler may have released this backend.
let rollback =
tokio::time::timeout(Duration::from_secs(3), sqlx::raw_sql("ROLLBACK").execute(&mut **conn)).await;
if matches!(rollback, Ok(Ok(_))) {
conn.in_transaction = false;
} else {
conn.conn.take();
}
} else {
if let Some(pid) = backend {
let _ = tokio::time::timeout(
Duration::from_secs(3),
self.cancel_query(format!("SELECT pg_catalog.pg_cancel_backend({pid})")),
)
.await;
}
conn.conn.take();
}
result
}
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
/// the statement on the server (PostgreSQL, MySQL) and drops the connection.
pub async fn execute(&self, sql: &str, max_rows: usize, cancel: &CancellationToken) -> IdeResult<QueryResult> {
+81 -4
Переглянути файл
@@ -205,6 +205,66 @@ impl DbManager {
self.record_jdbc_approval(source)
}
/// A workspace uses only the selected host driver and a fresh in-memory database.
pub(crate) async fn workspace_engine(&self, profile: &str) -> IdeResult<JdbcPool> {
let driver = self
.jdbc_drivers()?
.into_iter()
.find(|driver| {
driver.id == profile
&& driver.vendor.as_deref() == Some("duckdb")
&& driver.class_name == "org.duckdb.DuckDBDriver"
})
.ok_or_else(|| IdeError::invalid("Choose an installed DuckDB JDBC driver for the workspace"))?;
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
JdbcPool::connect(&source, None, driver, self.jdbc_registry()?.with_file_name("jdbc")).await
}
pub(crate) async fn prepare_workspace_duckdb_source(
&self,
source: &DataSource,
) -> IdeResult<WorkspaceDuckDbSource> {
let driver = self.approved_jdbc_driver(source, false)?;
if driver.vendor.as_deref() != Some("duckdb") || driver.class_name != "org.duckdb.DuckDBDriver" {
return Err(IdeError::invalid("Choose a saved DuckDB source with an installed DuckDB driver"));
}
let target = source.url.strip_prefix("jdbc:duckdb:").unwrap_or_default();
let mut parts = target.split(';');
let filename = parts.next().unwrap_or_default();
let cache = self.jdbc_registry()?.with_file_name("jdbc");
let path = cache.join("files").join(filename);
if filename.is_empty()
|| filename.starts_with([':', ' '])
|| filename.starts_with("memory:")
|| filename.starts_with("md:")
|| filename.contains("://")
|| !tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
{
return Err(IdeError::invalid("Choose an existing local DuckDB database file as the workspace source"));
}
let limits = [
("enable_external_access", "false"),
("allow_unsigned_extensions", "false"),
("autoinstall_known_extensions", "false"),
("autoload_known_extensions", "false"),
("memory_limit", "96MiB"),
("threads", "1"),
("temp_directory", ""),
("max_temp_directory_size", "0B"),
];
let protected = |name: &str| limits.iter().any(|(key, _)| name.trim().eq_ignore_ascii_case(key));
if parts.any(|option| protected(option.split('=').next().unwrap_or_default())) {
return Err(IdeError::invalid("DuckDB Workspace source URL changes a workspace read limit"));
}
let mut target = source.clone();
target.read_only = true;
target.properties.retain(|property| !protected(&property.name));
target
.properties
.extend(limits.map(|(name, value)| crate::DbProperty { name: name.into(), value: value.into() }));
Ok(WorkspaceDuckDbSource { target, driver, cache })
}
pub(crate) async fn open_pool(
&self,
source: &DataSource,
@@ -217,6 +277,14 @@ impl DbManager {
if source.driver != crate::DbDriver::Jdbc {
return crate::Pool::connect(source, password, Some(&self.root)).await;
}
let driver = self.approved_jdbc_driver(source, testing)?;
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
.map(crate::Pool::Jdbc)
}
fn approved_jdbc_driver(&self, source: &DataSource, testing: bool) -> IdeResult<DbJdbcDriver> {
if source.plugin_owner.is_some() {
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
}
@@ -225,10 +293,19 @@ impl DbManager {
if !source.vendor.is_empty() {
driver.require_vendor(&source.vendor)?;
}
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
.map(crate::Pool::Jdbc)
Ok(driver)
}
}
pub(crate) struct WorkspaceDuckDbSource {
target: DataSource,
driver: DbJdbcDriver,
cache: PathBuf,
}
impl WorkspaceDuckDbSource {
pub(crate) async fn connect(self, password: Option<&str>) -> IdeResult<JdbcPool> {
JdbcPool::connect(&self.target, password, self.driver, self.cache).await
}
}
+4
Переглянути файл
@@ -25,6 +25,8 @@ pub mod sql;
pub mod tools;
mod watch;
pub use watch::SourcesWatch;
pub mod workspace;
pub mod workspace_input;
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
@@ -378,6 +380,7 @@ pub struct DbManager {
sessions: Mutex<HashMap<String, Session>>,
/// Result pages read on from where the previous page stopped, not by running the statement again.
cursors: conn::Cursors,
workspace_run: tokio::sync::Mutex<()>,
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
/// (`None` until [`DbManager::watch_sources`]).
on_disk: Mutex<Option<Vec<DataSource>>>,
@@ -622,6 +625,7 @@ impl DbManager {
on_disk: Mutex::default(),
sessions: Mutex::default(),
cursors: conn::Cursors::default(),
workspace_run: tokio::sync::Mutex::new(()),
}
}
+579
Переглянути файл
@@ -0,0 +1,579 @@
//! A read-only equality join of explicitly selected source tables on the project host.
use crate::jdbc::JdbcPool;
use crate::workspace_input::{
self, WorkspaceInput, WorkspaceInputColumn, WorkspaceInputLimits, WorkspaceInputRequest, WorkspaceInputType,
};
use crate::{DbDriver, DbManager, QueryResult, sql};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::io::{BufWriter, Write};
use std::time::{Duration, Instant};
use tempfile::{NamedTempFile, TempPath};
const MAX_TABLES: usize = 8;
const MAX_RESULT_ROWS: usize = 100_000;
const MAX_RESULT_COLUMNS: usize = 256;
const WORKSPACE_INPUT_LIMITS: WorkspaceInputLimits =
WorkspaceInputLimits { max_rows: 100_000, max_cell_bytes: 1_048_576, max_bytes: 16_777_216 };
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinRelation")]
pub struct WorkspaceJoinRelation {
pub source_id: String,
pub database: String,
pub schema: String,
pub table: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinColumn")]
pub struct WorkspaceJoinColumn {
pub relation: u32,
pub column: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinCondition")]
pub struct WorkspaceJoinCondition {
/// The right relation is the next table in the chain.
pub left: WorkspaceJoinColumn,
pub right_column: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinProjection")]
pub struct WorkspaceJoinProjection {
pub relation: u32,
/// None expands this relation's columns in source order.
pub column: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinPlan")]
pub struct WorkspaceJoinPlan {
pub tables: Vec<WorkspaceJoinRelation>,
pub joins: Vec<WorkspaceJoinCondition>,
/// None expands all relations in FROM/JOIN order.
pub projection: Option<Vec<WorkspaceJoinProjection>>,
}
fn validate_plan(
table_count: usize,
joins: &[WorkspaceJoinCondition],
projection: Option<&[WorkspaceJoinProjection]>,
) -> IdeResult<()> {
if !(2..=MAX_TABLES).contains(&table_count) || joins.len() + 1 != table_count {
return Err(IdeError::invalid("A workspace JOIN needs 2 to 8 tables and one equality per JOIN"));
}
let valid_column = |name: &str| !name.is_empty() && name.len() <= 255 && !name.contains('\0');
for (index, link) in joins.iter().enumerate() {
if link.left.relation as usize > index || !valid_column(&link.left.column) || !valid_column(&link.right_column)
{
return Err(IdeError::invalid("Each JOIN must compare a column of its new table with an earlier table"));
}
}
if let Some(projection) = projection
&& (projection.is_empty()
|| projection.len() > MAX_RESULT_COLUMNS
|| projection.iter().any(|item| {
item.relation as usize >= table_count || item.column.as_deref().is_some_and(|name| !valid_column(name))
}))
{
return Err(IdeError::invalid("Invalid workspace SELECT columns"));
}
Ok(())
}
struct StagedTable {
path: TempPath,
longest_row: usize,
columns: Vec<WorkspaceInputColumn>,
}
impl WorkspaceInputType {
fn is_integer(self) -> bool {
use WorkspaceInputType::*;
matches!(self, Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64)
}
fn duckdb_type(self) -> String {
use WorkspaceInputType::*;
match self {
Boolean => "BOOLEAN",
Int8 => "TINYINT",
Int16 => "SMALLINT",
Int32 => "INTEGER",
Int64 => "BIGINT",
UInt8 => "UTINYINT",
UInt16 => "USMALLINT",
UInt32 => "UINTEGER",
UInt64 => "UBIGINT",
Float32 => "FLOAT",
Float64 => "DOUBLE",
Decimal { precision, scale } => return format!("DECIMAL({precision},{scale})"),
Text => "VARCHAR",
Date => "DATE",
Time => "TIME",
Timestamp => "TIMESTAMP",
TimestampTz => "TIMESTAMPTZ",
Uuid => "UUID",
}
.into()
}
}
fn stage(input: WorkspaceInput, cancel: &CancellationToken) -> IdeResult<StagedTable> {
let mut file = NamedTempFile::new()?;
let mut longest_row = 1;
{
let mut out = BufWriter::new(file.as_file_mut());
for row in input.rows {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if row.len() != input.columns.len() {
return Err(IdeError::invalid("Incomplete workspace input row"));
}
let mut bytes = row.len(); // separators and newline
for (column, cell) in row.into_iter().enumerate() {
if column > 0 {
out.write_all(b",")?;
}
bytes += 2; // quotes or the NULL marker
if let Some(value) = cell {
bytes += value.len();
out.write_all(b"\"")?;
let mut pieces = value.split('"');
out.write_all(pieces.next().unwrap_or_default().as_bytes())?;
for piece in pieces {
bytes += 1;
out.write_all(b"\"\"")?;
out.write_all(piece.as_bytes())?;
}
out.write_all(b"\"")?;
} else {
out.write_all(br"\N")?;
}
}
longest_row = longest_row.max(bytes);
out.write_all(b"\n")?;
}
out.flush()?;
}
Ok(StagedTable { path: file.into_temp_path(), longest_row, columns: input.columns })
}
impl StagedTable {
fn quoted_path(&self) -> IdeResult<String> {
self.path
.to_str()
.map(|p| sql::quote_literal(DbDriver::Jdbc, p))
.ok_or_else(|| IdeError::invalid("The workspace temporary directory needs a UTF-8 path"))
}
fn scan(&self, path: &str) -> String {
// Synthetic column names also preserve case-distinct names from the source.
let columns = self
.columns
.iter()
.enumerate()
.map(|(i, c)| format!("'c{i}':'{}'", c.data_type.duckdb_type()))
.collect::<Vec<_>>()
.join(",");
let line = self.longest_row;
// The single-threaded reader only needs one complete CSV record per buffer.
let buffer = line.max(64 * 1024);
format!(
r#"read_csv({path},columns={{{columns}}},auto_detect=false,header=false,delim=',',quote='"',escape='"',nullstr='\N',allow_quoted_nulls=false,parallel=false,max_line_size={line},buffer_size={buffer})"#
)
}
fn column(&self, name: &str) -> IdeResult<usize> {
self.columns
.iter()
.position(|c| c.name == name)
.ok_or_else(|| IdeError::invalid(format!("Unknown workspace column: {name}")))
}
}
fn staging_columns<'a>(
table_count: usize,
joins: &'a [WorkspaceJoinCondition],
projection: Option<&'a [WorkspaceJoinProjection]>,
) -> Vec<Option<Vec<&'a str>>> {
let Some(projection) = projection else {
return vec![None; table_count];
};
let mut columns: Vec<Option<Vec<&str>>> = vec![Some(Vec::new()); table_count];
for item in projection {
let selected = &mut columns[item.relation as usize];
match (&item.column, selected) {
(Some(name), Some(selected)) => selected.push(name),
(None, selected) => *selected = None,
_ => {}
}
}
for (index, link) in joins.iter().enumerate() {
if let Some(selected) = &mut columns[link.left.relation as usize] {
selected.push(&link.left.column);
}
if let Some(selected) = &mut columns[index + 1] {
selected.push(&link.right_column);
}
}
for selected in columns.iter_mut().flatten() {
selected.sort_unstable();
selected.dedup();
}
columns
}
fn result_projection(
tables: &[StagedTable],
selection: Option<&[WorkspaceJoinProjection]>,
) -> IdeResult<Vec<(usize, usize)>> {
let mut fields = Vec::new();
match selection {
Some(selection) => {
for item in selection {
let relation = item.relation as usize;
let table = &tables[relation];
match &item.column {
Some(name) => fields.push((relation, table.column(name)?)),
None => fields.extend((0..table.columns.len()).map(|column| (relation, column))),
}
}
}
None => {
for (relation, table) in tables.iter().enumerate() {
fields.extend((0..table.columns.len()).map(|column| (relation, column)));
}
}
}
if fields.len() > MAX_RESULT_COLUMNS {
return Err(IdeError::invalid("Workspace result exceeds 256 columns"));
}
Ok(fields)
}
async fn join(
engine: &JdbcPool,
tables: &[StagedTable],
joins: &[WorkspaceJoinCondition],
selection: Option<&[WorkspaceJoinProjection]>,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
use std::fmt::Write as _;
let fields = result_projection(tables, selection)?;
let names = fields.iter().map(|(relation, column)| format!("r{relation}.c{column}")).collect::<Vec<_>>().join(", ");
let paths = tables.iter().map(StagedTable::quoted_path).collect::<IdeResult<Vec<_>>>()?;
let mut query = format!("SELECT {names} FROM {} r0", tables[0].scan(&paths[0]));
for (index, condition) in joins.iter().enumerate() {
let left_relation = condition.left.relation as usize;
let right_relation = index + 1;
let left = &tables[left_relation];
let right = &tables[right_relation];
let li = left.column(&condition.left.column)?;
let ri = right.column(&condition.right_column)?;
let (a, b) = (left.columns[li].data_type, right.columns[ri].data_type);
// DuckDB compares mixed integer widths and signs exactly, up to BIGINT against UBIGINT.
if a != b && !(a.is_integer() && b.is_integer()) {
return Err(IdeError::invalid("Choose integer join columns or columns of the same type and precision"));
}
write!(
query,
" INNER JOIN {} r{right_relation} ON r{left_relation}.c{li}=r{right_relation}.c{ri}",
right.scan(&paths[right_relation]),
)
.unwrap();
}
write!(query, " LIMIT {}", MAX_RESULT_ROWS + 1).unwrap();
for setting in [
"SET threads=1",
"SET memory_limit='96MiB'",
"SET temp_directory=''",
"SET max_temp_directory_size='0B'",
&format!("SET allowed_paths=[{}]", paths.join(",")),
"SET enable_external_access=false",
"SET lock_configuration=true",
] {
engine.query(setting, 0, 0, cancel).await?;
}
let mut result = engine.query(&query, 0, MAX_RESULT_ROWS, cancel).await?;
if result.has_more {
return Err(IdeError::invalid("Workspace result exceeds 100,000 rows"));
}
if result.columns.len() != fields.len() {
return Err(IdeError::invalid("Unexpected workspace result columns"));
}
for (display, (relation, column)) in result.columns.iter_mut().zip(fields) {
display.name.clone_from(&tables[relation].columns[column].name);
}
result.statement.clear();
Ok(result)
}
#[cfg(test)]
fn two_table_join(keys: [&str; 2]) -> WorkspaceJoinCondition {
WorkspaceJoinCondition {
left: WorkspaceJoinColumn { relation: 0, column: keys[0].into() },
right_column: keys[1].into(),
}
}
impl DbManager {
#[cfg(test)]
pub(crate) async fn workspace_join_pair_for_test(
&self,
driver: &str,
tables: [&WorkspaceInputRequest; 2],
keys: [&str; 2],
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let joins = [two_table_join(keys)];
validate_plan(tables.len(), &joins, None)?;
self.execute_workspace_join(driver, &tables, &joins, None, cancel).await
}
/// The caller retains the bounded result for paging. Reading another page never reruns the sources.
pub async fn workspace_join(
&self,
driver: &str,
plan: WorkspaceJoinPlan,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
validate_plan(plan.tables.len(), &plan.joins, plan.projection.as_deref())?;
let tables: Vec<_> = plan
.tables
.into_iter()
.map(|table| WorkspaceInputRequest {
source_id: table.source_id,
database: table.database,
schema: table.schema,
table: table.table,
limits: WORKSPACE_INPUT_LIMITS,
})
.collect();
let tables: Vec<_> = tables.iter().collect();
self.execute_workspace_join(driver, &tables, &plan.joins, plan.projection.as_deref(), cancel).await
}
async fn execute_workspace_join(
&self,
driver: &str,
tables: &[&WorkspaceInputRequest],
joins: &[WorkspaceJoinCondition],
projection: Option<&[WorkspaceJoinProjection]>,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let _run =
self.workspace_run.try_lock().map_err(|_| IdeError::invalid("A workspace query is already running"))?;
let start = Instant::now();
let child = cancel.child_token();
let run = async {
let cancel = &child;
let mut prepared = Vec::with_capacity(tables.len());
for table in tables {
let input = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
input = workspace_input::prepare_table(self, table) => input?,
};
prepared.push(input);
}
let selection = staging_columns(tables.len(), joins, projection);
let mut staged = Vec::with_capacity(tables.len());
let engine = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
engine = self.workspace_engine(driver) => engine?,
};
let result = async {
let mut remaining_rows = 200_000;
let mut remaining_bytes = 32 * 1024 * 1024;
for (mut table, columns) in prepared.into_iter().zip(&selection) {
let limits = &mut table.request.limits;
limits.max_rows = limits.max_rows.min(remaining_rows);
limits.max_bytes = limits.max_bytes.min(remaining_bytes);
let input = workspace_input::read_prepared_table(self, table, columns.as_deref(), cancel).await?;
remaining_rows -= input.rows.len();
remaining_bytes -= input.bytes;
let cancellation = cancel.clone();
let table = tokio::task::spawn_blocking(move || stage(input, &cancellation))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
staged.push(table);
}
join(&engine, &staged, joins, projection, cancel).await
}
.await;
// Windows cannot remove a staged file while the JDBC process still has it open.
engine.close().await;
drop(staged);
let mut result = result?;
result.elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
Ok(result)
};
tokio::pin!(run);
let stopped = tokio::select! {
biased;
() = cancel.cancelled() => IdeError::cancelled(),
result = &mut run => return result,
() = tokio::time::sleep(Duration::from_secs(90)) => IdeError::new(ide_core::error::ErrorKind::TimedOut, "Workspace query timed out"),
};
child.cancel();
// Let the source or JDBC bridge deliver cancellation before dropping its connection.
let _ = tokio::time::timeout(Duration::from_secs(15), run).await;
Err(stopped)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DbJdbcDriver;
fn input(values: &[(&str, Option<&str>)]) -> WorkspaceInput {
WorkspaceInput {
columns: vec![
WorkspaceInputColumn {
name: "key".into(),
data_type: WorkspaceInputType::Decimal { precision: 32, scale: 6 },
},
WorkspaceInputColumn { name: "text".into(), data_type: WorkspaceInputType::Text },
],
rows: values.iter().map(|(k, v)| vec![Some(k.to_string()), v.map(str::to_owned)]).collect(),
bytes: 0,
}
}
#[test]
fn workspace_join_chain_links_must_target_an_earlier_table() -> IdeResult<()> {
let first = two_table_join(["key", "key"]);
let second = two_table_join(["key", "id"]);
let links = [first, second];
validate_plan(3, &links, None)?;
let over_limit: Vec<_> = (0..8).map(|_| two_table_join(["key", "key"])).collect();
assert!(validate_plan(9, &over_limit, None).is_err());
validate_plan(8, &over_limit[..7], None)?;
assert!(validate_plan(4, &links, None).is_err());
assert!(validate_plan(3, &links, Some(&[])).is_err());
let invalid = WorkspaceJoinProjection { relation: 3, column: None };
assert!(validate_plan(3, &links, Some(&[invalid])).is_err());
let mut links = links;
links[0].left.relation = 1;
assert!(validate_plan(3, &links, None).is_err());
Ok(())
}
#[test]
fn staging_preserves_null_and_csv_text_and_removes_the_file_on_drop() -> IdeResult<()> {
let cancel = CancellationToken::new();
let table = stage(input(&[("1", None), ("2", Some("")), ("3", Some("a,\"b\"\nc"))]), &cancel)?;
let path = table.path.to_path_buf();
assert_eq!(std::fs::read_to_string(&path)?, "\"1\",\\N\n\"2\",\"\"\n\"3\",\"a,\"\"b\"\"\nc\"\n");
drop(table);
assert!(!path.exists());
cancel.cancel();
assert!(stage(input(&[("1", None)]), &cancel).is_err());
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
async fn workspace_engine_joins_exact_keys_nulls_and_empty_inputs() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let root = tmp.path();
let db = DbManager::new(
root.join("project"),
root.join("passwords"),
root.join("history"),
std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh"))),
)
.with_global_sources(root.join("global"));
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("driver fixture")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})?;
let cancel = CancellationToken::new();
let mut signed = input(&[("-1", None), ("9007199254740993", None), ("9223372036854775807", None)]);
signed.columns[0].data_type = WorkspaceInputType::Int64;
let mut unsigned = input(&[
("18446744073709551615", None),
("9007199254740992", None),
("9007199254740993", None),
("9223372036854775807", None),
]);
unsigned.columns[0].data_type = WorkspaceInputType::UInt64;
let tables = [stage(signed, &cancel)?, stage(unsigned, &cancel)?];
let engine = db.workspace_engine("duck").await?;
let output = join(&engine, &tables, &[two_table_join(["key", "key"])], None, &cancel).await?;
let mut matches: Vec<_> = output.rows.iter().map(|row| (row[0].as_deref(), row[2].as_deref())).collect();
matches.sort_unstable();
assert_eq!(
matches,
[
(Some("9007199254740993"), Some("9007199254740993")),
(Some("9223372036854775807"), Some("9223372036854775807")),
]
);
engine.close().await;
let wide = "a,\n\"b\"".repeat(32 * 1024);
let left = stage(input(&[("0", None), ("1", Some(&wide)), ("2", Some("short"))]), &cancel)?;
let right = stage(input(&[("1", Some(&wide))]), &cancel)?;
let engine = db.workspace_engine("duck").await?;
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0][1].as_deref(), Some(wide.as_str()));
assert_eq!(output.rows[0][3].as_deref(), Some(wide.as_str()));
engine.close().await;
for empty in [false, true] {
let left =
stage(input(&[("9007199254740993.000001", None), ("9007199254740993.000002", Some(""))]), &cancel)?;
let mut right =
input(&[("9007199254740993.000001", Some("a,\"b\"\nc")), ("9007199254740993.000002", Some(r"\N"))]);
if empty {
right.rows.clear();
}
let engine = db.workspace_engine("duck").await?;
let right = stage(right, &cancel)?;
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
assert_eq!(
output.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
["key", "text", "key", "text"]
);
let mut rows = output.rows;
rows.sort();
if empty {
assert!(rows.is_empty());
} else {
assert_eq!(rows.len(), 2);
assert_eq!(
rows[0],
[
Some("9007199254740993.000001".into()),
None,
Some("9007199254740993.000001".into()),
Some("a,\"b\"\nc".into())
]
);
assert_eq!(
rows[1],
[
Some("9007199254740993.000002".into()),
Some("".into()),
Some("9007199254740993.000002".into()),
Some(r"\N".into())
]
);
}
engine.close().await;
}
Ok(())
}
}
File diff suppressed because it is too large. Load diff
+134
Переглянути файл
@@ -0,0 +1,134 @@
#!/usr/bin/env bash
# Requires Docker, curl and Cargo. To exercise the JOIN and its cancellation as well
# as source reads, install Java 17+ and set DUCKDB_JDBC_JAR to an absolute JAR path.
# Usage: bash crates/ide-db/tests/fixtures/workspace.sh [command args...]
set -euo pipefail
cd "$(dirname "$0")/../../../.."
fixtures=$(mktemp -d "${TMPDIR:-/tmp}/openidea-workspace.XXXXXXXX")
pg=
ch=
cleanup() {
if [[ -n "$ch" ]]; then docker stop -t 2 "$ch" >/dev/null || true; fi
if [[ -n "$pg" ]]; then docker stop -t 2 "$pg" >/dev/null || true; fi
rm -f "$fixtures/users.xml"
rmdir "$fixtures"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
cat > "$fixtures/users.xml" <<'XML'
<clickhouse>
<profiles>
<workspace_strict>
<readonly>1</readonly>
<max_threads>1</max_threads>
<max_memory_usage>134217728</max_memory_usage>
<max_rows_to_read>100000</max_rows_to_read>
<max_execution_time>20</max_execution_time>
</workspace_strict>
<workspace_break>
<readonly>1</readonly>
<result_overflow_mode>break</result_overflow_mode>
</workspace_break>
<workspace_cap>
<readonly>1</readonly>
<max_result_rows>2</max_result_rows>
</workspace_cap>
</profiles>
<users>
<fixture_writer>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>default</profile>
<quota>default</quota>
</fixture_writer>
<fixture_strict>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_strict</profile>
<quota>default</quota>
</fixture_strict>
<fixture_break>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_break</profile>
<quota>default</quota>
</fixture_break>
<fixture_cap>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_cap</profile>
<quota>default</quota>
</fixture_cap>
</users>
</clickhouse>
XML
chmod 644 "$fixtures/users.xml"
pg=$(docker run --rm -d -p 127.0.0.1::5432 --cpus 1 --memory 320m \
--tmpfs /var/lib/postgresql/data:rw,size=128m \
-e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine)
ch=$(docker run --rm -d -p 127.0.0.1::8123 --cpus 1 --memory 1536m \
--tmpfs /var/lib/clickhouse --tmpfs /var/log/clickhouse-server \
--mount "type=bind,source=$fixtures/users.xml,target=/etc/clickhouse-server/users.d/workspace-fixture.xml,readonly" \
clickhouse/clickhouse-server:25.8.12.129)
WORKSPACE_PG_PORT=$(docker port "$pg" 5432/tcp | sed 's/^127\.0\.0\.1://')
WORKSPACE_CH_PORT=$(docker port "$ch" 8123/tcp | sed 's/^127\.0\.0\.1://')
export WORKSPACE_PG_PORT WORKSPACE_CH_PORT
ch_http="http://127.0.0.1:$WORKSPACE_CH_PORT"
ready() {
for ((attempt = 0; attempt < 45; ++attempt)); do
if "$@" >/dev/null 2>&1; then return 0; fi
sleep 1
done
printf 'Workspace fixture did not become ready: %s\n' "$1" >&2
return 1
}
ready docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres
ready curl -fsS --max-time 1 "$ch_http/ping"
docker exec -i "$pg" psql -h 127.0.0.1 -U postgres -Xq -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE "exact data" ("exact key" numeric(32,6), id bigint, ts timestamp(6) with time zone, label text);
INSERT INTO "exact data" VALUES
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456+03', E'a,b"c\nd'),
(100000000000000000002.000001, 9007199254740994, NULL, ''),
(NULL, 9007199254740995, NULL, NULL);
CREATE TABLE "empty data" (LIKE "exact data");
CREATE TABLE "unsupported data" (payload jsonb);
CREATE VIEW "fixture view" AS SELECT * FROM "exact data";
SQL
ch_sql() {
curl -fsS --max-time 5 --user fixture_writer: --data-binary "$1" "$ch_http/"
}
ch_sql "CREATE TABLE default.\"exact data\" (
\"exact key\" Nullable(Decimal(32,6)), id Int64, ts Nullable(DateTime64(6, 'Europe/Moscow')), label Nullable(String)
) ENGINE=Memory"
ch_sql "INSERT INTO default.\"exact data\" VALUES
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456', 'a,b\"c\\nd'),
(100000000000000000002.000001, 9007199254740994, NULL, ''),
(NULL, 9007199254740995, NULL, NULL)"
ch_sql 'CREATE TABLE default."empty data" AS default."exact data" ENGINE=Memory'
ch_sql 'CREATE TABLE default."unsupported data" (payload Array(String)) ENGINE=Memory'
ch_sql 'CREATE VIEW default."fixture view" AS SELECT * FROM default."exact data"'
ch_sql 'CREATE TABLE default."unsigned data" (id UInt64) ENGINE=Memory'
ch_sql 'INSERT INTO default."unsigned data" VALUES (9007199254740992), (9007199254740993), (18446744073709551615)'
ch_sql 'CREATE TABLE default."overflow data" (id Int64) ENGINE=Memory'
ch_sql 'INSERT INTO default."overflow data" VALUES (1), (2), (3), (4), (5)'
export WORKSPACE_CH_USER=fixture_writer
if (( $# > 0 )); then
"$@"
else
test_name=workspace_input::tests::native_workspace_sources_are_exact_and_fail_on_limits
cargo test --locked -p ide-db --lib "$test_name" -- --ignored
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib "$test_name" -- --ignored
cargo test --locked -p ide-db --lib clickhouse_workspace_refuses_truncated_reads -- --ignored
if [[ -n "${DUCKDB_JDBC_JAR:-}" ]]; then
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib workspace_join_chains_four_live_engines -- --ignored
fi
fi
+28 -23
Переглянути файл
@@ -432,34 +432,39 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
};
let cancel = CancellationToken::new();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
for url in ["jdbc:duckdb:", "jdbc:duckdb:memory:default"] {
source.url = url.into();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(
db.execute("test", "select id from session_items", 1, &cancel).await?.rows,
[vec![Some("42".into())]]
);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
}
source.read_only = true;
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:", "jdbc:duckdb:memory:default"] {
source.url = url.into();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
+9 -2
Переглянути файл
@@ -404,12 +404,19 @@ impl Host {
self.mcp_agent_runs.forget_window(window);
self.debugger.forget_breakpoints(self.owner_window(window));
self.external_logs.write().remove(self.owner_window(window));
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
let owner = self.owner_window(window);
let (project, requests) = {
// A request registering after the drain must not resolve the old project.
let mut project_requests = self.project_requests.write();
let mut projects = self.projects.write();
(projects.remove(window), project_requests.remove(owner).unwrap_or_default())
};
for request in requests {
self.cancel_request(request);
}
// After the cancels: a capture or open still running then discards what it registers.
ops::heap::close_window_snapshots(self, window);
let project = self.projects.write().remove(window)?;
let project = project?;
project.closed.cancel();
if let Some(plugins) = self.plugin_host() {
if self.windows_for_root(&project.root).is_empty() {
+135
Переглянути файл
@@ -7,6 +7,7 @@ use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::workspace::WorkspaceJoinPlan;
use ide_db::{
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
@@ -15,6 +16,27 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
#[command(trust = trusted)]
pub async fn db_workspace_join(
host: &Host,
window: &str,
request: RequestId,
driver: String,
plan: WorkspaceJoinPlan,
) -> IdeResult<QueryResult> {
let cancel = host.begin_project_request(window, request);
let result = async {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let db = host.project(window)?.db.clone();
db.workspace_join(&driver, plan, &cancel).await
}
.await;
host.end_request(request);
result
}
/// One statement of a console run.
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -840,6 +862,7 @@ pub async fn server_version(host: &Host, window: &str, id: &str) -> IdeResult<u3
ide_command::domain!(
db:
db_apply_edits,
db_workspace_join,
db_completion,
db_connect,
db_connected,
@@ -924,6 +947,118 @@ mod tests {
host
}
fn workspace_test_plan() -> WorkspaceJoinPlan {
use ide_db::workspace::{WorkspaceJoinColumn, WorkspaceJoinCondition, WorkspaceJoinRelation};
let relation = |id: &str| WorkspaceJoinRelation {
source_id: id.into(),
database: "default".into(),
schema: "default".into(),
table: "items".into(),
};
WorkspaceJoinPlan {
tables: vec![relation("left"), relation("right")],
joins: vec![WorkspaceJoinCondition {
left: WorkspaceJoinColumn { relation: 0, column: "id".into() },
right_column: "id".into(),
}],
projection: None,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_join_respects_an_early_cancel() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let request = RequestId(1);
host.cancel_request(request);
let error = db_workspace_join(&host, "main", request, "no driver installed".into(), workspace_test_plan())
.await
.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_join_cannot_resolve_a_project_after_its_requests_are_drained() {
use std::time::{Duration, Instant};
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let active = host.begin_project_request(window, RequestId(1));
std::thread::scope(|threads| {
// Hold close at heap cleanup, which follows cancellation of registered requests.
let heap = host.heap_windows.lock();
let close = threads.spawn(|| host.close_project_detached(window));
let deadline = Instant::now() + Duration::from_secs(3);
while !active.is_cancelled() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
let drained = active.is_cancelled();
let detached = host.project(window).is_err();
drop(heap);
close.join().unwrap();
assert!(drained, "close did not reach the cancellation step");
assert!(detached, "close drained its requests while the old project was still available");
});
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
async fn workspace_join_stops_when_its_project_closes() {
use std::time::Duration;
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let sources = ["left", "right"].map(|id| DataSource {
id: id.into(),
name: format!("ClickHouse fixture {id}"),
driver: DbDriver::Clickhouse,
host: "127.0.0.1".into(),
port: Some(listener.local_addr().unwrap().port()),
..Default::default()
});
db_save_sources(&host, window, sources.into()).await.unwrap();
host.project(window)
.unwrap()
.db
.save_jdbc_driver(ide_db::DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("official JDBC fixture")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})
.unwrap();
for (request, close_project) in [(RequestId(2), false), (RequestId(3), true)] {
let join = db_workspace_join(&host, window, request, "duck".into(), workspace_test_plan());
tokio::pin!(join);
// Accept the source connection and leave it open without replying.
let (socket, _) = tokio::select! {
result = &mut join => panic!("workspace ended before reaching the source: {result:?}"),
peer = tokio::time::timeout(Duration::from_secs(15), listener.accept()) => peer.unwrap().unwrap(),
};
if close_project {
host.close_project_detached(window);
} else {
host.cancel_request(request);
}
let stopped = tokio::time::timeout(Duration::from_secs(3), &mut join).await;
if stopped.is_err() {
host.cancel_request(request);
let _ = tokio::time::timeout(Duration::from_secs(5), &mut join).await;
}
let error = stopped.expect("workspace JOIN did not stop after cancellation").unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
assert!(!host.project_requests.read().values().flatten().any(|entry| *entry == request));
drop(socket);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires a disposable loopback PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT"]
async fn postgres_console_commands_keep_commit_result_reads_and_release_scoped() {
+20
Переглянути файл
@@ -209,6 +209,26 @@ Closing a selected result activates its left neighbor, or its right neighbor if
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
## Join tables across data sources
In a trusted project, open **Query Workspace** in the Database tree. Type `#` to see saved PostgreSQL and ClickHouse connections, SQLite files and DuckDB JDBC files. Choose a source and type `.` to complete a table. If two connections share a name, give them distinct names under **Workspace Settings › SQL aliases**. The workspace uses an [installed DuckDB JDBC driver](#duckdb) on the project host.
```sql
SELECT a.id, a.join_key, g.region, t.channel
FROM #accounts.public.customers AS a
JOIN #events.events.purchases AS e ON a.id = e.customer_id
JOIN #geo.main.region_map AS g ON a.id = g.id
JOIN #labels.main.tags AS t ON g.zone = t.zone;
```
A SELECT can join two to eight tables. Each inner JOIN compares one column from its table with one column from an earlier table. Select individual columns, `alias.*`, or `*`. Specifying columns limits the source reads to those columns and the JOIN keys. Integer keys can have different sizes and signs. Other key types must match, including precision and scale for decimals.
Press **⌘Enter** (macOS) or **Ctrl+Enter** (Windows and Linux) to run the statement at the caret. Select several complete statements to run them in order, or use **Execute Script** for the whole editor. Each completed statement gets its own elapsed time and result tab. You can stop a batch and page through the completed results.
Each statement reads its inputs through independent read-only connections and joins them in a fresh in-memory DuckDB on the project host. Temporary staging files are removed when the run ends. A source with a startup script is ineligible. To keep temporary tables between statements in a regular console, create a [DuckDB data source](#duckdb) and select **In memory**.
Each input allows up to 100,000 rows, 128 columns, 16 MiB of data and 1 MiB per value. Combined inputs allow up to 200,000 rows and 32 MiB per statement. A result allows up to 100,000 rows, 256 columns and a 16 MiB JDBC reply. If a limit is exceeded, the statement fails and the batch stops.
## Export and import
The export button offers **Export Data…** and quick copies: **Copy as CSV**, **Copy as TSV**, **Copy as JSON**, **Copy as SQL Inserts**, **Copy as Markdown** and **Copy as One-Row**. The **Export Data** dialog adds **Transpose**, column and row headers, a preview, **Copy to Clipboard** and **Export to File**. Export covers the rows that are loaded (the current page).
+20
Переглянути файл
@@ -208,6 +208,26 @@ FROM sales_archive.main.orders;
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
## 跨数据源联接表
在受信任的项目中,从数据库树打开**查询工作区**。输入 `#` 可查看已保存的 PostgreSQL 和 ClickHouse 连接、SQLite 文件及 DuckDB JDBC 文件。选定数据源后,输入 `.` 可补全表名。如果两个连接重名,可在**工作区设置 › SQL 别名**中分别指定别名。工作区使用项目主机上[已安装的 DuckDB JDBC 驱动](#duckdb)。
```sql
SELECT a.id, a.join_key, g.region, t.channel
FROM #accounts.public.customers AS a
JOIN #events.events.purchases AS e ON a.id = e.customer_id
JOIN #geo.main.region_map AS g ON a.id = g.id
JOIN #labels.main.tags AS t ON g.zone = t.zone;
```
一条 SELECT 可以联接两到八张表。每个内联接的条件是该表的一列与先前引入的某张表的一列相等。可以指定要返回的列,也可以使用 `alias.*` 或 `*`。指定列时,只从源表读取这些列和联接键。整数键允许位宽和符号不同。其他类型的键必须匹配,十进制数的精度和小数位数也要一致。
按 **⌘Enter**(macOS)或 **Ctrl+Enter**(Windows 和 Linux)运行光标所在的语句。选中多条完整语句可依次运行。也可以使用**执行脚本**运行整个编辑器中的语句。每条已完成的语句都有独立的耗时和结果标签页。停止批次后,仍可翻页查看已完成的结果。
每条语句通过独立的只读连接读取源表,并在项目主机上的临时内存 DuckDB 中执行联接。运行结束时会删除暂存文件。配置了启动脚本的数据源不可用。要在普通控制台中跨语句保留临时表,请创建 [DuckDB 数据源](#duckdb)并选择**内存**。
每个输入最多允许 100,000 行、128 列和 16 MiB 数据,单个值上限为 1 MiB。每条语句的所有输入合计最多允许 200,000 行和 32 MiB。结果最多允许 100,000 行、256 列,JDBC 响应上限为 16 MiB。超出限制时,该语句会报错,批次随即停止。
## 导出与导入
导出按钮提供 **导出数据…** 以及快速复制:**Copy as CSV**、**Copy as TSV**、**Copy as JSON**、**Copy as SQL Inserts**、**Copy as Markdown** 和 **Copy as One-Row**。**导出数据** 对话框还支持 **转置**、列标题和行标题、预览、**复制到剪贴板** 和 **导出到文件**。导出范围是已加载的行(当前页)。
+766
Переглянути файл
@@ -0,0 +1,766 @@
import type { Locator, Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function setupWorkspace(page: Page, options: { multipleDrivers?: boolean; fullNames?: boolean } = {}) {
await stubDesktop(page);
await page.evaluate(async ({ fullNames, multipleDrivers }) => {
const store = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ store);
const sources = [
{ id: "accounts", name: fullNames ? "Accounts · PostgreSQL" : "accounts", driver: "postgres" },
{ id: "events", name: fullNames ? "Events · ClickHouse" : "events", driver: "clickhouse" },
];
const table = (schema: string, name: string, ...keys: string[]) => ({
schema,
name,
kind: "table",
columns: keys.map((name) => ({
name,
dataType: "BIGINT",
nullable: false,
primaryKey: false,
hasDefault: false,
})),
});
const completion = {
accounts: {
defaultSchema: "public",
tables: [
table("public", "customers", "id", "join_key"),
table("legacy", "customers", "archived_id"),
{ ...table("public", "customers_view"), kind: "view" },
],
foreignKeys: [],
},
events: {
defaultSchema: "events",
tables: [table("events", "purchases", "customer_id", "join_key")],
foreignKeys: [],
},
};
useDatabase.setState({ sources });
Object.assign(window.__ipc.handlers, {
db_sources: () => sources,
db_connected: () => [],
db_completion: ({ id }: { id: keyof typeof completion }) => completion[id],
db_jdbc_drivers: () =>
[
{ id: "duck", name: "DuckDB JDBC" },
{ id: "duck-local", name: "DuckDB Local" },
]
.slice(0, multipleDrivers ? 2 : 1)
.map((driver) => ({
...driver,
className: "org.duckdb.DuckDBDriver",
vendor: "duckdb",
jars: [],
urlTemplate: "jdbc:duckdb:",
})),
db_workspace_join: () => ({
statement: "",
columns: [
{ name: "id", typeName: "BIGINT" },
{ name: "customer", typeName: "VARCHAR" },
{ name: "customer_id", typeName: "BIGINT" },
{ name: "amount", typeName: "DECIMAL(32,6)" },
{ name: "note", typeName: "VARCHAR" },
],
rows: Array.from({ length: 501 }, (_, i) => {
const id = (9_007_199_254_740_993n + BigInt(i)).toString();
return [
id,
i === 500 ? "Last customer" : "Customer " + (i + 1),
id,
"123456789012345678.000001",
i === 0 ? null : "",
];
}),
hasMore: false,
affected: null,
elapsedMs: 42,
executionMs: null,
truncated: [],
}),
});
}, options);
}
async function openWorkspace(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("db.queryWorkspace");
});
return page.getByRole("region", { name: "Query Workspace" });
}
const SQL = "SELECT * FROM #accounts.public.customers a JOIN #events.events.purchases b ON a.id = b.customer_id";
async function saveWorkspaceDraft(page: Page, draft: Record<string, unknown>) {
await page.evaluate(async (draft) => {
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const root = useProject.getState().project.root;
localStorage.setItem("openidea.db-workspace:" + root, JSON.stringify(draft));
}, draft);
}
async function showDatabase(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("db.showToolWindow");
});
return page.getByRole("tree", { name: "Data sources" }).getByRole("treeitem", { name: "Query Workspace" });
}
async function settingsFor(page: Page, workspace: Locator) {
await workspace
.getByRole("toolbar", { name: "Workspace actions" })
.getByRole("button", { name: /Workspace Settings…/ })
.click();
return page.getByRole("dialog", { name: "Workspace Settings" });
}
test("joins four saved data sources without registering them in the workspace", async ({ workbench: page }, info) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
{ id: "accounts", name: "accounts", driver: "postgres" },
{ id: "events", name: "events", driver: "clickhouse" },
{ id: "warehouse", name: "warehouse", driver: "jdbc", vendor: "duckdb", url: "jdbc:duckdb:/warehouse.duckdb" },
{ id: "lookup", name: "lookup", driver: "sqlite", file: "lookup.sqlite" },
{ id: "memory", name: "memory", driver: "jdbc", vendor: "duckdb", url: "jdbc:duckdb:memory:session" },
{ id: "arbitrary", name: "arbitrary", driver: "jdbc", url: "jdbc:other:anywhere" },
{ id: "startup", name: "startup", driver: "postgres", options: { startupScript: "SELECT 1" } },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
const reply = window.__ipc.handlers.db_workspace_join;
window.__ipc.handlers.db_workspace_join = (args) => ({
...(reply?.(args) as object),
columns: [
{ name: "id", typeName: "BIGINT" },
{ name: "label", typeName: "VARCHAR" },
],
rows: [
["9007199254740993", "Retail"],
["9007199254740994", "Wholesale"],
],
});
});
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.focus();
await page.screenshot({ path: info.outputPath("workspace-four-source-empty.png"), animations: "disabled" });
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
await page.keyboard.insertText("SELECT * FROM ");
await page.keyboard.insertText("#");
for (const name of ["accounts", "events", "warehouse", "lookup"]) {
await expect(page.getByRole("option", { name: new RegExp(`^#${name}`) })).toBeVisible();
}
await expect(page.getByRole("option", { name: /^#(memory|arbitrary|startup)/ })).toHaveCount(0);
await page.screenshot({ path: info.outputPath("workspace-four-source-completion.png"), animations: "disabled" });
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
await editor.press("Escape");
await editor.press("Meta+A");
await page.keyboard.insertText(
[
"SELECT a.id, l.label FROM #accounts.public.customers AS a",
"JOIN #events.events.purchases AS e ON a.id=e.customer_id",
"JOIN #warehouse.main.items AS w ON e.customer_id=w.id",
"JOIN #lookup.main.labels AS l ON l.id=w.id;",
].join("\n"),
);
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
await expect(workspace.getByRole("dialog", { name: "Workspace Settings" })).toHaveCount(0);
await expect(workspace.getByRole("grid").getByText("Retail", { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-four-source-results.png"), animations: "disabled" });
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([
{
driver: "duck",
plan: {
tables: [
{ sourceId: "accounts", schema: "public", table: "customers" },
{ sourceId: "events", schema: "events", table: "purchases" },
{ sourceId: "warehouse", schema: "main", table: "items" },
{ sourceId: "lookup", schema: "main", table: "labels" },
],
joins: [
{ left: { relation: 0, column: "id" }, rightColumn: "customer_id" },
{ left: { relation: 1, column: "customer_id" }, rightColumn: "id" },
{ left: { relation: 2, column: "id" }, rightColumn: "id" },
],
projection: [
{ relation: 0, column: "id" },
{ relation: 3, column: "label" },
],
},
},
]);
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
});
test("shows the workspace before any data sources are added", async ({ workbench: page }, info) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const store = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ store);
window.__ipc.handlers.db_sources = () => [];
useDatabase.setState({ sources: [], loaded: true });
});
const node = await showDatabase(page);
await expect(node).toBeVisible();
await node.click();
await page.keyboard.press("Enter");
const workspace = page.getByRole("region", { name: "Query Workspace" });
const editor = workspace.getByLabel("Workspace SQL");
await expect(editor).toBeEmpty();
await expect(editor).toBeFocused();
await expect(workspace.locator("pre")).toContainText("FROM #source_a.schema.table_a");
await expect(workspace.getByRole("button", { name: "Insert JOIN" })).toHaveCount(0);
await expect(workspace.getByRole("button", { name: "New Data Source…" })).toBeVisible();
await expect(workspace.locator("pre")).toContainText("ON a.key = b.key");
await expect(workspace.getByRole("grid")).toHaveCount(0);
const height = await editor.evaluate((element) => element.closest(".cm-editor")!.getBoundingClientRect().height);
expect(height).toBeGreaterThan(500);
await page.screenshot({ path: info.outputPath("workspace-empty.png"), animations: "disabled" });
await page.keyboard.insertText("SELECT");
await expect(editor).toHaveText("SELECT");
await expect(workspace.locator("pre")).toHaveCount(0);
await page.setViewportSize({ width: 720, height: 620 });
await page.evaluate(async () => {
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const settings = useProject.getState().settings;
useProject.setState({
settings: { ...settings, appearance: { ...settings?.appearance, theme: "dark", syncWithOs: false } },
});
});
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
await editor.press("Meta+Enter");
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(
settings.getByText("Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources."),
).toBeVisible();
const dialog = (await settings.boundingBox())!;
expect(dialog.x + dialog.width).toBeLessThanOrEqual(720);
await settings.getByRole("button", { name: "New Data Source…" }).click();
const sourceDialog = page.getByRole("dialog", { name: "New Data Source", exact: true });
await expect(sourceDialog).toBeVisible();
await sourceDialog.press("Escape");
await settings.press("Escape");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
});
test("completes preferred aliases and pages the same workspace result", async ({ workbench: page }, info) => {
await setupWorkspace(page, { fullNames: true });
const node = await showDatabase(page);
await node.click({ button: "right" });
await page.getByRole("menuitem", { name: /Workspace Settings…/ }).click();
const workspace = page.getByRole("region", { name: "Query Workspace" });
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(settings.getByText("In memory", { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-settings.png"), animations: "disabled" });
await settings.getByRole("button", { name: "SQL aliases", exact: true }).press("Enter");
await settings.getByRole("textbox", { name: /^SQL alias for Accounts/ }).fill(" acct ");
const rightAlias = settings.getByRole("textbox", { name: /^SQL alias for Events/ });
await rightAlias.fill("acct");
await expect(settings.getByRole("alert")).toHaveText("Choose a SQL alias unique to this source.");
const ok = settings.getByRole("button", { name: "OK", exact: true });
await expect(ok).toBeDisabled();
await rightAlias.fill("events");
await expect(ok).toBeEnabled();
await page.screenshot({ path: info.outputPath("workspace-aliases.png"), animations: "disabled" });
await ok.click();
const editor = workspace.getByLabel("Workspace SQL");
await expect(editor).toBeFocused();
const context = workspace.getByRole("button", {
name: /Workspace Settings.*DuckDB JDBC/,
});
await expect(context).toHaveText("DuckDB JDBC");
await workspace.getByRole("button", { name: "Insert JOIN" }).click();
await expect(editor).toContainText("#source_a.schema.table_a");
await expect(editor).toContainText("#source_b.schema.table_b");
const selection = () => page.evaluate(() => window.getSelection()?.toString());
expect(await selection()).toBe("#source_a");
await page.getByRole("option", { name: /^#acct/ }).click();
await expect(editor).toContainText("#acct.schema.table_a");
await editor.press("Tab");
expect(await selection()).toBe("#source_b");
await editor.press("Control+Space");
await page.getByRole("option", { name: /^#events/ }).click();
await editor.press("Tab");
expect(await selection()).toBe("schema.table_a");
await editor.press("Control+Space");
await page.getByRole("option", { name: /^public\.customers/ }).click();
await expect(editor).toContainText("#acct.public.customers");
await editor.press("Tab");
expect(await selection()).toBe("schema.table_b");
await editor.press("Meta+A");
await page.keyboard.insertText('SELECT * FROM #"Accounts · PostgreSQL".');
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /public\.customers/ })).toBeVisible();
await editor.press("Escape");
await editor.press("Meta+A");
await page.keyboard.insertText("SELECT * FROM #ACCT.");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /^#ACCT\.public\.customers/ })).toBeVisible();
await editor.press("Escape");
await editor.press("Meta+A");
await page.keyboard.insertText("SELECT *\nFROM #");
await editor.press("Control+Space");
await expect(
page.getByRole("option", { name: /^#events/ }).getByText("Events · ClickHouse", { exact: true }),
).toBeVisible();
await expect(page.getByRole("option", { name: /^#left/ })).toHaveCount(0);
await expect(page.getByRole("option", { name: /^#right/ })).toHaveCount(0);
const accountOption = page.getByRole("option", { name: /^#acct/ });
await expect(accountOption.getByText("Accounts · PostgreSQL", { exact: true })).toBeVisible();
await accountOption.click();
await page.keyboard.insertText(".");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /legacy\.customers/ })).toBeVisible();
await expect(page.getByRole("option", { name: /customers_view/ })).toHaveCount(0);
await page.screenshot({ path: info.outputPath("workspace-completion.png"), animations: "disabled" });
await page.getByRole("option", { name: /public\.customers/ }).click();
await page.keyboard.insertText(" AS a\nJOIN #events.events.");
await editor.press("Control+Space");
await page.getByRole("option", { name: /#events\.events\.purchases/ }).click();
await page.keyboard.insertText(" AS b\n ON a.");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /archived_id|customer_id/ })).toHaveCount(0);
const keyOption = (name: string) => page.getByRole("option").filter({ has: page.getByText(name, { exact: true }) });
await expect(keyOption("id")).toBeVisible();
await keyOption("id").click();
await page.keyboard.insertText(" = b.");
await editor.press("Control+Space");
await expect(keyOption("customer_id")).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-keys.png"), animations: "disabled" });
await keyOption("customer_id").click();
await editor.press("Meta+Enter");
const grid = workspace.getByRole("grid");
await expect(grid.getByText("Customer 1", { exact: true })).toBeVisible();
await expect(grid.getByText("9007199254740993", { exact: true })).toHaveCount(2);
await expect(grid.getByText("123456789012345678.000001", { exact: true }).first()).toBeVisible();
await expect(grid.getByText("<null>", { exact: true })).toBeVisible();
expect((await ipcCalls(page, "db_workspace_join"))[0]).toMatchObject({
driver: "duck",
plan: {
tables: [
{ sourceId: "accounts", database: "", schema: "public", table: "customers" },
{ sourceId: "events", database: "", schema: "events", table: "purchases" },
],
joins: [{ left: { relation: 0, column: "id" }, rightColumn: "customer_id" }],
projection: null,
},
});
expect(await ipcCalls(page, "db_completion")).toEqual([{ id: "accounts" }, { id: "events" }]);
await workspace.getByRole("button", { name: "Next Page" }).click();
await expect(grid.getByText("Last customer", { exact: true })).toBeVisible();
await expect(workspace.getByRole("button", { name: "Next Page" })).toBeDisabled();
await workspace.getByRole("button", { name: "Previous Page" }).click();
await expect(grid.getByText("Customer 1", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(1);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
await page.screenshot({ path: info.outputPath("workspace-join.png"), animations: "disabled" });
});
test("runs the selected JOIN or the one at the caret from a multi-statement draft", async ({
workbench: page,
}, info) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
const second = SQL.replace("public.customers", "legacy.customers");
await editor.click();
await page.keyboard.insertText(SQL + ";\n" + second + ";");
await editor.press("Meta+Enter");
await expect.poll(async () => (await ipcCalls(page, "db_workspace_join")).length).toBe(1);
expect((await ipcCalls(page, "db_workspace_join"))[0]).toMatchObject({
plan: { tables: [{ schema: "legacy" }, { sourceId: "events" }] },
});
await editor.press("Meta+Home");
await editor.press("Shift+End");
const selected = await page.evaluate(() => window.getSelection()?.toString());
expect(selected).toBe(SQL + ";");
await workspace.getByRole("button", { name: "Run", exact: true }).click();
await expect.poll(async () => (await ipcCalls(page, "db_workspace_join")).length).toBe(2);
expect((await ipcCalls(page, "db_workspace_join"))[1]).toMatchObject({
plan: { tables: [{ schema: "public" }, { sourceId: "events" }] },
});
await page.evaluate(() => {
const reply = window.__ipc.handlers.db_workspace_join;
window.__ipc.handlers.db_workspace_join = async (args) => {
await new Promise<void>((resolve) => {
window.addEventListener("workspace-test-release", () => resolve(), { once: true });
});
const result = reply?.(args) as { rows: string[][] };
if ((args.plan as { tables: { schema: string }[] }).tables[0]!.schema === "legacy")
result.rows[0]![1] = "Legacy customer";
return result;
};
});
const release = () => page.evaluate(() => window.dispatchEvent(new Event("workspace-test-release")));
const selectionRange = () =>
editor.evaluate((element) => {
const state = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view
.state;
const { from, to } = state.selection.main;
return { from, to };
});
await editor.press("Meta+A");
const fullRange = await selectionRange();
await editor.press("Meta+Enter");
const running = workspace.locator(".cm-openidea-db-executing");
const runningText = () => running.evaluateAll((nodes) => nodes.map((node) => node.textContent).join(""));
await expect.poll(runningText).toBe(SQL);
expect(await selectionRange()).toEqual(fullRange);
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(3);
await page.screenshot({ path: info.outputPath("workspace-batch-running.png"), animations: "disabled" });
await release();
await expect.poll(runningText).toBe(second);
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(4);
await release();
await expect(workspace.getByRole("tab", { name: "Result 2", exact: true })).toBeVisible();
await expect(workspace.locator(".cm-openidea-db-run-ok")).toHaveCount(2);
const grid = workspace.getByRole("grid");
await expect(grid.getByText("Legacy customer", { exact: true })).toBeVisible();
await workspace.getByRole("tab", { name: "Result 1", exact: true }).click();
await expect(grid.getByText("Customer 1", { exact: true })).toBeVisible();
await workspace.getByRole("button", { name: "Next Page" }).click();
await expect(grid.getByText("Last customer", { exact: true })).toBeVisible();
await workspace.getByRole("tab", { name: "Result 2", exact: true }).click();
await expect(grid.getByText("Legacy customer", { exact: true })).toBeVisible();
await workspace.getByRole("tab", { name: "Result 1", exact: true }).click();
await expect(grid.getByText("Last customer", { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-batch-results.png"), animations: "disabled" });
const calls = await ipcCalls(page, "db_workspace_join");
expect(calls.slice(2)).toMatchObject([
{ plan: { tables: [{ schema: "public" }, { sourceId: "events" }] } },
{ plan: { tables: [{ schema: "legacy" }, { sourceId: "events" }] } },
]);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
await editor.press("Meta+A");
await editor.press("Backspace");
await workspace.getByRole("button", { name: "Insert JOIN" }).click();
await page.getByRole("option", { name: /^#accounts/ }).click();
await editor.press("Tab");
await editor.press("Control+Space");
await page.getByRole("option", { name: /^#events/ }).click();
for (const field of ["public.customers", "events.purchases", "id", "customer_id"]) {
await editor.press("Tab");
await page.keyboard.insertText(field);
}
await editor.press("Meta+Enter");
await expect.poll(async () => (await ipcCalls(page, "db_workspace_join")).length).toBe(5);
expect((await ipcCalls(page, "db_workspace_join"))[4]).toMatchObject({
plan: { tables: [{ table: "customers" }, { sourceId: "events" }] },
});
await release();
});
test("cancels the active request and surfaces parser, source and limit errors", async ({ workbench: page }) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const run = workspace.getByRole("button", { name: "Run", exact: true });
const alert = workspace.getByRole("alert");
const editor = workspace.getByLabel("Workspace SQL");
await editor.click();
await editor.press("Meta+A");
await page.keyboard.insertText("DELETE FROM #accounts.public.customers");
await run.click();
await expect(alert).toHaveText("Expected SELECT in the workspace query.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
await editor.click();
await editor.press("Meta+A");
await page.keyboard.insertText(SQL);
await page.evaluate(() => {
let active: { id: unknown; reject: (error: unknown) => void } | undefined;
window.__ipc.handlers.db_workspace_join = ({ request }) =>
new Promise((_, reject) => {
active = { id: request, reject };
});
window.__ipc.handlers.cancel_request = ({ id }) => {
if (active?.id !== id) throw new Error("Unexpected cancellation request.");
active?.reject({ kind: "cancelled", message: "Operation cancelled", data: null });
};
});
await run.click();
await expect(workspace.getByText("Running query", { exact: true })).toBeVisible();
await expect(workspace.getByRole("button", { name: /Workspace Settings…/ })).toBeDisabled();
await workspace.getByRole("button", { name: "Stop", exact: true }).click();
await expect(alert).toHaveText("Cancelled");
await expect(run).toBeEnabled();
expect(await ipcCalls(page, "cancel_request")).toEqual([
{ id: (await ipcCalls(page, "db_workspace_join"))[0]!.request },
]);
for (const message of [
"Could not connect to Events",
"Workspace input exceeds the source row limit",
"Workspace result exceeds 100,000 rows",
]) {
await page.evaluate((message) => {
window.__ipc.handlers.db_workspace_join = () => {
throw { kind: "invalidInput", message, data: null };
};
}, message);
await run.click();
await expect(alert).toHaveText(message);
await expect(workspace.getByRole("grid")).toHaveCount(0);
await expect(run).toBeEnabled();
}
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(4);
});
test("validates all selected statements before reading either source", async ({ workbench: page }) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
const alert = workspace.getByRole("alert");
await editor.click();
await page.keyboard.insertText(SQL + ";\nDELETE FROM #accounts.public.customers;");
await editor.press("Meta+A");
await editor.press("Meta+Enter");
await expect(alert).toHaveText("Expected SELECT in the workspace query.");
await expect(workspace.locator(".cm-openidea-db-run-error")).toHaveCount(1);
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
await page.keyboard.insertText(Array.from({ length: 13 }, () => SQL + ";").join("\n"));
await workspace.getByRole("button", { name: "Execute Script" }).click();
await expect(alert).toHaveText("The workspace can run up to 12 statements at a time.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
});
for (const failure of ["cancel", "error", "row budget"] as const) {
test(`stops the script after ${failure} and keeps the completed result`, async ({ workbench: page }) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.click();
await page.keyboard.insertText([SQL, SQL.replace("public.customers", "legacy.customers"), SQL].join(";\n") + ";");
await page.evaluate((failure) => {
const reply = window.__ipc.handlers.db_workspace_join;
window.__ipc.handlers.db_workspace_join = ({ request, plan, ...args }) => {
const result = reply?.({ request, plan, ...args }) as { rows: Array<Array<string | null>> };
if ((plan as { tables: { schema: string }[] }).tables[0]!.schema !== "legacy") return result;
if (failure === "error") throw { kind: "invalidInput", message: "Could not connect to Events", data: null };
if (failure === "row budget") return { ...result, rows: Array(100_000).fill(result.rows[0]) };
return new Promise((_, reject) => {
window.__ipc.handlers.cancel_request = ({ id }) => {
if (id !== request) throw new Error("Unexpected cancellation request.");
reject({ kind: "cancelled", message: "Operation cancelled", data: null });
};
});
};
}, failure);
await workspace.getByRole("button", { name: "Execute Script" }).click();
const result = workspace.getByRole("tab", { name: "Result 1", exact: true });
await expect(result).toBeVisible();
if (failure === "cancel") await workspace.getByRole("button", { name: "Stop", exact: true }).click();
const message = {
cancel: "Cancelled",
error: "Could not connect to Events",
"row budget": "The workspace batch exceeds the result size limit.",
}[failure];
await expect(workspace.getByRole("alert")).toHaveText(message);
await expect(workspace.locator(".cm-openidea-db-run-ok")).toHaveCount(1);
await expect(workspace.locator(".cm-openidea-db-run-error")).toHaveCount(1);
await expect(workspace.locator(".cm-openidea-db-timing")).toHaveCount(2);
await result.click();
await expect(workspace.getByRole("grid").getByText("Customer 1", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(2);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
});
}
test("migrates old source slots, aliases and driver with each project's SQL", async ({ workbench: page }) => {
await setupWorkspace(page, { multipleDrivers: true });
const legacySQL = SQL.replace("#accounts", "#left").replace("#events", "#right");
await saveWorkspaceDraft(page, {
left: "accounts",
right: "events",
sourceAliases: { accounts: "acct", events: "evt" },
profile: "duck-local",
sql: legacySQL,
});
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await expect(editor).toHaveText(legacySQL);
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([
{ driver: "duck-local", plan: { tables: [{ sourceId: "accounts" }, { sourceId: "events" }] } },
]);
const settings = await settingsFor(page, workspace);
const driver = settings.getByRole("button", { name: "Workspace DuckDB driver" });
await expect(driver).toHaveText("DuckDB Local");
await settings.getByText("SQL aliases", { exact: true }).click();
const accountsAlias = settings.getByRole("textbox", { name: /^SQL alias for accounts/ });
const eventsAlias = settings.getByRole("textbox", { name: /^SQL alias for events/ });
await expect(accountsAlias).toHaveValue("acct");
await expect(eventsAlias).toHaveValue("evt");
await accountsAlias.fill("customers");
await settings.getByRole("button", { name: "OK", exact: true }).click();
const close = page
.getByRole("region", { name: "Editor", exact: true })
.getByRole("button", { name: "Close Tab", exact: true });
await close.click();
await expect(workspace).toHaveCount(0);
await openWorkspace(page);
await expect(editor).toHaveText(legacySQL);
await settingsFor(page, workspace);
await settings.getByText("SQL aliases", { exact: true }).click();
await expect(accountsAlias).toHaveValue("customers");
await expect(eventsAlias).toHaveValue("evt");
await expect(driver).toHaveText("DuckDB Local");
await accountsAlias.fill("discarded");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await settingsFor(page, workspace);
await settings.getByText("SQL aliases", { exact: true }).click();
await expect(accountsAlias).toHaveValue("customers");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await close.click();
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const project = useProject.getState().project;
useProject.setState({ project: { ...project, root: project.root + "-other" } });
});
await openWorkspace(page);
await expect(editor).toBeEmpty();
await settingsFor(page, workspace);
await expect(driver).toHaveText("Select DuckDB driver");
await settings.getByText("SQL aliases", { exact: true }).click();
await expect(accountsAlias).toHaveValue("");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(1);
});
test("does not retarget a deleted legacy source to an unrelated source named left", async ({ workbench: page }) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
{ id: "replacement", name: "left", driver: "postgres" },
{ id: "events", name: "events", driver: "clickhouse" },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
});
const sql = SQL.replace("#accounts", "#left").replace("#events", "#right");
await saveWorkspaceDraft(page, { sql, left: "deleted", right: "events" });
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
const alert = workspace.getByRole("alert");
await editor.press("Meta+Enter");
await expect(alert).toHaveText("Data source left is unavailable. Type # to see available sources.");
await editor.press("Meta+A");
await page.keyboard.insertText(sql.replace("#left", '#"left"'));
await editor.press("Meta+Enter");
await expect(alert).toHaveText("Data source left is unavailable. Type # to see available sources.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
await editor.press("Meta+A");
await page.keyboard.insertText("SELECT * FROM #");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /^#"?left/ })).toHaveCount(0);
await page.getByRole("option", { name: "Set unique SQL aliases…" }).click();
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await settings.getByRole("textbox", { name: "SQL alias for left (PostgreSQL)" }).fill("replacement_src");
await settings.getByRole("button", { name: "OK", exact: true }).click();
await editor.press("Meta+A");
await page.keyboard.insertText(sql.replace("#left", "#replacement_src"));
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([
{ plan: { tables: [{ sourceId: "replacement" }, { sourceId: "events" }] } },
]);
});
test("offers aliases when identical saved names cannot be resolved", async ({ workbench: page }) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
{ id: "accounts", name: "Shared", driver: "postgres", host: "accounts.example" },
{ id: "events", name: "Shared", driver: "clickhouse", host: "events.example" },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
});
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.focus();
await page.keyboard.insertText("SELECT * FROM #");
await editor.press("Control+Space");
const aliasOption = page.getByRole("option", { name: "Set unique SQL aliases…" });
await expect(aliasOption).toBeVisible();
await expect(page.getByRole("option", { name: /^#"Shared"/ })).toHaveCount(0);
await aliasOption.click();
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(settings.getByText("accounts.example", { exact: true })).toBeVisible();
await settings.getByRole("textbox", { name: "SQL alias for Shared (PostgreSQL)" }).fill("accounts");
await settings.getByRole("textbox", { name: "SQL alias for Shared (ClickHouse)" }).fill("events");
await settings.getByRole("button", { name: "OK", exact: true }).click();
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /^#accounts/ })).toBeVisible();
await expect(page.getByRole("option", { name: /^#events/ })).toBeVisible();
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
});
test("keeps unrelated queries executable when a stored alias becomes ambiguous", async ({ workbench: page }) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
...useDatabase.getState().sources,
{ id: "old", name: "old", driver: "postgres" },
{ id: "new", name: "colliding", driver: "postgres" },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
});
await saveWorkspaceDraft(page, { sql: SQL, sourceAliases: { old: "colliding" } });
const workspace = await openWorkspace(page);
await workspace.getByLabel("Workspace SQL").press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(1);
const settings = await settingsFor(page, workspace);
await expect(settings.getByRole("alert")).toHaveText("Choose a SQL alias unique to this source.");
await expect(settings.getByRole("button", { name: "OK", exact: true })).toBeDisabled();
});
test("asks before replacing a missing explicitly selected execution driver", async ({ workbench: page }) => {
await setupWorkspace(page);
await saveWorkspaceDraft(page, { sql: SQL, profile: "missing" });
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.press("Meta+Enter");
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(settings.getByRole("alert")).toHaveText("The saved DuckDB driver is unavailable.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
const driver = settings.getByRole("button", { name: "Workspace DuckDB driver" });
await driver.click();
await page.getByRole("option", { name: "DuckDB JDBC" }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([{ driver: "duck" }]);
});
+1
Переглянути файл
@@ -179,6 +179,7 @@ db_tool_options trusted desktop bin
db_tool_preview trusted desktop bindings sync
db_tool_version trusted desktop bindings async
db_trust_ssh_host trusted project_host bindings async
db_workspace_join trusted project_host bindings async
debug_attachable_processes always project_host bindings async
debug_breakpoint_states trusted project_host bindings sync
debug_capabilities trusted project_host bindings sync
+32
Переглянути файл
@@ -465,6 +465,7 @@ export const commands = {
/** The version line of the executable at `path`. */
dbToolVersion: (path: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_tool_version", { path })),
dbTrustSshHost: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_trust_ssh_host", { id })),
dbWorkspaceJoin: (request: RequestId, driver: string, plan: DbWorkspaceJoinPlan) => typedError<DbQueryResult, IdeError>(__TAURI_INVOKE("db_workspace_join", { request, driver, plan })),
/** Attach to Process: the user's processes a debugger can attach to. */
debugAttachableProcesses: () => typedError<AttachableProcess[], IdeError>(__TAURI_INVOKE("debug_attachable_processes")),
/** Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`). */
@@ -6331,6 +6332,37 @@ export type DbTxMode = "auto" | "manual";
export type DbVisibilityChange = { kind: "databases"; selection: DbSchemaSelection } | { kind: "schemas"; selection: DbSchemaSelection } | { kind: "databaseSchemas"; database: string; selection: DbSchemaSelection | null };
export type DbWorkspaceJoinColumn = {
relation: number,
column: string,
};
export type DbWorkspaceJoinCondition = {
/** The right relation is the next table in the chain. */
left: DbWorkspaceJoinColumn,
rightColumn: string,
};
export type DbWorkspaceJoinPlan = {
tables: DbWorkspaceJoinRelation[],
joins: DbWorkspaceJoinCondition[],
/** None expands all relations in FROM/JOIN order. */
projection: DbWorkspaceJoinProjection[] | null,
};
export type DbWorkspaceJoinProjection = {
relation: number,
/** None expands this relation's columns in source order. */
column: string | null,
};
export type DbWorkspaceJoinRelation = {
sourceId: string,
database: string,
schema: string,
table: string,
};
/** What a session's adapter supports, for enabling actions. */
export type DebugCapabilities = {
restartFrame: boolean,
+3
Переглянути файл
@@ -366,6 +366,9 @@
flex: 1;
min-height: 0;
}
.treeHost[data-empty] > :first-child {
flex: 0 0 32px;
}
.nodeRow {
display: flex;
align-items: center;
+21 -18
Переглянути файл
@@ -69,7 +69,7 @@ import {
import { DB_VIEW_FOCUS, databaseTree, openTableData } from "./treeActions";
import { newMenu, nodeMenu } from "./treeMenu";
import styles from "./Database.module.css";
import { formatMessage, tx } from "@/platform/i18n";
import { formatMessage, tx, useTx } from "@/platform/i18n";
import { databaseRequest } from "./requests";
const GROUP_LABELS: Record<Group, string> = {
@@ -147,6 +147,7 @@ function groupSize(d: DbTableDetails, g: Group): number {
}
export function DatabaseView() {
const t = useTx();
const st = useDatabase();
const folders = st.separateProceduresAndFunctions ? SEPARATE_FOLDERS : FOLDERS;
const tree = useRef<TreeHandle>(null);
@@ -206,6 +207,7 @@ export function DatabaseView() {
...st.sources
.filter((source) => !grouped.has(source.id ?? ""))
.map((source): Node => ({ kind: "source", key: source.id ?? "", source })),
{ kind: "workspace", key: ":query-workspace" },
];
}, [st.folders, st.sources]);
@@ -549,6 +551,8 @@ export function DatabaseView() {
const label = (n: Node): string => {
switch (n.kind) {
case "workspace":
return t("Query Workspace");
case "source":
return n.source.pluginOwner ? `${n.source.name} (${n.source.pluginOwner})` : (n.source.name ?? "");
case "sourceFolder":
@@ -632,6 +636,8 @@ export function DatabaseView() {
const icon = (n: Node): string | undefined => {
switch (n.kind) {
case "workspace":
return "db-console";
case "source":
return sourceIcon(n.source);
case "sourceFolder":
@@ -668,25 +674,11 @@ export function DatabaseView() {
}
};
if (st.loaded && st.foldersLoaded && !st.sources.length && !st.folders.length)
return (
<div className={styles.dbView}>
<DatabaseToolbar />
<EmptyState title="No data sources">
<Button variant="ghost" onClick={() => void executeAction("db.newDataSource")}>
<T>New Data Source…</T>
</Button>
<Button variant="ghost" onClick={() => void executeAction("db.newSourceFolder")}>
<T>New Folder…</T>
</Button>
</EmptyState>
</div>
);
const empty = st.loaded && st.foldersLoaded && !st.sources.length && !st.folders.length;
return (
<div className={styles.dbView}>
<DatabaseToolbar />
<div className={styles.treeHost} ref={treeHost}>
<div className={styles.treeHost} ref={treeHost} data-empty={empty ? "" : undefined}>
<Tree<Node>
aria-label="Data sources"
focusContext={DB_VIEW_FOCUS}
@@ -785,7 +777,8 @@ export function DatabaseView() {
})
}
onActivate={(n) => {
if (n.kind === "table") openTableData(n.id, n.schema, n.table.name, n.catalog);
if (n.kind === "workspace") void executeAction("db.queryWorkspace");
else if (n.kind === "table") openTableData(n.id, n.schema, n.table.name, n.catalog);
else if (n.kind === "source") void openConsole(n.source.id ?? "");
else if (n.kind === "database" && n.catalog === undefined) void openConsole(n.id);
else {
@@ -800,6 +793,16 @@ export function DatabaseView() {
}}
speedSearch
/>
{empty && (
<EmptyState title="No data sources">
<Button variant="ghost" onClick={() => void executeAction("db.newDataSource")}>
<T>New Data Source…</T>
</Button>
<Button variant="ghost" onClick={() => void executeAction("db.newSourceFolder")}>
<T>New Folder…</T>
</Button>
</EmptyState>
)}
</div>
</div>
);
+30 -10
Переглянути файл
@@ -535,7 +535,33 @@ describe("DuckDB data sources", () => {
}
});
it("requires write access for in-memory databases", async () => {
it.each(["jdbc:duckdb::memory:;threads=1", "jdbc:duckdb:memory:default", "jdbc:duckdb::memory:local;threads=1"])(
"requires write access for the in-memory URL %s",
async (url) => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK"));
render(
<SourceDialog
initial={{
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
url,
urlOnly: true,
readOnly: true,
}}
/>,
);
await screen.findByText("Turn off Read-only in Options to use an in-memory DuckDB database.");
expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled();
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
const readOnly = screen.getByRole("checkbox", { name: "Read-only" });
fireEvent.click(readOnly);
expect(readOnly).toBeDisabled();
await waitFor(() => expect(screen.getByRole("button", { name: "Test Connection" })).toBeEnabled());
},
);
it("keeps read-only available for a file with a memory-like name", async () => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK"));
render(
<SourceDialog
@@ -543,19 +569,13 @@ describe("DuckDB data sources", () => {
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
url: "jdbc:duckdb::memory:;threads=1",
url: "jdbc:duckdb:./memory:default",
urlOnly: true,
readOnly: true,
}}
/>,
);
await screen.findByText("Turn off Read-only in Options to use an in-memory DuckDB database.");
expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled();
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
const readOnly = screen.getByRole("checkbox", { name: "Read-only" });
fireEvent.click(readOnly);
expect(readOnly).toBeDisabled();
await waitFor(() => expect(screen.getByRole("button", { name: "Test Connection" })).toBeEnabled());
fireEvent.click(await screen.findByRole("tab", { name: "Options" }));
expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeEnabled();
});
it("keeps an existing generic DuckDB JDBC source generic", async () => {
+4 -1
Переглянути файл
@@ -710,11 +710,14 @@ export function SourceDialog({
: fromTemplate
? renderedUrl
: (s.url ?? "");
const duckDbTarget = jdbcUrl.split(";", 1)[0]!;
const duckDbMemory =
duckdb &&
(duckDbMode === "memory" ||
(duckDbMode === "url" &&
[DUCKDB_JDBC_PREFIX, `${DUCKDB_JDBC_PREFIX}:memory:`].includes(jdbcUrl.split(";", 1)[0]!)));
(duckDbTarget === DUCKDB_JDBC_PREFIX ||
duckDbTarget.startsWith(DUCKDB_JDBC_PREFIX + "memory:") ||
duckDbTarget.startsWith(DUCKDB_JDBC_PREFIX + ":memory:"))));
const chooseProfile = (profile?: DbJdbcDriver, type = vendor) => {
setTest(null);
setConnectionSecurityConfirmed(false);
+140
Переглянути файл
@@ -0,0 +1,140 @@
.workspace {
display: flex;
height: 100%;
min-height: 0;
flex-direction: column;
background: var(--bg-editor);
}
.toolbar,
.firstRunActions,
.running,
.settingsActions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
}
.toolbar {
flex: none;
padding: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
gap: var(--space-0-5);
}
.context {
min-width: 0;
max-width: calc(100% - 32px);
margin-inline-start: auto;
}
.context > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.firstRun,
.running {
color: var(--fg-muted);
}
.running {
margin-inline-start: var(--space-2);
}
.settings [role="alert"] {
color: var(--danger);
}
.settings {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
}
.settings p {
margin: 0;
color: var(--fg-muted);
}
.driverMode {
margin-inline-start: var(--space-2);
color: var(--fg-muted);
}
.aliasFields {
display: grid;
gap: var(--space-2);
max-height: 260px;
overflow: auto;
padding: var(--space-2) var(--space-1) var(--space-1) 0;
}
.aliasField {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
}
.aliasName {
display: flex;
gap: var(--space-1-5);
align-items: center;
}
.aliasName > span,
.aliasName small {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.aliasName small {
display: block;
color: var(--fg-muted);
}
.field {
display: grid;
gap: var(--space-1);
min-width: 0;
}
.query {
position: relative;
flex: 1;
min-height: 90px;
overflow: hidden;
}
.editor {
height: 100%;
}
.firstRun {
position: absolute;
inset-block-start: 42px;
inset-inline-start: 44px;
max-width: calc(100% - 54px);
padding: var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-field, 6px);
background: var(--bg-island);
pointer-events: none;
}
.firstRunActions button {
pointer-events: auto;
}
.example {
margin: var(--space-2) 0;
color: var(--fg-editor);
font-family: var(--font-mono);
line-height: 1.45;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.exampleKeyword {
color: var(--syn-keyword);
}
.exampleName {
color: var(--syn-string);
}
.query[data-result] {
flex: 0 1 38%;
border-bottom: 1px solid var(--border);
}
.query :global(.cm-editor) {
height: 100%;
}
.results {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
+907
Переглянути файл
@@ -0,0 +1,907 @@
import {
autocompletion,
completionKeymap,
hasNextSnippetField,
hasPrevSnippetField,
snippet,
startCompletion,
type Completion,
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { findLanguageDescription, loadSupport } from "@/editor/core/cm/languages";
import { baseExtensions, compartments } from "@/editor/core/cm/setup";
import { executeAction } from "@/platform/actions";
import { tx, useTx } from "@/platform/i18n";
import { shortcutLabel } from "@/platform/keymap";
import {
call,
commands,
isCancelled,
nextRequestId,
type DataSource,
type DbQueryResult,
type RequestId,
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Button, Dialog, Icon, IconButton, Input, Select, Spinner, T, Tabs, Toolbar } from "@/ui";
import type { EditorInput } from "@/workbench/contributions";
import { executionMarks, trackExecution } from "./executionMarks";
import { Grid } from "./Grid";
import { jdbcProfileOption, JdbcDriverProfiles, useJdbcDrivers } from "./JdbcDriverProfiles";
import { sourceLabel, targetOf } from "./model";
import { projectRequest } from "./requests";
import { formatElapsed } from "./resultView";
import { quoteIdent } from "./sql/complete";
import { identName, inLiteral, lex } from "./sql/lexer";
import { loadCompletion, loadSources, useDatabase } from "./store";
import { DUCKDB_JDBC_CLASS, DUCKDB_JDBC_PREFIX, vendorOf } from "./vendors";
import {
WORKSPACE_SQL_LIMIT,
workspaceJoinColumnOptions,
workspaceJoinColumnTarget,
workspaceJoinQuery,
workspaceSourceAliasError,
workspaceSourceResolver,
type WorkspaceSourceReference,
workspaceStatementRanges,
} from "./workspaceQuery";
import dbStyles from "./Database.module.css";
import styles from "./WorkspaceEditor.module.css";
const PAGE_SIZE = 500;
const MAX_BATCH_STATEMENTS = 12;
const MAX_BATCH_ROWS = 100_000;
const MAX_BATCH_BYTES = 64 * 1024 * 1024;
type WorkspaceResult = { sql: string; data: DbQueryResult; page: number };
type WorkspaceRun = { request: RequestId | null; cancelled: boolean };
// Estimate retained JS payload without serializing or copying the grid's rows.
function resultBytes(result: DbQueryResult, available: number): number {
let bytes = 0;
for (const column of result.columns) bytes += 64 + 2 * (column.name.length + column.typeName.length);
for (const row of result.rows) {
bytes += 24 + 8 * row.length;
for (const cell of row) if (cell !== null) bytes += 24 + 2 * cell.length;
if (bytes > available) break;
}
return bytes;
}
function resultLabel(n: number) {
return tx`Result ${n}`;
}
type Configuration = {
profile: string;
sourceAliases: Record<string, string>;
legacySources: { left: string; right: string };
};
type SavedSource = DataSource & { id: string };
type SourceResolver = ReturnType<typeof workspaceSourceResolver>;
function sourcePrefix(name: string) {
return "#" + quoteIdent(name, "postgres");
}
function preferredReference(ref: WorkspaceSourceReference, resolve: SourceResolver) {
if (ref.alias && resolve(ref.alias)?.id === ref.id) return sourcePrefix(ref.alias);
const prefix = sourcePrefix(ref.name);
if (resolve(ref.name, prefix.startsWith('#"'))?.id === ref.id) return prefix;
if (resolve(ref.name, true)?.id === ref.id) return '#"' + ref.name.replaceAll('"', '""') + '"';
return undefined;
}
const JOIN_TEMPLATE =
"SELECT *\nFROM ${1:#source_a}.${3:schema.table_a} AS a\nJOIN ${2:#source_b}.${4:schema.table_b} AS b\n ON a.${5:key} = b.${6:key}";
const exampleKeywords = new Set(["SELECT", "FROM", "AS", "JOIN", "ON"]);
function JoinExample() {
const sql = JOIN_TEMPLATE.replace(/\$\{\d+:([^}]+)\}/g, "$1");
const tokens = lex(sql, "postgres").tokens.filter(
(token) => token.kind === "quoted" || exampleKeywords.has(token.upper),
);
return (
<pre className={styles.example}>
<code>
{tokens.map((token, index) => (
<Fragment key={token.from}>
{sql.slice(tokens[index - 1]?.to ?? 0, token.from)}
<span className={token.kind === "quoted" ? styles.exampleName : styles.exampleKeyword}>{token.text}</span>
</Fragment>
))}
{sql.slice(tokens.at(-1)?.to ?? 0)}
</code>
</pre>
);
}
function eligible(source: DataSource): source is SavedSource {
if (!source.id || source.id.includes(":") || source.options?.startupScript?.trim()) return false;
if (source.driver === "postgres" || source.driver === "clickhouse") return true;
if (source.driver === "sqlite") return !!source.file && !source.file.includes(":memory:");
if (source.driver !== "jdbc" || vendorOf(source).id !== "duckdb") return false;
const endpoint = source.url?.split(";", 1)[0];
if (!endpoint?.startsWith(DUCKDB_JDBC_PREFIX)) return false;
const path = endpoint.slice(DUCKDB_JDBC_PREFIX.length);
return !!path && !/^[: ]|^(?:memory|md):/i.test(path) && !path.includes("://");
}
function sourceReferences(sources: SavedSource[], config: Configuration): WorkspaceSourceReference[] {
return sources.map((source) => ({
id: source.id,
name: source.name || source.id,
alias: Object.hasOwn(config.sourceAliases, source.id) ? config.sourceAliases[source.id]!.trim() : undefined,
legacy:
source.id === config.legacySources.left ? "left" : source.id === config.legacySources.right ? "right" : undefined,
}));
}
function metadataTarget(source: SavedSource, database: string) {
if (!database || database === source.database || (source.driver === "sqlite" && database === "main"))
return source.id;
if (source.driver === "postgres" || source.driver === "clickhouse")
return targetOf(source.id, database, source.database ?? null);
// A file source's completion is for its saved file only.
return null;
}
function complete(
bindings: () => {
references: WorkspaceSourceReference[];
resolve: SourceResolver;
candidates: SavedSource[];
configureAliases: () => void;
},
): CompletionSource {
return async (context) => {
const field = context.state.selection.main;
const selectingField =
context.explicit &&
!field.empty &&
field.from === context.pos &&
(hasNextSnippetField(context.state) || hasPrevSnippetField(context.state));
const end = selectingField ? field.to : context.pos;
if (end > WORKSPACE_SQL_LIMIT) return null;
const sql = context.state.sliceDoc(0, end);
const parsed = lex(sql, "postgres");
const state = inLiteral(parsed, end);
if (state === "string" || state === "comment") return null;
const { references, resolve, candidates, configureAliases } = bindings();
const current = projectRequest();
const stillCurrent = () =>
current() && !context.aborted && (!context.view || context.view.state.doc === context.state.doc);
const target = workspaceJoinColumnTarget(sql, resolve, parsed);
if (target) {
const source = candidates.find((candidate) => candidate.id === target.sourceId);
const id = source && metadataTarget(source, target.database);
if (!id) return null;
const catalog = useDatabase.getState().completion[id] ?? (await loadCompletion(id));
if (!catalog || !stillCurrent()) return null;
const updated = workspaceJoinColumnTarget(sql, bindings().resolve, parsed);
if (
updated?.sourceId !== target.sourceId ||
updated.database !== target.database ||
updated.schema !== target.schema ||
updated.table !== target.table
)
return null;
const selectingKey = selectingField && field.from === target.from;
const column = selectingKey ? { ...target, prefix: "" } : target;
return {
from: target.from,
to: selectingKey ? field.to : undefined,
options: workspaceJoinColumnOptions(column, catalog),
filter: false,
};
}
const hash = parsed.tokens.findLastIndex((token) => token.text === "#");
if (hash < 0) return null;
const tokens = parsed.tokens.slice(hash + 1);
if (tokens.some((token) => token.kind !== "quoted" && token.kind !== "word" && token.text !== ".")) return null;
const from = parsed.tokens[hash]!.from;
const prefix = sql.slice(from);
if (/\s$/.test(prefix) && state !== "quoted") return null;
if (tokens.length < 2) {
const typed = tokens[0]?.text.toLowerCase() ?? "";
const options: Completion[] = [];
const vendors = new Map(candidates.map((source) => [source.id, vendorOf(source).label]));
let needsAliases = false;
for (const ref of references) {
const preferred = preferredReference(ref, resolve);
if (!preferred) needsAliases = true;
else {
const detail = preferred === sourcePrefix(ref.name) ? vendors.get(ref.id) : ref.name;
options.push({ label: preferred, type: "namespace", detail, boost: 5 });
}
if (ref.legacy && preferred !== "#" + ref.legacy && typed && ref.legacy.startsWith(typed))
options.push({ label: "#" + ref.legacy, type: "namespace", detail: ref.name });
}
if (needsAliases) {
options.push({
label: prefix,
displayLabel: tx("Set unique SQL aliases…"),
type: "namespace",
boost: -10,
apply: configureAliases,
});
}
const selectingSource = selectingField && field.from === from;
return { from, to: selectingSource ? field.to : undefined, options, filter: !selectingSource };
}
const sourceToken = tokens[0]!;
const name = identName(sourceToken);
const quoted = sourceToken.kind === "quoted";
const ref = resolve(name, quoted);
if (!ref || tokens[1]!.text !== ".") return null;
const source = candidates.find((candidate) => candidate.id === ref.id);
const qualifier = tokens[2];
const explicitDatabase = qualifier && qualifier.text !== "." && tokens[3]?.text === "." && tokens[5]?.text === ".";
const database = explicitDatabase
? qualifier.kind === "word"
? qualifier.text.toLowerCase()
: identName(qualifier)
: "";
const id = source && metadataTarget(source, database);
if (!id) return null;
const catalog = useDatabase.getState().completion[id] ?? (await loadCompletion(id));
if (!catalog || !stillCurrent() || bindings().resolve(name, quoted)?.id !== ref.id) return null;
// Keep the user's quoted or bare source spelling, which the resolver interpreted above.
const sourcePath = sql.slice(from, sourceToken.to) + (database ? "." + quoteIdent(database, "postgres") : "");
const prefixLower = prefix.toLowerCase();
const selectingTable = selectingField && field.from === tokens[1]!.to;
const options: Completion[] = [];
for (const table of catalog.tables) {
if (table.kind !== "table") continue;
const tableName = quoteIdent(table.name, "postgres");
const schema = quoteIdent(table.schema || catalog.defaultSchema, "postgres");
const qualified = `${sourcePath}.${schema}.${tableName}`;
const direct = `${sourcePath}.${tableName}`;
const label =
selectingTable || qualified.toLowerCase().startsWith(prefixLower)
? qualified
: !database && table.schema === catalog.defaultSchema && direct.toLowerCase().startsWith(prefixLower)
? direct
: null;
if (label) {
options.push({
label: selectingTable ? label.slice(sourcePath.length + 1) : label,
type: "class",
detail: ref.name,
});
if (options.length === 100) break;
}
}
return {
from: selectingTable ? field.from : from,
to: selectingTable ? field.to : undefined,
options,
filter: false,
};
};
}
function readDraft(key: string) {
let value: Record<string, unknown> = {};
try {
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (stored && typeof stored === "object") value = stored as Record<string, unknown>;
} catch {
/* Storage may be disabled. */
}
const legacy = value.legacySources as Partial<Configuration["legacySources"]> | null | undefined;
return {
legacySources: {
left: typeof legacy?.left === "string" ? legacy.left : typeof value.left === "string" ? value.left : "",
right: typeof legacy?.right === "string" ? legacy.right : typeof value.right === "string" ? value.right : "",
},
profile: typeof value.profile === "string" ? value.profile : "",
sourceAliases: Object.fromEntries(
value.sourceAliases && typeof value.sourceAliases === "object"
? Object.entries(value.sourceAliases).filter((entry): entry is [string, string] => typeof entry[1] === "string")
: [],
),
sql: typeof value.sql === "string" ? value.sql : "",
};
}
export function WorkspaceEditor({ input }: { input: EditorInput }) {
const t = useTx();
const storageKey = "openidea." + input.key;
const [draft] = useState(() => readDraft(storageKey));
const sources = useDatabase((state) => state.sources);
const registry = useJdbcDrivers();
const [config, setConfig] = useState<Configuration>({
legacySources: draft.legacySources,
profile: draft.profile,
sourceAliases: draft.sourceAliases,
});
const [settings, setSettings] = useState<Configuration | null>(null);
const [showAliases, setShowAliases] = useState(false);
const settingsRequested = useDatabase((state) => state.workspaceSettingsRequest === input.key);
const [manage, setManage] = useState(false);
const [empty, setEmpty] = useState(() => draft.sql.length === 0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [results, setResults] = useState<WorkspaceResult[]>([]);
const [active, setActive] = useState("feedback");
const panelId = useId();
const panel = useRef<HTMLDivElement>(null);
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const running = useRef<WorkspaceRun | null>(null);
const candidates = useMemo(() => sources.filter(eligible), [sources]);
const drivers = registry.drivers?.filter((d) => d.vendor === "duckdb" && d.className === DUCKDB_JDBC_CLASS) ?? [];
const driverFor = (id: string) =>
id ? drivers.find((driver) => driver.id === id) : drivers.length === 1 ? drivers[0] : undefined;
const references = useMemo(() => sourceReferences(candidates, config), [candidates, config]);
const resolve = useMemo(() => workspaceSourceResolver(references, config), [references, config]);
const usableReferences = useMemo(
() => references.filter((ref) => preferredReference(ref, resolve)).length,
[references, resolve],
);
const aliasError = useMemo(() => workspaceSourceAliasError(references, resolve), [references, resolve]);
const needsAliases = usableReferences !== references.length;
const ready = !!driverFor(config.profile) && candidates.length >= 2;
const settingsError = useMemo(() => {
if (!settings) return null;
const sources = sourceReferences(candidates, settings);
return workspaceSourceAliasError(sources, workspaceSourceResolver(sources, settings));
}, [candidates, settings]);
const current = useRef({
config,
references,
resolve,
candidates,
execute: () => {},
configureAliases: () => {},
});
const openSettings = (aliases = needsAliases || !!aliasError) => {
if (running.current) return;
setShowAliases(aliases);
setSettings(config);
};
useEffect(() => {
if (!settingsRequested || busy) return;
const frame = requestAnimationFrame(() => {
useDatabase.setState({ workspaceSettingsRequest: null });
setShowAliases(needsAliases || !!aliasError);
setSettings(config);
});
return () => cancelAnimationFrame(frame);
}, [settingsRequested, busy, config, needsAliases, aliasError]);
const stop = () => {
const run = running.current;
if (!run || run.cancelled) return;
run.cancelled = true;
if (run.request !== null) void commands.cancelRequest(run.request);
};
const execute = async (script = false) => {
const editor = view.current;
if (running.current || !editor) return;
const driver = driverFor(config.profile);
if (!ready || !driver) {
openSettings();
return;
}
const state = editor.state;
const range = state.selection.main;
// Tab fields in Insert JOIN are selections for editing the template.
const selected = !script && !range.empty && !hasNextSnippetField(state) && !hasPrevSnippetField(state);
const from = selected ? range.from : 0;
const to = selected ? range.to : state.doc.length;
const submitted = selected || script;
const reportError = (message: string) => {
setError(message);
setActive("feedback");
};
if (to - from > WORKSPACE_SQL_LIMIT) {
reportError(tx("Workspace SQL exceeds 65,536 characters."));
return;
}
const sql = state.sliceDoc(from, to);
const spans = workspaceStatementRanges(sql, submitted ? undefined : range.head).map((span) => ({
from: span.from + from,
to: span.to + from,
}));
if (!spans.length) {
editor.focus();
return;
}
if (spans.length > MAX_BATCH_STATEMENTS) {
reportError(tx("The workspace can run up to 12 statements at a time."));
return;
}
const tracker = trackExecution(editor);
const queries = [];
// Validate the entire batch before the first request touches any source.
for (const span of spans) {
const text = state.sliceDoc(span.from, span.to);
try {
queries.push({ text, plan: workspaceJoinQuery(text, resolve) });
} catch (e) {
const error = e instanceof Error ? e.message : String(e);
tracker.start([span]);
tracker.update(null, [{ index: 0, error, ms: null }]);
tracker.end();
reportError(error);
return;
}
}
const activeProject = projectRequest();
const run: WorkspaceRun = { request: null, cancelled: false };
const ownsRun = () => activeProject() && running.current === run;
running.current = run;
setError("");
setResults([]);
setActive("feedback");
setBusy(true);
tracker.start(spans);
let rows = 0;
let bytes = 0;
try {
for (const [index, { text, plan }] of queries.entries()) {
if (!ownsRun()) break;
if (run.cancelled) {
reportError(tx("Cancelled"));
break;
}
const request = nextRequestId();
run.request = request;
const startedAt = Date.now();
tracker.update({ index, startedAt });
try {
// Each JOIN owns the source reads and staging until it finishes.
// oxlint-disable-next-line no-await-in-loop
const data = await call(commands.dbWorkspaceJoin(request, driver.id, plan));
if (!ownsRun()) break;
rows += data.rows.length;
bytes += resultBytes(data, MAX_BATCH_BYTES - bytes);
if (rows > MAX_BATCH_ROWS || bytes > MAX_BATCH_BYTES)
throw new Error(tx("The workspace batch exceeds the result size limit."));
tracker.update(null, [{ index, error: null, ms: data.elapsedMs ?? Date.now() - startedAt }]);
setResults((previous) => [...previous, { sql: text, page: 0, data }]);
setActive(String(index));
} catch (e) {
if (!ownsRun()) break;
const error = isCancelled(e) ? tx("Cancelled") : e instanceof Error ? e.message : String(e);
tracker.update(null, [{ index, error, ms: Date.now() - startedAt }]);
reportError(error);
break;
} finally {
run.request = null;
}
}
} finally {
if (running.current === run) {
running.current = null;
tracker.end();
setBusy(false);
}
}
};
useLayoutEffect(() => {
current.current = {
config,
references,
resolve,
candidates,
execute: () => void execute(),
configureAliases: () => openSettings(true),
};
});
useEffect(() => {
if (!useDatabase.getState().loaded) void loadSources();
if (!host.current) return;
const sql = findLanguageDescription("SQL", "workspace.sql");
const editor = new EditorView({
parent: host.current,
state: EditorState.create({
doc: draft.sql,
extensions: baseExtensions({
ctx: { doc: -1, path: "workspace.sql", language: "sql", uiMode: "SQL", readOnly: false, virtual: true },
settings: useProject.getState().settings?.editor,
info: undefined,
language: null,
docLength: draft.sql.length,
contributions: [],
extra: [
executionMarks,
autocompletion({ override: [complete(() => current.current)] }),
EditorView.updateListener.of((update) => {
if (update.docChanged) setEmpty(update.state.doc.length === 0);
}),
Prec.highest(
keymap.of([
{
key: "Mod-Enter",
run: () => {
current.current.execute();
return true;
},
},
...completionKeymap,
]),
),
Prec.highest(EditorView.contentAttributes.of({ "aria-label": tx("Workspace SQL") })),
],
}),
}),
});
view.current = editor;
const panel = editor.dom.closest("[data-editor-focus]");
const focusEditor = () => editor.focus();
panel?.addEventListener("focus", focusEditor);
if (panel) focusEditor();
const save = () => {
try {
localStorage.setItem(
storageKey,
JSON.stringify({ ...current.current.config, sql: editor.state.doc.toString() }),
);
} catch {
/* The current session remains usable without storage. */
}
};
editor.dom.addEventListener("focusout", save);
window.addEventListener("pagehide", save);
if (sql)
void loadSupport(sql).then((language) => {
if (view.current === editor && language)
editor.dispatch({ effects: compartments.language.reconfigure(language) });
});
return () => {
stop();
running.current = null;
save();
editor.dom.removeEventListener("focusout", save);
panel?.removeEventListener("focus", focusEditor);
window.removeEventListener("pagehide", save);
view.current = null;
editor.destroy();
};
}, [draft, storageKey]);
const insertJoin = () => {
const editor = view.current;
if (!editor || editor.state.doc.length) return;
snippet(JOIN_TEMPLATE)(editor, null, 0, 0);
editor.focus();
startCompletion(editor);
};
const applySettings = () => {
if (!settings || !driverFor(settings.profile) || settingsError) return;
const next = {
...settings,
sourceAliases: Object.fromEntries(
Object.entries(settings.sourceAliases)
.map(([id, alias]) => [id, alias.trim()])
.filter(([, alias]) => alias),
),
};
if (
next.profile !== config.profile ||
JSON.stringify(next.sourceAliases) !== JSON.stringify(config.sourceAliases)
) {
setConfig(next);
setResults([]);
setActive("feedback");
setError("");
}
setSettings(null);
const editor = view.current;
requestAnimationFrame(() => {
if (view.current === editor) editor?.focus();
});
};
const result = results[Number(active)];
const start = (result?.page ?? 0) * PAGE_SIZE;
const first = start + 1;
const total = result?.data.rows.length ?? 0;
const last = Math.min(start + PAGE_SIZE, total);
const hasFeedback = busy || results.length > 0 || !!error;
const setPage = (page: number) =>
setResults((previous) => previous.map((item) => (item === result ? { ...item, page } : item)));
const configureLabel = t("Workspace Settings…");
const driver = driverFor(config.profile);
const connectionContext = driver ? `${configureLabel} · ${driver.name}` : configureLabel;
const newSource = () => void executeAction("db.newDataSource");
return (
<section className={styles.workspace} aria-label={t("Query Workspace")}>
<Toolbar className={styles.toolbar} aria-label="Workspace actions">
{busy ? (
<IconButton icon="stop" title="Stop" tone="danger" onClick={stop} />
) : (
<>
<IconButton
icon="run"
title="Run"
tone="accent"
shortcut={shortcutLabel("db.execute")}
onClick={() => void execute()}
/>
<IconButton icon="gutter-run-all" title="Execute Script" onClick={() => void execute(true)} />
</>
)}
<Button
variant="ghost"
size="small"
className={styles.context}
icon="settings"
aria-label={connectionContext}
title={connectionContext}
disabled={busy}
onClick={() => openSettings()}
>
<span>{driver?.name ?? configureLabel}</span>
</Button>
</Toolbar>
<div className={styles.query} data-result={hasFeedback ? "" : undefined}>
<div className={styles.editor} ref={host} />
{empty && (
<div className={styles.firstRun}>
{candidates.length < 2 ? (
<T>Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.</T>
) : (
<T>Type # to choose a saved data source.</T>
)}
<JoinExample />
<div className={styles.firstRunActions}>
{usableReferences >= 2 ? (
<Button variant="secondary" size="small" onClick={insertJoin}>
<T>Insert JOIN</T>
</Button>
) : candidates.length < 2 ? (
<Button variant="primary" size="small" onClick={newSource}>
<T>New Data Source…</T>
</Button>
) : (
<Button variant="primary" size="small" onClick={() => openSettings()}>
<T>Workspace Settings…</T>
</Button>
)}
</div>
</div>
)}
</div>
{hasFeedback && (
<>
<Tabs
className={dbStyles.resultTabs}
variant="compact"
aria-label={t("Results")}
activeId={active}
panelIdPrefix={panelId}
onSelect={setActive}
items={[
{ id: "feedback", label: "Feedback", icon: "db-console" },
...results.map(({ sql }, index) => ({
id: String(index),
label: resultLabel(index + 1),
icon: "db-table",
verbatim: true,
tooltip: sql,
})),
]}
focusContent={() => {
const target = panel.current?.querySelector<HTMLElement>('[role="grid"], [role="log"]');
target?.focus();
return !!target && document.activeElement === target;
}}
/>
<div
ref={panel}
className={styles.results}
role="tabpanel"
id={`${panelId}-panel-${active}`}
aria-labelledby={`${panelId}-tab-${active}`}
>
{result ? (
<>
<div className={dbStyles.fill}>
<Grid
key={`${active}-${result.page}`}
columns={result.data.columns.map((c) => ({ name: c.name, type: c.typeName }))}
rowCount={Math.min(PAGE_SIZE, result.data.rows.length - start)}
firstRowNumber={first}
value={(row, col) => result.data.rows[start + row]?.[col] ?? null}
/>
</div>
<div className={dbStyles.pagerDock}>
<Toolbar className={dbStyles.resultPager} aria-label={t("Result pages")}>
{result.data.rows.length > PAGE_SIZE ? (
<>
<IconButton
size="small"
icon="chevron-left"
title="Previous Page"
disabled={result.page === 0}
onClick={() => setPage(result.page - 1)}
/>
<span className={dbStyles.resultPagerRange}>{t`${first}-${last} of ${total}`}</span>
<IconButton
size="small"
icon="chevron-right"
title="Next Page"
disabled={start + PAGE_SIZE >= result.data.rows.length}
onClick={() => setPage(result.page + 1)}
/>
</>
) : (
<span className={dbStyles.resultPagerRange}>{t`${result.data.rows.length} rows`}</span>
)}
</Toolbar>
</div>
</>
) : (
<div role="log" tabIndex={0} className={dbStyles.output} aria-label={t("Feedback")}>
{results.map(({ data }, index) => (
<div key={index} className={dbStyles.outputLine}>
{resultLabel(index + 1)} · {t`${data.rows.length} rows`}
{data.elapsedMs !== null && ` · ${formatElapsed(data.elapsedMs)}`}
</div>
))}
{error && (
<div role="alert" className={dbStyles.outputError}>
{error}
</div>
)}
{busy && (
<div role="status" className={styles.running}>
<Spinner label={t("Running query")} /> <T>Running query</T>
</div>
)}
</div>
)}
</div>
</>
)}
{settings && (
<Dialog
open
title={t("Workspace Settings")}
width={480}
onClose={() => {
setManage(false);
setSettings(null);
}}
buttons={[
{ label: "Cancel", role: "cancel" },
{
label: "OK",
role: "default",
disabled: !driverFor(settings.profile) || !!settingsError,
onClick: applySettings,
},
]}
>
<div className={styles.settings}>
<label className={styles.field}>
<span>
<T>Workspace DuckDB driver</T>
<small className={styles.driverMode}>
<T>In memory</T>
</small>
</span>
<Select
aria-label={t("Workspace DuckDB driver")}
aria-description={t("In memory")}
value={driverFor(settings.profile)?.id ?? null}
placeholder="Select DuckDB driver"
options={drivers.map(jdbcProfileOption)}
onChange={(profile) => setSettings({ ...settings, profile })}
/>
</label>
{!settings.profile && registry.drivers && !driverFor(settings.profile) && (
<p>
<T>Choose a DuckDB JDBC driver to run workspace SQL.</T>
</p>
)}
<div className={styles.settingsActions}>
<Button variant="ghost" disabled={registry.drivers === null} onClick={() => setManage(true)}>
<T>Manage Drivers…</T>
</Button>
{registry.error && (
<Button onClick={registry.retry}>
<T>Retry</T>
</Button>
)}
</div>
{candidates.length > 0 && (
<div>
<Button
variant="ghost"
size="small"
icon={showAliases ? "chevron-down" : "chevron-right"}
aria-expanded={showAliases}
aria-controls={showAliases ? `${panelId}-aliases` : undefined}
onClick={() => setShowAliases(!showAliases)}
>
<T>SQL aliases</T>
</Button>
{showAliases && (
<div id={`${panelId}-aliases`} className={styles.aliasFields}>
<p>
<T>Use a short SQL name for a source. Leave it blank to use the connection name.</T>
</p>
{candidates.map((source) => {
const label = sourceLabel({ ...source, name: source.name || source.id });
const detail = source.file || [source.host, source.database].filter(Boolean).join(" / ");
const alias = Object.hasOwn(settings.sourceAliases, source.id)
? settings.sourceAliases[source.id]
: "";
return (
<label key={source.id} className={styles.aliasField}>
<span className={styles.aliasName} title={detail ? `${label} · ${detail}` : label}>
<Icon name={vendorOf(source).icon} size={14} />
<span>
{source.name || source.id}
{detail && <small>{detail}</small>}
</span>
</span>
<Input
aria-label={t`SQL alias for ${label}`}
aria-description={detail || undefined}
mono
value={alias}
placeholder={source.name || source.id}
onChange={(event) =>
setSettings({
...settings,
sourceAliases: { ...settings.sourceAliases, [source.id]: event.target.value },
})
}
/>
</label>
);
})}
</div>
)}
</div>
)}
{settings.profile && registry.drivers && !driverFor(settings.profile) && (
<p role="alert">
<T>The saved DuckDB driver is unavailable.</T>
</p>
)}
{settingsError && <p role="alert">{settingsError}</p>}
{registry.error && <div role="alert">{registry.error}</div>}
{candidates.length < 2 && (
<div className={styles.settingsActions}>
<p>
<T>Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.</T>
</p>
<Button variant="secondary" size="small" onClick={newSource}>
<T>New Data Source…</T>
</Button>
</div>
)}
</div>
</Dialog>
)}
{settings && manage && registry.drivers && (
<JdbcDriverProfiles
drivers={registry.drivers}
selected={driverFor(settings.profile)?.id ?? ""}
sourceVendor="duckdb"
onClose={() => setManage(false)}
onSave={(d) => {
registry.setDrivers((old) => [...(old ?? []).filter((entry) => entry.id !== d.id), d]);
setSettings({ ...settings, profile: d.id });
}}
onUse={(d) => {
setSettings({ ...settings, profile: d.id });
setManage(false);
}}
onRemove={(id) => registry.setDrivers((old) => (old ?? []).filter((d) => d.id !== id))}
/>
)}
</section>
);
}
+22 -479
Переглянути файл
@@ -17,29 +17,12 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import {
Compartment,
EditorSelection,
EditorState,
Facet,
Prec,
RangeSet,
type Range,
StateEffect,
StateField,
type Extension,
type Text,
type Transaction,
} from "@codemirror/state";
import { Compartment, EditorState, Facet, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import {
Decoration,
EditorView,
GutterMarker,
RectangleMarker,
ViewPlugin,
WidgetType,
gutter,
layer,
showPanel,
showTooltip,
type Panel,
@@ -47,9 +30,8 @@ import {
} from "@codemirror/view";
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import { problemProviders, type ContributedProblem, type EditorDocContext } from "@/editor/api";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import { call, commands, type DbSessionContext, type DbStatementOutcome, type SqlStatement } from "@/platform/ipc";
import type { EditorDocContext } from "@/editor/api";
import { call, commands, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
@@ -76,7 +58,6 @@ import {
} from "./sql/complete";
import { sqlDriverOf, type SqlDriver } from "./sql/dialect";
import { duckdbLanguage } from "./sql/duckdbHighlight";
import { unsafeMessage } from "./sql/unsafe";
import { WHOLE_FILE, sqlSupport, type SqlText } from "./sqlSupport";
import { snowflakeLanguage } from "./sql/snowflakeHighlight";
import {
@@ -107,7 +88,6 @@ import {
setManualCommit,
sourceById,
useDatabase,
type ConfirmUnsafe,
} from "./store";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
@@ -117,393 +97,48 @@ import type { ResultTab } from "./store";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { confirmUnsafe, executionMarks, runField, setPreview, trackExecution } from "./executionMarks";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { jdbcDialect } from "./vendors";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
/** Statement outcomes of the last run, kept on the text (IDEA's gutter check / error and timing). */
interface RunMark {
from: number;
to: number;
/** After the statement's `;` when it has one. */
timingAt: number;
error: string | null;
ms: number | null;
}
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
active: { index: number; startedAt: number } | null;
spans: readonly { from: number; to: number }[];
}
function activeSpan(ex: Executing | null) {
const span = ex?.active ? ex.spans[ex.active.index] : undefined;
return span && span.from < span.to ? span : undefined;
}
interface AskMark {
from: number;
to: number;
message: string;
}
interface RunState {
ask?: AskMark | null;
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const setAsk = StateEffect.define<AskMark | null>();
/** Saving can append the final newline without changing any submitted SQL or statement offsets. */
function savedFinalNewline(tr: Transaction): boolean {
if (!tr.docChanged || !tr.isUserEvent("input.save")) return false;
const end = tr.startState.doc.length;
let only = true;
tr.changes.iterChanges((from, to, _f, _t, insert) => {
only &&= from === end && to === end && insert.toString() === "\n";
});
return only;
}
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) value = { ...e.value, ask: value.ask };
for (const e of tr.effects) if (e.is(setAsk)) value = { ...value, ask: e.value };
if (!tr.docChanged || savedFinalNewline(tr)) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
let touched = false;
tr.changes.iterChangedRanges((a, b) => {
if (a <= m.to && b >= m.from) touched = true;
});
if (!touched)
marks.push({
...m,
from: tr.changes.mapPos(m.from),
to: tr.changes.mapPos(m.to),
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing, ask: null };
},
provide: (f) => [
EditorView.decorations.compute([f], (state) => {
const st = state.field(f);
const ranges = [];
const active = st.executing?.active;
const span = activeSpan(st.executing);
if (active && span) {
const end = state.sliceDoc(span.to, span.to + 1) === ";" ? span.to + 1 : span.to;
const at = Math.min(end, state.doc.lineAt(span.from).to);
ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(span.from, span.to));
ranges.push(Decoration.widget({ widget: new ElapsedWidget(active.startedAt), side: 1 }).range(at));
}
for (const m of st.marks) {
if (m.error) ranges.push(Decoration.mark({ class: "cm-openidea-db-error" }).range(m.from, m.to));
if (m.ms !== null)
ranges.push(Decoration.widget({ widget: new TimingWidget(m.ms), side: 1 }).range(m.timingAt));
}
const u = st.ask;
if (u && u.from < u.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-warning" }).range(u.from, u.to));
return Decoration.set(ranges, true);
}),
showPanel.from(f, (st) => (st.ask ? askBanner(st.ask) : st.banner ? errorBanner(st.banner) : null)),
// The editor's hover shows the run errors and the unsafe-query warning like other problems.
problemProviders.compute([f], (state) => {
const st = state.field(f);
const problems: ContributedProblem[] = [];
for (const m of st.marks)
if (m.error && m.from < m.to) problems.push({ from: m.from, to: m.to, severity: "error", message: m.error });
const u = st.ask;
if (u && u.from < u.to) problems.push({ from: u.from, to: u.to, severity: "warning", message: u.message });
return () => problems;
}),
],
});
class TimingWidget extends WidgetType {
constructor(readonly ms: number) {
super();
}
eq(other: TimingWidget) {
return other.ms === this.ms;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = formatElapsed(this.ms);
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(
readonly error: string | null,
readonly warning: string | null = null,
) {
super();
}
eq(other: RunMarker) {
return other.error === this.error && other.warning === this.warning;
}
toDOM() {
if (this.warning) {
const el = iconNode("warning", 14, "cm-openidea-db-run-warning");
el.dataset.tooltip = this.warning;
return el;
}
const el = iconNode(
this.error ? "error" : "check",
14,
this.error ? "cm-openidea-db-run-error" : "cm-openidea-db-run-ok",
);
el.dataset.tooltip = this.error ?? tx("Executed");
return el;
}
}
const runGutter = gutter({
class: "cm-openidea-db-gutter",
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const active = activeSpan(st.executing);
const line = active ? doc.lineAt(active.from).from : undefined;
const unsafe = st.ask;
const unsafeLine = unsafe && unsafe.from <= doc.length ? doc.lineAt(unsafe.from).from : -1;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && doc.lineAt(m.from).from !== unsafeLine)
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
if (line !== undefined && line !== unsafeLine) ranges.push(new ExecutingMarker().range(line));
if (unsafe && unsafeLine >= 0) ranges.push(new RunMarker(null, unsafe.message).range(unsafeLine));
return RangeSet.of(ranges, true);
},
});
function errorBanner(message: string) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = message;
text.title = message;
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", "Close");
close.appendChild(iconNode("close", 14));
close.onclick = () => view.dispatch({ effects: setRun.of({ ...view.state.field(runField), banner: null }) });
dom.append(text, close);
return { dom, top: false };
};
}
type AskChoice = "execute" | "suppress" | "cancel";
/** The answer to the banner a view asks with. */
const askAnswers = new WeakMap<EditorView, (choice: AskChoice) => void>();
/** Consoles whose unsafe queries run without asking (Execute and Suppress), until the app restarts. */
const unsafeSuppressed = new Set<string>();
function askBanner(mark: AskMark) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner cm-openidea-db-banner-warning";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = mark.message;
text.dataset.tooltip = mark.message;
const answer = (choice: AskChoice) => askAnswers.get(view)?.(choice);
const action = (label: string, choice: AskChoice) => {
const b = document.createElement("button");
b.type = "button";
b.className = "cm-openidea-db-banner-action";
b.textContent = label;
b.onclick = () => answer(choice);
return b;
};
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", tx("Close"));
close.appendChild(iconNode("close", 14));
close.onclick = () => answer("cancel");
const actions = [action(tx("Execute"), "execute"), action(tx("Execute and Suppress"), "suppress")];
dom.append(text, ...actions, close);
return { dom, top: false };
};
}
/**
* Editing or closing the console while the unsafe-query banner waits cancels the run.
*/
const cancelAskOnEdit = [
EditorView.updateListener.of((u) => {
if (!u.docChanged) return;
if (u.transactions.every((tr) => !tr.docChanged || savedFinalNewline(tr))) {
const preparing = preparingViews.get(u.view);
if (preparing?.doc === u.startState.doc) preparing.doc = u.state.doc;
return;
}
if (u.startState.field(runField).ask) askAnswers.get(u.view)?.("cancel");
}),
ViewPlugin.define((view) => ({
destroy: () => {
closedViews.add(view);
askAnswers.get(view)?.("cancel");
},
})),
];
/** Views destroyed with a question open: nothing more to dispatch to them. */
const closedViews = new WeakSet<EditorView>();
/** Shows `mark` in the banner and waits for the answer. */
function ask(view: EditorView, mark: AskMark): Promise<AskChoice> {
askAnswers.get(view)?.("cancel");
return new Promise<AskChoice>((resolve) => {
askAnswers.set(view, (choice) => {
askAnswers.delete(view);
if (!closedViews.has(view) && view.state.field(runField, false)?.ask) view.dispatch({ effects: setAsk.of(null) });
resolve(choice);
});
view.dispatch({ effects: setAsk.of(mark) });
});
}
/** Shows the unsafe-query banner for `statement` and waits for the answer (true: run it). */
function confirmUnsafe(view: EditorView, path: string, current: () => boolean): ConfirmUnsafe {
return async (statement, unsafe) => {
if (!current()) return false;
if (unsafeSuppressed.has(path)) return true;
const len = view.state.doc.length;
const choice = await ask(view, {
from: Math.min(len, statement.from + unsafe.from),
to: Math.min(len, statement.from + unsafe.to),
message: unsafeMessage(unsafe),
});
if (choice === "suppress") unsafeSuppressed.add(path);
return choice !== "cancel";
};
}
let nextExecution = 0;
const preparingViews = new WeakMap<EditorView, { doc: Text }>();
export { previewRanges } from "./executionMarks";
/** Runs `from`–`to` of `view`, following each statement as it executes. */
async function executeRange(view: EditorView, path: string, from: number, to: number) {
const token = ++nextExecution;
const sent = view.state.doc;
askAnswers.get(view)?.("cancel");
const preparing = { doc: sent };
preparingViews.set(view, preparing);
const current = () =>
!closedViews.has(view) && view.state.doc === preparing.doc && preparingViews.get(view) === preparing;
const start = (statements: readonly SqlStatement[]) => {
const st = view.state.field(runField, false);
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (!st || !current()) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const first = spans[0]!;
const last = spans[spans.length - 1]!;
const marks = st.marks.filter((mark) => mark.to <= first.from || mark.from >= last.to);
view.dispatch({ effects: setRun.of({ marks, banner: null, executing: { token, spans, active: null } }) });
};
const tracker = trackExecution(view, (error) => `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`);
try {
await executeConsole(
path,
sent.toString(),
from,
to,
start,
tracker.start,
(events) => {
const st = view.state.field(runField, false);
const ex = st?.executing;
if (!st || ex?.token !== token) return;
const last = events[events.length - 1]!;
const active = last.type === "started" ? { index: last.index, startedAt: Date.now() } : null;
const marks = [...st.marks];
let banner = st.banner;
const completed = events.filter((event) => event.type !== "started");
const spans = tracker.update(
active,
completed.map(({ index, outcome }) => ({
index,
error: outcome.error,
ms: outcome.result?.elapsedMs ?? null,
})),
);
const placed = new Map<number, DbStatementOutcome>();
for (const event of events) {
if (event.type === "started") continue;
const span = ex.spans[event.index];
if (!span || span.from >= span.to) continue;
const { from, to } = span;
const { error, result } = event.outcome;
marks.push({
from,
to,
timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to,
error,
ms: result?.elapsedMs ?? null,
});
if (error) banner = `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`;
placed.set(event.index, { ...event.outcome, statement: { ...event.outcome.statement, ...span } });
for (const { index, outcome } of completed) {
const span = spans.get(index);
if (span) placed.set(index, { ...outcome, statement: { ...outcome.statement, ...span } });
}
view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) });
return placed;
},
confirmUnsafe(view, path, current),
confirmUnsafe(view, path, tracker.current),
);
} finally {
if (preparingViews.get(view) === preparing) preparingViews.delete(view);
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
tracker.end();
}
}
@@ -529,94 +164,6 @@ export async function explainInView(view: EditorView, path: string) {
const consolePath = Facet.define<string, string>({ combine: (v) => v[0] ?? "" });
const setPreview = StateEffect.define<readonly { from: number; to: number }[]>();
/**
* The range the console's next Execute would submit, bordered on the text (DataGrip's current
* statement border): the caret's statement, or the selection's — the statements `db_statements`
* splits that range into, the very call the run itself makes.
*/
const previewField = StateField.define<readonly { from: number; to: number }[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setPreview)) return e.value;
if (!tr.docChanged) return value;
// The preview is of the text it was computed for; edits only move where that is.
const next: { from: number; to: number }[] = [];
for (const r of value) {
const from = tr.changes.mapPos(r.from, 1);
const to = tr.changes.mapPos(r.to, -1);
if (from < to) next.push({ from, to });
}
return next;
},
});
/** The bordered ranges: a run in progress keeps its submitted range, whatever the caret does. */
export function previewRanges(state: EditorState): readonly { from: number; to: number }[] {
const ex = state.field(runField, false)?.executing;
const ranges = ex?.spans.length
? [{ from: ex.spans[0]!.from, to: ex.spans[ex.spans.length - 1]!.to }]
: (state.field(previewField, false) ?? []);
return ranges.filter((r) => r.from < r.to);
}
const PREVIEW_CLASS = "cm-openidea-db-preview";
/**
* One box around each statement's text: the union of its lines' text (indentation and trailing
* blanks left out), as tall as the statement even where it runs out of view.
*/
function previewBoxes(view: EditorView): RectangleMarker[] {
const { doc } = view.state;
const boxes: RectangleMarker[] = [];
for (const r of previewRanges(view.state)) {
let left = Infinity;
let right = -Infinity;
let offset: number | null = null;
for (const visible of view.visibleRanges) {
const from = Math.max(r.from, visible.from);
const to = Math.min(r.to, visible.to);
if (from >= to) continue;
for (let pos = from; pos <= to;) {
const line = doc.lineAt(pos);
const text = line.text;
let start = Math.max(from, line.from) - line.from;
let end = Math.min(to, line.to) - line.from;
while (start < end && /\s/.test(text[start]!)) start++;
while (end > start && /\s/.test(text[end - 1]!)) end--;
if (start < end)
for (const m of RectangleMarker.forRange(
view,
PREVIEW_CLASS,
EditorSelection.range(line.from + start, line.from + end),
)) {
left = Math.min(left, m.left);
right = Math.max(right, m.left + (m.width ?? 0));
offset ??= m.top - view.lineBlockAt(line.from).top;
}
pos = line.to + 1;
}
}
if (offset == null || right <= left) continue;
const top = view.lineBlockAt(r.from).top + offset;
const bottom = view.lineBlockAt(r.to).bottom + offset;
boxes.push(new RectangleMarker(PREVIEW_CLASS, left - 2, top, right - left + 4, bottom - top));
}
return boxes;
}
const previewLayer = layer({
above: false,
markers: previewBoxes,
update: (u) =>
u.docChanged ||
u.viewportChanged ||
u.geometryChanged ||
u.startState.field(previewField, false) !== u.state.field(previewField, false) ||
u.startState.field(runField, false)?.executing !== u.state.field(runField, false)?.executing,
});
/** How long typing pauses before the preview is split again (until then it follows the edit). */
const PREVIEW_TYPING_DELAY_MS = 150;
@@ -1531,11 +1078,7 @@ export function consoleExtension(ctx: EditorDocContext): Extension {
if (ctx.language !== SQL_LANGUAGE || ctx.virtual || ctx.readOnly) return [];
return [
consolePath.of(ctx.path),
runField,
runGutter,
cancelAskOnEdit,
previewField,
previewLayer,
executionMarks,
previewSync,
inlineField,
syncInline,
+494
Переглянути файл
@@ -0,0 +1,494 @@
import {
EditorSelection,
RangeSet,
StateEffect,
StateField,
type EditorState,
type Range,
type Text,
type Transaction,
} from "@codemirror/state";
import {
Decoration,
EditorView,
ViewPlugin,
GutterMarker,
RectangleMarker,
WidgetType,
gutter,
layer,
showPanel,
type Panel,
} from "@codemirror/view";
import { problemProviders, type ContributedProblem } from "@/editor/api";
import type { ConfirmUnsafe } from "./store";
import { unsafeMessage } from "./sql/unsafe";
import { tx } from "@/platform/i18n";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import { formatElapsed } from "./resultView";
/** Statement outcomes of the last run, kept on the text (IDEA's gutter check / error and timing). */
interface RunMark {
from: number;
to: number;
/** After the statement's `;` when it has one. */
timingAt: number;
error: string | null;
ms: number | null;
}
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
active: { index: number; startedAt: number } | null;
spans: readonly { from: number; to: number }[];
}
function activeSpan(ex: Executing | null) {
const span = ex?.active ? ex.spans[ex.active.index] : undefined;
return span && span.from < span.to ? span : undefined;
}
interface AskMark {
from: number;
to: number;
message: string;
}
interface RunState {
ask?: AskMark | null;
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const setAsk = StateEffect.define<AskMark | null>();
/** Saving can append the final newline without changing any submitted SQL or statement offsets. */
function savedFinalNewline(tr: Transaction): boolean {
if (!tr.docChanged || !tr.isUserEvent("input.save")) return false;
const end = tr.startState.doc.length;
let only = true;
tr.changes.iterChanges((from, to, _f, _t, insert) => {
only &&= from === end && to === end && insert.toString() === "\n";
});
return only;
}
export const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) value = { ...e.value, ask: value.ask };
for (const e of tr.effects) if (e.is(setAsk)) value = { ...value, ask: e.value };
if (!tr.docChanged || savedFinalNewline(tr)) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
let touched = false;
tr.changes.iterChangedRanges((a, b) => {
if (a <= m.to && b >= m.from) touched = true;
});
if (!touched)
marks.push({
...m,
from: tr.changes.mapPos(m.from),
to: tr.changes.mapPos(m.to),
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing, ask: null };
},
provide: (f) => [
EditorView.decorations.compute([f], (state) => {
const st = state.field(f);
const ranges = [];
const active = st.executing?.active;
const span = activeSpan(st.executing);
if (active && span) {
const end = state.sliceDoc(span.to, span.to + 1) === ";" ? span.to + 1 : span.to;
const at = Math.min(end, state.doc.lineAt(span.from).to);
ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(span.from, span.to));
ranges.push(Decoration.widget({ widget: new ElapsedWidget(active.startedAt), side: 1 }).range(at));
}
for (const m of st.marks) {
if (m.error) ranges.push(Decoration.mark({ class: "cm-openidea-db-error" }).range(m.from, m.to));
if (m.ms !== null)
ranges.push(Decoration.widget({ widget: new TimingWidget(m.ms), side: 1 }).range(m.timingAt));
}
const u = st.ask;
if (u && u.from < u.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-warning" }).range(u.from, u.to));
return Decoration.set(ranges, true);
}),
showPanel.from(f, (st) => (st.ask ? askBanner(st.ask) : st.banner ? errorBanner(st.banner) : null)),
// The editor's hover shows the run errors and the unsafe-query warning like other problems.
problemProviders.compute([f], (state) => {
const st = state.field(f);
const problems: ContributedProblem[] = [];
for (const m of st.marks)
if (m.error && m.from < m.to) problems.push({ from: m.from, to: m.to, severity: "error", message: m.error });
const u = st.ask;
if (u && u.from < u.to) problems.push({ from: u.from, to: u.to, severity: "warning", message: u.message });
return () => problems;
}),
],
});
class TimingWidget extends WidgetType {
constructor(readonly ms: number) {
super();
}
eq(other: TimingWidget) {
return other.ms === this.ms;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = formatElapsed(this.ms);
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(
readonly error: string | null,
readonly warning: string | null = null,
) {
super();
}
eq(other: RunMarker) {
return other.error === this.error && other.warning === this.warning;
}
toDOM() {
if (this.warning) {
const el = iconNode("warning", 14, "cm-openidea-db-run-warning");
el.dataset.tooltip = this.warning;
return el;
}
const el = iconNode(
this.error ? "error" : "check",
14,
this.error ? "cm-openidea-db-run-error" : "cm-openidea-db-run-ok",
);
el.dataset.tooltip = this.error ?? tx("Executed");
return el;
}
}
const runGutter = gutter({
class: "cm-openidea-db-gutter",
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const active = activeSpan(st.executing);
const line = active ? doc.lineAt(active.from).from : undefined;
const unsafe = st.ask;
const unsafeLine = unsafe && unsafe.from <= doc.length ? doc.lineAt(unsafe.from).from : -1;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && doc.lineAt(m.from).from !== unsafeLine)
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
if (line !== undefined && line !== unsafeLine) ranges.push(new ExecutingMarker().range(line));
if (unsafe && unsafeLine >= 0) ranges.push(new RunMarker(null, unsafe.message).range(unsafeLine));
return RangeSet.of(ranges, true);
},
});
function errorBanner(message: string) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = message;
text.title = message;
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", "Close");
close.appendChild(iconNode("close", 14));
close.onclick = () => view.dispatch({ effects: setRun.of({ ...view.state.field(runField), banner: null }) });
dom.append(text, close);
return { dom, top: false };
};
}
type AskChoice = "execute" | "suppress" | "cancel";
/** The answer to the banner a view asks with. */
const askAnswers = new WeakMap<EditorView, (choice: AskChoice) => void>();
/** Consoles whose unsafe queries run without asking (Execute and Suppress), until the app restarts. */
const unsafeSuppressed = new Set<string>();
function askBanner(mark: AskMark) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner cm-openidea-db-banner-warning";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = mark.message;
text.dataset.tooltip = mark.message;
const answer = (choice: AskChoice) => askAnswers.get(view)?.(choice);
const action = (label: string, choice: AskChoice) => {
const b = document.createElement("button");
b.type = "button";
b.className = "cm-openidea-db-banner-action";
b.textContent = label;
b.onclick = () => answer(choice);
return b;
};
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", tx("Close"));
close.appendChild(iconNode("close", 14));
close.onclick = () => answer("cancel");
const actions = [action(tx("Execute"), "execute"), action(tx("Execute and Suppress"), "suppress")];
dom.append(text, ...actions, close);
return { dom, top: false };
};
}
/**
* Editing or closing the console while the unsafe-query banner waits cancels the run.
*/
const cancelAskOnEdit = [
EditorView.updateListener.of((u) => {
if (!u.docChanged) return;
if (u.transactions.every((tr) => !tr.docChanged || savedFinalNewline(tr))) {
const preparing = preparingViews.get(u.view);
if (preparing?.doc === u.startState.doc) preparing.doc = u.state.doc;
return;
}
if (u.startState.field(runField).ask) askAnswers.get(u.view)?.("cancel");
}),
ViewPlugin.define((view) => ({
destroy: () => {
closedViews.add(view);
askAnswers.get(view)?.("cancel");
},
})),
];
/** Views destroyed with a question open: nothing more to dispatch to them. */
const closedViews = new WeakSet<EditorView>();
/** Shows `mark` in the banner and waits for the answer. */
function ask(view: EditorView, mark: AskMark): Promise<AskChoice> {
askAnswers.get(view)?.("cancel");
return new Promise<AskChoice>((resolve) => {
askAnswers.set(view, (choice) => {
askAnswers.delete(view);
if (!closedViews.has(view) && view.state.field(runField, false)?.ask) view.dispatch({ effects: setAsk.of(null) });
resolve(choice);
});
view.dispatch({ effects: setAsk.of(mark) });
});
}
/** Shows the unsafe-query banner for `statement` and waits for the answer (true: run it). */
export function confirmUnsafe(view: EditorView, path: string, current: () => boolean): ConfirmUnsafe {
return async (statement, unsafe) => {
if (!current()) return false;
if (unsafeSuppressed.has(path)) return true;
const len = view.state.doc.length;
const choice = await ask(view, {
from: Math.min(len, statement.from + unsafe.from),
to: Math.min(len, statement.from + unsafe.to),
message: unsafeMessage(unsafe),
});
if (choice === "suppress") unsafeSuppressed.add(path);
return choice !== "cancel";
};
}
export const setPreview = StateEffect.define<readonly { from: number; to: number }[]>();
/**
* The range the console's next Execute would submit, bordered on the text (DataGrip's current
* statement border): the caret's statement, or the selection's — the statements `db_statements`
* splits that range into, the very call the run itself makes.
*/
const previewField = StateField.define<readonly { from: number; to: number }[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setPreview)) return e.value;
if (!tr.docChanged) return value;
// The preview is of the text it was computed for; edits only move where that is.
const next: { from: number; to: number }[] = [];
for (const r of value) {
const from = tr.changes.mapPos(r.from, 1);
const to = tr.changes.mapPos(r.to, -1);
if (from < to) next.push({ from, to });
}
return next;
},
});
/** The bordered ranges: a run in progress keeps its submitted range, whatever the caret does. */
export function previewRanges(state: EditorState): readonly { from: number; to: number }[] {
const ex = state.field(runField, false)?.executing;
const ranges = ex?.spans.length
? [{ from: ex.spans[0]!.from, to: ex.spans[ex.spans.length - 1]!.to }]
: (state.field(previewField, false) ?? []);
return ranges.filter((r) => r.from < r.to);
}
const PREVIEW_CLASS = "cm-openidea-db-preview";
/**
* One box around each statement's text: the union of its lines' text (indentation and trailing
* blanks left out), as tall as the statement even where it runs out of view.
*/
function previewBoxes(view: EditorView): RectangleMarker[] {
const { doc } = view.state;
const boxes: RectangleMarker[] = [];
for (const r of previewRanges(view.state)) {
let left = Infinity;
let right = -Infinity;
let offset: number | null = null;
for (const visible of view.visibleRanges) {
const from = Math.max(r.from, visible.from);
const to = Math.min(r.to, visible.to);
if (from >= to) continue;
for (let pos = from; pos <= to;) {
const line = doc.lineAt(pos);
const text = line.text;
let start = Math.max(from, line.from) - line.from;
let end = Math.min(to, line.to) - line.from;
while (start < end && /\s/.test(text[start]!)) start++;
while (end > start && /\s/.test(text[end - 1]!)) end--;
if (start < end)
for (const m of RectangleMarker.forRange(
view,
PREVIEW_CLASS,
EditorSelection.range(line.from + start, line.from + end),
)) {
left = Math.min(left, m.left);
right = Math.max(right, m.left + (m.width ?? 0));
offset ??= m.top - view.lineBlockAt(line.from).top;
}
pos = line.to + 1;
}
}
if (offset == null || right <= left) continue;
const top = view.lineBlockAt(r.from).top + offset;
const bottom = view.lineBlockAt(r.to).bottom + offset;
boxes.push(new RectangleMarker(PREVIEW_CLASS, left - 2, top, right - left + 4, bottom - top));
}
return boxes;
}
const previewLayer = layer({
above: false,
markers: previewBoxes,
update: (u) =>
u.docChanged ||
u.viewportChanged ||
u.geometryChanged ||
u.startState.field(previewField, false) !== u.state.field(previewField, false) ||
u.startState.field(runField, false)?.executing !== u.state.field(runField, false)?.executing,
});
export const executionMarks = [runField, runGutter, cancelAskOnEdit, previewField, previewLayer];
type StatementSpan = { from: number; to: number };
type RunOutcome = { index: number; error: string | null; ms: number | null };
let nextExecution = 0;
const preparingViews = new WeakMap<EditorView, { doc: Text }>();
/** Track the submitted ranges through edits, without changing the editor selection. */
export function trackExecution(view: EditorView, bannerFor?: (error: string) => string) {
const token = ++nextExecution;
const sent = view.state.doc;
askAnswers.get(view)?.("cancel");
const preparing = { doc: sent };
preparingViews.set(view, preparing);
const current = () =>
!closedViews.has(view) && view.state.doc === preparing.doc && preparingViews.get(view) === preparing;
return {
current,
start(spans: readonly StatementSpan[]) {
const st = view.state.field(runField, false);
const first = spans[0],
last = spans.at(-1);
// The offsets are into the text sent; an edit while preparing leaves them unplaced.
if (!st || !current() || !first || !last) return;
const marks = st.marks.filter((mark) => mark.to <= first.from || mark.from >= last.to);
view.dispatch({ effects: setRun.of({ marks, banner: null, executing: { token, spans, active: null } }) });
},
update(active: Executing["active"], outcomes: readonly RunOutcome[] = []) {
const st = view.state.field(runField, false);
const ex = st?.executing;
const placed = new Map<number, StatementSpan>();
if (!st || ex?.token !== token) return placed;
const marks = [...st.marks];
let banner = st.banner;
for (const { index, error, ms } of outcomes) {
const span = ex.spans[index];
if (!span || span.from >= span.to) continue;
const { from, to } = span;
marks.push({
from,
to,
timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to,
error,
ms,
});
if (error && bannerFor) banner = bannerFor(error);
placed.set(index, span);
}
view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) });
return placed;
},
end() {
if (preparingViews.get(view) === preparing) preparingViews.delete(view);
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
},
};
}
+27 -1
Переглянути файл
@@ -19,8 +19,9 @@ import {
type TableCommandTarget,
} from "./tableEditorFocus";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { projectLocation, useRemote } from "@/platform/remote";
import {
editorService,
registerEditorKind,
registerOverlay,
registerProjectViewRoot,
@@ -246,6 +247,14 @@ export function activate(): () => void {
}),
registerDatabaseWindow(),
registerResultsDestination(),
registerEditorKind({
kind: "db-workspace",
singleton: true,
component: lazyComponent(() => import("./WorkspaceEditor").then((m) => m.WorkspaceEditor)),
title: () => tx("Query Workspace"),
icon: () => "database",
keepAlive: true,
}),
registerEditorKind({
kind: TABLE_KIND,
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
@@ -321,6 +330,7 @@ export function activate(): () => void {
executions: {},
dialog: null,
newMenuOpen: false,
workspaceSettingsRequest: null,
});
}),
useDatabase.subscribe((s, prev) => {
@@ -367,6 +377,22 @@ export function activate(): () => void {
when: "projectOpen",
run: () => toolWindowService().show(DB_TOOL_WINDOW, true),
},
{
id: "db.queryWorkspace",
title: "Query Workspace",
category: "Tools",
icon: "database",
keywords: ["cross-database", "join", "workspace"],
when: "projectOpen",
run: async ({ arg }) => {
const location = projectLocation(useProject.getState().project?.root);
if (!location) return;
const key = "db-workspace:" + location;
const current = projectRequest();
await editorService().openInput({ kind: "db-workspace", key }, { focus: true });
if (arg === "configure" && current()) useDatabase.setState({ workspaceSettingsRequest: key });
},
},
{
id: "db.newDataSource",
title: "New Data Source…",
+2
Переглянути файл
@@ -63,6 +63,7 @@ export function routineFolder(kind: DbRoutineInfo["kind"], separate = false): "r
type InSchema = Pick<TableRef, "id" | "catalog" | "schema">;
export type DbNode =
| { kind: "workspace"; key: string }
| { kind: "source"; key: string; source: DataSource }
| { kind: "sourceFolder"; key: string; folder: DbSourceFolder }
/** DuckDB's `catalog` stays on the session of `id`; other databases have their own target. */
@@ -85,6 +86,7 @@ export type DbNode =
/** The connection target a node belongs to. */
export function nodeTarget(n: DbNode): string | null {
if (n.kind === "workspace") return null;
if (n.kind === "source") return n.source.id ?? null;
if (n.kind === "sourceFolder" || n.kind === "message") return null;
if ("id" in n && typeof n.id === "string") return n.id;
+12 -11
Переглянути файл
@@ -147,22 +147,23 @@ class Parens {
}
}
/** Half-open token range of the statement containing the editor offset. */
export function statementTokenRange(tokens: readonly Token[], pos: number) {
let start = 0;
for (let i = 0; i < tokens.length; i++) {
if (!isP(tokens[i], ";")) continue;
if (tokens[i]!.to > pos) return { start, end: i };
start = i + 1;
}
return { start, end: tokens.length };
}
export function analyze(text: string, pos: number, driver: SqlDriver, lexed: Lexed = lex(text, driver)): Analysis {
const word = WORD_BEFORE.exec(text.slice(Math.max(0, pos - 256), pos))![0];
const prefix = { from: pos - word.length, text: word };
const all = lexed.tokens;
// The statement: between the `;` before the caret word and the next one.
let a = 0;
let b = all.length;
for (let i = 0; i < all.length; i++) {
if (!isP(all[i], ";")) continue;
if (all[i]!.to <= prefix.from) a = i + 1;
else {
b = i;
break;
}
}
const { start: a, end: b } = statementTokenRange(all, prefix.from);
const st = all.slice(a, b);
const sFrom = a > 0 ? all[a - 1]!.to : 0;
const sTo = b < all.length ? all[b]!.from : text.length;
+17 -9
Переглянути файл
@@ -2,7 +2,7 @@
* SQL tokens for completion and resolution: words, quoted identifiers, string
* literals, numbers and punctuation, with comments and whitespace dropped.
* Dialect-aware (MySQL backticks / `#` comments / backslash escapes,
* PostgreSQL dollar quoting, Snowflake `$$` strings / `//` comments / stages /
* PostgreSQL dollar quoting / nested comments, Snowflake `$$` strings / `//` comments / stages /
* variant paths). Offsets are UTF-16, like the editor's.
*/
import { sqlWordUpper, type SqlDriver } from "./dialect";
@@ -33,13 +33,21 @@ const STAGE_END = /[\s(),;']/;
const PATH_OWNER = /[\p{L}\p{N}_$)\]"']/u;
const TWO_CHAR = new Set(["::", "<=", ">=", "<>", "!=", "||", "->", "=>", ":="]);
function duckdbBlockCommentEnd(text: string, start: number): number {
const delimiter = /\/\*|\*\//g;
delimiter.lastIndex = start + 2;
let depth = 1;
for (let match = delimiter.exec(text); match; match = delimiter.exec(text)) {
depth += match[0] === "/*" ? 1 : -1;
if (depth === 0) return match.index;
function blockCommentEnd(text: string, from: number, nested: boolean): number {
const end = text.indexOf("*/", from);
if (!nested || end < 0) return end;
const inner = text.indexOf("/*", from);
if (inner < 0 || inner >= end) return end;
let depth = 2;
for (let i = inner + 2; i + 1 < text.length; i++) {
if (text.startsWith("/*", i)) {
depth++;
i++;
} else if (text.startsWith("*/", i)) {
if (--depth === 0) return i;
i++;
}
}
return -1;
}
@@ -90,7 +98,7 @@ export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed {
comments.push({ from: i, to, open: true });
i = to;
} else if (c === "/" && next === "*") {
const end = duckdb ? duckdbBlockCommentEnd(text, i) : text.indexOf("*/", i + 2);
const end = blockCommentEnd(text, i + 2, driver === "postgres" || duckdb);
const to = end < 0 ? n : end + 2;
comments.push({ from: i, to, open: end < 0 });
i = to;
+2
Переглянути файл
@@ -261,6 +261,7 @@ interface DatabaseState {
selectedNodes: DbNode[];
/** The toolbar's New popup is open. */
newMenuOpen: boolean;
workspaceSettingsRequest: string | null;
/** Expanded nodes of the Database tree. */
treeExpanded: Set<string>;
/** A tree node to select and scroll to (Go to Declaration from a console). */
@@ -350,6 +351,7 @@ export const useDatabase = create<DatabaseState>(() => ({
selectedNode: null,
selectedNodes: [],
newMenuOpen: false,
workspaceSettingsRequest: null,
treeExpanded: new Set(),
treeReveal: null,
paramValues: {},
+6
Переглянути файл
@@ -82,6 +82,7 @@ async function sourceFromClipboard() {
export function newMenu(): MenuItem[] {
return [
{ kind: "action", action: "db.newConsole", label: "Query Console" },
{ kind: "action", action: "db.queryWorkspace", label: "Query Workspace" },
sep,
...dataSourceItems(),
sep,
@@ -172,6 +173,11 @@ function batchSourceMenu(sources: Extract<DbNode, { kind: "source" }>[]): MenuIt
/** Context menu of a tree node (`null`: the empty area). */
export function nodeMenu(n: DbNode | null, selection: readonly DbNode[] = []): MenuItem[] {
if (!n) return [{ label: "New", icon: "plus", submenu: newMenu() }];
if (n.kind === "workspace")
return [
{ kind: "action", action: "db.queryWorkspace", label: "Query Workspace", icon: "db-console" },
{ kind: "action", action: "db.queryWorkspace", label: "Workspace Settings…", icon: "settings", arg: "configure" },
];
if (n.kind === "source") {
const sources = selection.filter((node): node is Extract<DbNode, { kind: "source" }> => node.kind === "source");
if (sources.length > 1) return batchSourceMenu(sources);
+273
Переглянути файл
@@ -0,0 +1,273 @@
import { describe, expect, it } from "vitest";
import type { DbCompletion, DbCompletionColumn } from "@/platform/ipc";
import { lex } from "./sql/lexer";
import {
workspaceJoinColumnOptions,
workspaceJoinColumnTarget,
workspaceJoinQuery,
workspaceSourceAliasError,
workspaceSourceResolver,
workspaceStatementRanges,
} from "./workspaceQuery";
const refs = [
{ id: "pg", name: 'Sales "EU"', alias: "crm", legacy: "left" },
{ id: "ch", name: "events", alias: "logs", legacy: "right" },
] as const;
const resolve = workspaceSourceResolver(refs);
const basic = "SELECT * FROM #left.public.users a JOIN #right.events.users b ON ";
const pair = (a: string, b: string) => `SELECT * FROM #${a}.public.users a JOIN #${b}.db.log b ON b.id=a.id`;
describe("saved workspace references", () => {
it("uses a saved name without setup, optional aliases and migrated shortcuts", () => {
for (const [a, b] of [
['"Sales ""EU"""', "events"],
["CRM", "logs"],
["left", "right"],
]) {
expect(workspaceJoinQuery(pair(a!, b!), resolve).tables.map((t) => t.sourceId)).toEqual(["pg", "ch"]);
}
const fresh = [
{ id: "a", name: "left" },
{ id: "b", name: "logs" },
];
expect(workspaceSourceResolver(fresh)("left")?.id).toBe("a");
expect(workspaceSourceResolver(fresh)("right")).toBeUndefined();
expect(() => workspaceJoinQuery(pair('""', "logs"), resolve)).toThrow();
});
it("never rebinds a deleted source's saved alias or old positional name", () => {
const available = [
{ id: "new", name: "left" },
{ id: "fresh", name: "crm" },
];
const resolve = workspaceSourceResolver(available, {
legacySources: { left: "removed", right: "" },
sourceAliases: { removed: "crm" },
});
expect(resolve("left")).toBeUndefined();
expect(resolve("CRM")).toBeUndefined();
expect(resolve("left", true)).toBeUndefined();
expect(resolve("crm", true)).toBeUndefined();
expect(resolve("CRM", true)).toBeUndefined();
});
it("keeps quoted positional references bound when a source is renamed", () => {
const resolve = workspaceSourceResolver([
{ id: "old", name: "Renamed", legacy: "left" },
{ id: "new", name: "left", alias: "replacement" },
]);
expect(resolve("left", true)?.id).toBe("old");
expect(resolve("replacement")?.id).toBe("new");
});
it("resolves quoted display names exactly and rejects ambiguous bare names", () => {
const sources = [
{ id: "a", name: "Sales", alias: "europe" },
{ id: "b", name: "SALES", alias: "asia" },
];
expect(workspaceSourceResolver(sources)("sales")).toBeNull();
expect(workspaceSourceResolver(sources)("Sales", true)?.id).toBe("a");
expect(workspaceSourceAliasError(sources)).toBeNull();
expect(workspaceSourceResolver(sources)("ASIA")?.id).toBe("b");
expect(() => workspaceJoinQuery(pair("sales", "asia"), workspaceSourceResolver(sources))).toThrow(
/Multiple sources/,
);
});
it.each(["events", "right", "two words", "a.b", "#crm", "1crm"])(
"rejects conflicting or invalid optional alias %s",
(alias) => {
expect(workspaceSourceAliasError([{ ...refs[0], alias }, refs[1]])).toBeTruthy();
expect(workspaceSourceAliasError([{ ...refs[0], alias: "события" }, refs[1]])).toBeNull();
},
);
it("uses table names by default, preserving old source-qualified drafts", () => {
for (const predicate of ["users.pk=log.pk", "left.pk=right.pk"]) {
const plan = workspaceJoinQuery(
"select * from #left.users /* first */ inner join #right.db.log on " + predicate,
resolve,
);
expect(plan.joins).toEqual([{ left: { relation: 0, column: "pk" }, rightColumn: "pk" }]);
expect(plan.tables[0]).toEqual({ sourceId: "pg", database: "", schema: "", table: "users" });
}
});
it("keeps old unaliased same-table-name drafts bound by source", () => {
const sql = "SELECT * FROM #left.public.t JOIN #right.logs.t ON left.id=right.id";
expect(workspaceJoinQuery(sql, resolve).joins[0]?.left.relation).toBe(0);
expect(() => workspaceJoinQuery(sql.replace("left.id", "t.id"), resolve)).toThrow();
});
it("preserves quoted identifiers and reversed keys", () => {
const q = 'SELECT * FROM #left."odd.schema"."a""b" AS a JOIN #right.events.lookup b ON b."Key"=a.id;';
const plan = workspaceJoinQuery(q, resolve);
expect(plan.tables[0]).toMatchObject({ sourceId: "pg", schema: "odd.schema", table: 'a"b' });
expect(plan.joins).toEqual([{ left: { relation: 0, column: "id" }, rightColumn: "Key" }]);
expect(plan.projection).toBeNull();
});
it.each(["a.id = a.id", "missing.id = b.id", "a.id = b.id; select 1", "a.id = b.id OR true", 'a.id = b."oops'])(
"rejects unsupported predicates %s",
(predicate) => {
expect(() => workspaceJoinQuery(basic + predicate, resolve)).toThrow();
},
);
it("bounds relations and rejects a projection referencing an unknown qualifier", () => {
const chain = (n: number) =>
"SELECT * FROM #left.s.t a0" +
Array.from({ length: n - 1 }, (_, i) => ` JOIN #right.s.t a${i + 1} ON a0.id=a${i + 1}.id`).join("");
expect(workspaceJoinQuery(chain(8), resolve).tables).toHaveLength(8);
expect(() => workspaceJoinQuery(chain(9), resolve)).toThrow(/eight/);
expect(() => workspaceJoinQuery(chain(2).replace("*", "other.id"), resolve)).toThrow();
});
it("uses only the statement at the caret and ignores escaped delimiters and nested comments", () => {
const first = '-- 👋 ;\nSELECT * FROM #left.public."odd;name" a JOIN #right.db.t b ON a.id=b.id';
const second = "SELECT * FROM #left.public.other a /* nested /* ; */ still ; */ JOIN #right.db.t b ON a.id=b.id";
const text = " " + first + " ;\n\n " + second + ";\n-- comment only";
const start = text.indexOf(second);
expect(workspaceStatementRanges(text)).toEqual([
{ from: 2, to: first.length + 2 },
{ from: start, to: start + second.length },
]);
expect(workspaceJoinQuery(text, resolve, text.indexOf("odd")).tables[0]?.table).toBe("odd;name");
expect(workspaceJoinQuery(text, resolve, text.indexOf("nested")).tables[0]?.table).toBe("other");
expect(workspaceJoinQuery(text, resolve, text.length).tables[0]?.table).toBe("other");
expect(workspaceStatementRanges("-- nothing;\n;; ")).toEqual([]);
expect(() => workspaceJoinQuery(text, resolve)).toThrow();
});
});
describe("completion in workspace join keys", () => {
it("finds the current statement, with a quoted key prefix and escaped identifiers", () => {
const first = pair("left", "right") + ";\n";
const prefix = first + 'SELECT * FROM #logs."Log DB"."Event.Table" "b.Name" JOIN #crm."o.dd"."a""b" a ON ';
const a = prefix + "a.";
expect(workspaceJoinColumnTarget(a, resolve, lex(a, "postgres"))).toEqual({
sourceId: "pg",
database: "",
schema: "o.dd",
table: 'a"b',
from: a.length,
prefix: "",
quoted: false,
});
const b = prefix + 'a."User ID" /* comment */ = "b.Name"."Cust';
expect(workspaceJoinColumnTarget(b, resolve)).toEqual({
sourceId: "ch",
database: "",
schema: "Log DB",
table: "Event.Table",
from: b.indexOf('"Cust'),
prefix: "Cust",
quoted: true,
});
});
it.each([
"a. -- b.",
"a. /* b.",
"a.id = 'b.",
"a.id = $q$b.",
"missing.",
"a.id = a.",
"a.id OR b.",
"a.id = b.id; SELECT x.",
"a.id = b.id ",
])("does not complete invalid or literal context %s", (predicate) => {
expect(workspaceJoinColumnTarget(basic + predicate, resolve)).toBeNull();
});
it("rejects missing sources, duplicate table aliases, oversized SQL and unfinished nested comments", () => {
const complete = (s: string) => workspaceJoinColumnTarget(s, resolve);
expect(complete(basic.replace("#left", "#gone") + "a.")).toBeNull();
expect(complete(basic.replace("users b", "users a") + "a.")).toBeNull();
expect(complete(basic + "a." + " ".repeat(65_536))).toBeNull();
expect(complete(basic + "/* outer /* inner */ a.")).toBeNull();
expect(complete(basic + "/* outer /* inner */ a. */ b.")).toMatchObject({ sourceId: "ch" });
expect(() => workspaceJoinQuery(basic + "/* outer /* inner */ a.id=b.id", resolve)).toThrow();
});
it.each(["sqlite", "mysql", "clickhouse"] as const)("preserves non-nested %s block comments", (driver) => {
expect(lex("/* outer /* inner */ value", driver).tokens.map((t) => t.text)).toEqual(["value"]);
});
it("uses the one exact catalog table and inserts safely quoted column names", () => {
const column = (name: string): DbCompletionColumn => ({
name,
dataType: "bigint",
primaryKey: false,
nullable: false,
hasDefault: false,
});
const catalog: DbCompletion = {
defaultSchema: "wrong",
foreignKeys: [],
tables: [
{ schema: "wrong", name: "users", kind: "table", columns: [column("wrong_table")] },
{ schema: "Public", name: "users", kind: "table", columns: [column("wrong_case")] },
{ schema: "public", name: "users", kind: "view", columns: [column("wrong_kind")] },
{
schema: "public",
name: "users",
kind: "table",
columns: ["id", "ID", "User ID", 'a"b', "select"].map(column),
},
],
};
const target = workspaceJoinColumnTarget(basic + "a.", resolve)!;
expect(workspaceJoinColumnOptions(target, catalog).map(({ label, apply }) => [label, apply])).toEqual([
["id", "id"],
["ID", '"ID"'],
["User ID", '"User ID"'],
['a"b', '"a""b"'],
["select", '"select"'],
]);
expect(
workspaceJoinColumnOptions(workspaceJoinColumnTarget(basic + "a.i", resolve)!, catalog).map((x) => x.label),
).toEqual(["id", "ID"]);
expect(
workspaceJoinColumnOptions(workspaceJoinColumnTarget(basic + 'a."I', resolve)!, catalog).map((x) => x.label),
).toEqual(["ID"]);
expect(workspaceJoinColumnOptions({ ...target, table: "unknown" }, catalog)).toEqual([]);
});
});
describe("saved sources in a Workspace", () => {
const sources = [
{ id: "pg", name: "accounts" },
{ id: "ch", name: "events" },
{ id: "duck", name: "Regional data", alias: "geo" },
{ id: "sq", name: "labels" },
];
const resolve = workspaceSourceResolver(sources);
const statement = `SELECT a.*, e.*, g.region, t.channel
FROM #accounts.workspace_fixture.public.customers a
JOIN #events.events.purchases e ON e.customer_id = a.id
JOIN #geo.geo.main.region_map g ON g.id = a.id
JOIN #labels.main.tags t ON t.zone = g.zone`;
it("compiles a real four-engine JOIN without assigning sides", () => {
expect(workspaceJoinQuery(statement, resolve)).toEqual({
tables: [
{ sourceId: "pg", database: "workspace_fixture", schema: "public", table: "customers" },
{ sourceId: "ch", database: "", schema: "events", table: "purchases" },
{ sourceId: "duck", database: "geo", schema: "main", table: "region_map" },
{ sourceId: "sq", database: "", schema: "main", table: "tags" },
],
joins: [
{ left: { relation: 0, column: "id" }, rightColumn: "customer_id" },
{ left: { relation: 0, column: "id" }, rightColumn: "id" },
{ left: { relation: 2, column: "zone" }, rightColumn: "zone" },
],
projection: [
{ relation: 0, column: null },
{ relation: 1, column: null },
{ relation: 2, column: "region" },
{ relation: 3, column: "channel" },
],
});
});
it("completes columns for the third and fourth inputs without an assigned side", () => {
expect(workspaceJoinColumnTarget(statement.slice(0, statement.lastIndexOf("g.zone") + 2), resolve)).toMatchObject({
sourceId: "duck",
database: "geo",
schema: "main",
table: "region_map",
});
});
it("rejects a join which does not link the new table to an earlier one", () => {
expect(() => workspaceJoinQuery(statement.replace("t.zone = g.zone", "a.id = e.customer_id"), resolve)).toThrow();
expect(() => workspaceJoinQuery(statement.replace("g.id = a.id", "g.id = t.id"), resolve)).toThrow();
});
});
+279
Переглянути файл
@@ -0,0 +1,279 @@
import { tx } from "@/platform/i18n";
import type { DbCompletion } from "@/platform/ipc";
import { statementTokenRange } from "./sql/analyze";
import { quoteIdent } from "./sql/complete";
import { identName, inLiteral, lex, type Lexed, type Token } from "./sql/lexer";
export interface WorkspaceSourceReference {
id: string;
name: string;
alias?: string;
legacy?: "left" | "right";
}
interface WorkspaceTableReference {
sourceId: string;
database: string;
schema: string;
table: string;
}
export const WORKSPACE_SQL_LIMIT = 65_536;
/** Resolve a whole project list once, retaining ambiguity instead of choosing the first duplicate. */
export function workspaceSourceResolver(
sources: readonly WorkspaceSourceReference[],
bindings?: { legacySources?: { left: string; right: string }; sourceAliases?: Record<string, string> },
) {
type Matches = Map<string, WorkspaceSourceReference | null>;
const exact: Matches = new Map();
const folded: Matches = new Map();
const reserved = new Map<string, WorkspaceSourceReference | undefined>();
for (const side of ["left", "right"] as const) {
if (bindings?.legacySources?.[side]) reserved.set(side, undefined);
}
const put = (index: Matches, key: string, source: WorkspaceSourceReference) => {
const previous = index.get(key);
index.set(key, previous === undefined || previous?.id === source.id ? source : null);
};
for (const source of sources) {
for (const name of [source.name, source.alias?.trim()]) {
if (!name) continue;
put(exact, name, source);
put(folded, name.toLowerCase(), source);
}
if (source.legacy) reserved.set(source.legacy, source);
}
if (bindings?.sourceAliases) {
const available = new Set(sources.map((source) => source.id));
for (const [id, alias] of Object.entries(bindings.sourceAliases)) {
if (alias.trim() && !available.has(id)) reserved.set(alias.trim().toLowerCase(), undefined);
}
}
return (name: string, quoted = false) => {
const key = name.toLowerCase();
// A saved draft can quote a bound alias. Its owner must survive renames and deletion.
if (reserved.has(key)) return reserved.get(key);
return quoted ? exact.get(name) : folded.get(key);
};
}
export function workspaceSourceAliasError(
sources: readonly WorkspaceSourceReference[],
resolve = workspaceSourceResolver(sources),
): string | null {
for (const source of sources) {
const alias = source.alias?.trim();
if (!alias) continue;
if (!/^[\p{L}_][\p{L}\p{N}_]*$/u.test(alias))
return tx("Start each SQL alias with a letter or underscore, then use letters, digits or underscores.");
if (resolve(alias)?.id !== source.id) return tx("Choose a SQL alias unique to this source.");
}
return null;
}
type ResolveSource = ReturnType<typeof workspaceSourceResolver>;
type Column = { relation: number; column: string };
type Projection = { relation: number; column: string | null };
type Join = { left: Column; rightColumn: string };
function parseJoin(
tokens: readonly Token[],
resolveSource: ResolveSource,
complete?: (table: WorkspaceTableReference) => void,
) {
let cursor = 0;
const take = (expected: string) => {
if (tokens[cursor]?.upper !== expected) return false;
cursor++;
return true;
};
const need = (expected: string) => {
if (!take(expected)) throw new Error(tx`Expected ${expected} in the workspace query.`);
};
const identifier = () => {
const token = tokens[cursor++];
if (token?.kind === "word") return token.text.toLowerCase();
if (token?.kind === "quoted" && /^"(?:[^"]|"")+"$/.test(token.text)) return identName(token);
throw new Error(tx("Expected an identifier in the workspace query."));
};
need("SELECT");
const fields: { owner: string; column: string | null }[] = [];
if (!take("*")) {
do {
const owner = identifier();
need(".");
fields.push({ owner, column: take("*") ? null : identifier() });
} while (take(","));
}
need("FROM");
const tables: WorkspaceTableReference[] = [];
const aliases: string[] = [];
const legacyQualifiers: (string | undefined)[] = [];
const relation = () => {
need("#");
const quoted = tokens[cursor]?.kind === "quoted";
const name = identifier();
const source = resolveSource(name, quoted);
if (source === null)
throw new Error(tx`Multiple sources match ${name}. Set a unique SQL alias in Workspace Settings.`);
if (!source) throw new Error(tx`Data source ${name} is unavailable. Type # to see available sources.`);
need(".");
const parts = [identifier()];
while (take(".")) {
if (parts.length === 3) throw new Error(tx("A table reference can include a database and a schema."));
parts.push(identifier());
}
const table = parts.pop()!;
const schema = parts.pop() ?? "";
const database = parts.pop() ?? "";
const explicit = take("AS") || (!!tokens[cursor] && !["INNER", "JOIN", "ON", ";"].includes(tokens[cursor]!.upper));
const alias = explicit ? identifier() : table;
if (aliases.some((existing, index) => existing === alias && (explicit || legacyQualifiers[index] === undefined)))
throw new Error(tx("Give each workspace table a distinct alias."));
aliases.push(alias);
// Earlier drafts could qualify an unaliased table by its source name.
legacyQualifiers.push(explicit ? undefined : name);
tables.push({ sourceId: source.id, database, schema, table });
};
const indexOfOwner = (name: string) => {
const index = aliases.indexOf(name);
if (index >= 0 && aliases.lastIndexOf(name) === index) return index;
const old = legacyQualifiers.indexOf(name);
if (old >= 0 && legacyQualifiers.lastIndexOf(name) === old) return old;
throw new Error(tx`Unknown or ambiguous table qualifier: ${name}.`);
};
const key = (candidate?: number): Column => {
const relation = indexOfOwner(identifier());
need(".");
if (
candidate !== undefined &&
(relation === candidate || (relation < tables.length - 1 && candidate < tables.length - 1))
)
throw new Error(tx("Each JOIN must compare the new table with an earlier table."));
if (cursor === tokens.length) complete?.(tables[relation]!);
return { relation, column: identifier() };
};
relation();
const joins: Join[] = [];
do {
take("INNER");
need("JOIN");
if (tables.length === 8) throw new Error(tx("A workspace query can join up to eight tables."));
relation();
need("ON");
const a = key();
need("=");
const b = key(a.relation);
joins.push(
a.relation === tables.length - 1 ? { left: b, rightColumn: a.column } : { left: a, rightColumn: b.column },
);
} while (tokens[cursor]?.upper === "INNER" || tokens[cursor]?.upper === "JOIN");
take(";");
if (cursor !== tokens.length) throw new Error(tx("Expected one SELECT with direct equality JOINs."));
const projection: Projection[] | null = fields.length
? fields.map(({ owner, column }) => ({ relation: indexOfOwner(owner), column }))
: null;
return { tables, joins, projection };
}
/** Split on SQL delimiters, matching the console's trimmed UTF-16 ranges and caret rules. */
export function workspaceStatementRanges(sql: string, caret?: number): { from: number; to: number }[] {
if (sql.length > WORKSPACE_SQL_LIMIT) throw new Error(tx("Workspace SQL exceeds 65,536 characters."));
const ranges: { from: number; to: number }[] = [];
let start = 0;
let hasCode = false;
const add = (end: number) => {
if (!hasCode) return;
const segment = sql.slice(start, end);
ranges.push({ from: end - segment.trimStart().length, to: start + segment.trimEnd().length });
hasCode = false;
};
for (const token of lex(sql, "postgres").tokens) {
if (token.kind === "punct" && token.text === ";") {
add(token.from);
start = token.to;
} else {
hasCode = true;
}
}
add(sql.length);
if (caret === undefined || !ranges.length) return ranges;
const next = ranges.findIndex(({ to }) => to >= caret);
if (next === -1) return [ranges.at(-1)!];
const current = ranges[next]!;
const previous = ranges[next - 1];
if (caret < current.from && previous && (sql.slice(previous.to, caret).match(/\n/g)?.length ?? 0) <= 1) {
return [previous];
}
return [current];
}
/** The host receives resolved identifiers and equality edges, never editor SQL. */
export function workspaceJoinQuery(sql: string, resolveSource: ResolveSource, caret?: number) {
if (sql.length > WORKSPACE_SQL_LIMIT) throw new Error(tx("Workspace SQL exceeds 65,536 characters."));
if (caret !== undefined) {
const range = workspaceStatementRanges(sql, caret)[0];
sql = range ? sql.slice(range.from, range.to) : "";
}
return parseJoin(lex(sql, "postgres").tokens, resolveSource);
}
export interface WorkspaceJoinColumnTarget extends WorkspaceTableReference {
from: number;
prefix: string;
quoted: boolean;
}
export function workspaceJoinColumnTarget(
sql: string,
resolveSource: ResolveSource,
lexed?: Lexed,
): WorkspaceJoinColumnTarget | null {
if (sql.length > WORKSPACE_SQL_LIMIT) return null;
const parsed = lexed ?? lex(sql, "postgres");
const literal = inLiteral(parsed, sql.length);
if (literal === "string" || literal === "comment") return null;
const { start } = statementTokenRange(parsed.tokens, sql.length);
const tokens = parsed.tokens.slice(start);
const last = tokens.at(-1);
const partial = last?.to === sql.length && (last.kind === "word" || last.kind === "quoted") ? last : undefined;
if (tokens.at(partial ? -2 : -1)?.text !== ".") return null;
let target: WorkspaceJoinColumnTarget | null = null;
try {
parseJoin(partial ? tokens.slice(0, -1) : tokens, resolveSource, (table) => {
target = {
...table,
from: partial?.from ?? sql.length,
prefix: partial ? identName(partial) : "",
quoted: partial?.kind === "quoted",
};
});
} catch {
// Completion parses an unfinished predicate and records its qualifier before the missing key.
}
return target;
}
/** Use workspace quoting for columns regardless of the selected table's database dialect. */
export function workspaceJoinColumnOptions(target: WorkspaceJoinColumnTarget, catalog: DbCompletion) {
const schema = target.schema || catalog.defaultSchema;
const table = catalog.tables.find(
(table) => table.kind === "table" && table.schema === schema && table.name === target.table,
);
const prefix = target.quoted ? target.prefix : target.prefix.toLowerCase();
const options = [];
for (const column of table?.columns ?? []) {
if (!(target.quoted ? column.name : column.name.toLowerCase()).startsWith(prefix)) continue;
options.push({
label: column.name,
apply: quoteIdent(column.name, "postgres"),
detail: column.dataType,
type: "property",
});
if (options.length === 100) break;
}
return options;
}
+34
Переглянути файл
@@ -1,6 +1,40 @@
{
"Duplicate Template": "Duplicate Template",
"No SQL client": "No SQL client",
"The saved DuckDB driver is unavailable.": "The saved DuckDB driver is unavailable.",
"SQL aliases": "SQL aliases",
"Workspace Settings…": "Workspace Settings…",
"Workspace Settings": "Workspace Settings",
"Type # to choose a saved data source.": "Type # to choose a saved data source.",
"Choose a DuckDB JDBC driver to run workspace SQL.": "Choose a DuckDB JDBC driver to run workspace SQL.",
"Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.": "Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.",
"SQL alias for {label}": "SQL alias for {label}",
"Set unique SQL aliases…": "Set unique SQL aliases…",
"Choose a SQL alias unique to this source.": "Choose a SQL alias unique to this source.",
"Multiple sources match {name}. Set a unique SQL alias in Workspace Settings.": "Multiple sources match {name}. Set a unique SQL alias in Workspace Settings.",
"Data source {name} is unavailable. Type # to see available sources.": "Data source {name} is unavailable. Type # to see available sources.",
"A table reference can include a database and a schema.": "A table reference can include a database and a schema.",
"Give each workspace table a distinct alias.": "Give each workspace table a distinct alias.",
"Unknown or ambiguous table qualifier: {name}.": "Unknown or ambiguous table qualifier: {name}.",
"Each JOIN must compare the new table with an earlier table.": "Each JOIN must compare the new table with an earlier table.",
"A workspace query can join up to eight tables.": "A workspace query can join up to eight tables.",
"Expected one SELECT with direct equality JOINs.": "Expected one SELECT with direct equality JOINs.",
"Use a short SQL name for a source. Leave it blank to use the connection name.": "Use a short SQL name for a source. Leave it blank to use the connection name.",
"Start each SQL alias with a letter or underscore, then use letters, digits or underscores.": "Start each SQL alias with a letter or underscore, then use letters, digits or underscores.",
"Workspace actions": "Workspace actions",
"Insert JOIN": "Insert JOIN",
"Query Workspace": "Query Workspace",
"Workspace SQL": "Workspace SQL",
"In memory": "In memory",
"Workspace DuckDB driver": "Workspace DuckDB driver",
"Select DuckDB driver": "Select DuckDB driver",
"Running query": "Running query",
"Workspace SQL exceeds 65,536 characters.": "Workspace SQL exceeds 65,536 characters.",
"Expected {expected} in the workspace query.": "Expected {expected} in the workspace query.",
"Expected an identifier in the workspace query.": "Expected an identifier in the workspace query.",
"The workspace can run up to 12 statements at a time.": "The workspace can run up to 12 statements at a time.",
"The workspace batch exceeds the result size limit.": "The workspace batch exceeds the result size limit.",
"Feedback": "Feedback",
"Quick Preview": "Quick Preview",
"No images to compare": "No images to compare",
"Image diff": "Image diff",
+34
Переглянути файл
@@ -1,4 +1,38 @@
{
"The saved DuckDB driver is unavailable.": "Сохранённый драйвер DuckDB недоступен.",
"SQL aliases": "SQL-алиасы",
"Workspace Settings…": "Настройки рабочей области…",
"Workspace Settings": "Настройки рабочей области",
"Type # to choose a saved data source.": "Введите #, чтобы выбрать сохранённый источник данных.",
"Choose a DuckDB JDBC driver to run workspace SQL.": "Выберите драйвер DuckDB JDBC для выполнения запросов.",
"Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.": "Сохраните хотя бы два источника PostgreSQL, ClickHouse, SQLite или файловых DuckDB.",
"SQL alias for {label}": "SQL-алиас для {label}",
"Set unique SQL aliases…": "Задать уникальные SQL-алиасы…",
"Choose a SQL alias unique to this source.": "Выберите уникальный SQL-алиас для этого источника.",
"Multiple sources match {name}. Set a unique SQL alias in Workspace Settings.": "Имени {name} соответствуют несколько источников. Задайте уникальный SQL-алиас в настройках рабочей области.",
"Data source {name} is unavailable. Type # to see available sources.": "Источник {name} недоступен. Введите #, чтобы увидеть доступные источники.",
"A table reference can include a database and a schema.": "В ссылке на таблицу можно указать базу данных и схему.",
"Give each workspace table a distinct alias.": "Задайте каждой таблице уникальный алиас.",
"Unknown or ambiguous table qualifier: {name}.": "Не удалось однозначно определить таблицу {name}.",
"Each JOIN must compare the new table with an earlier table.": "В каждом JOIN сравнивайте столбцы новой и одной из предыдущих таблиц.",
"A workspace query can join up to eight tables.": "В запросе рабочей области можно соединить до восьми таблиц.",
"Expected one SELECT with direct equality JOINs.": "Ожидается один SELECT с JOIN по равенству столбцов.",
"Use a short SQL name for a source. Leave it blank to use the connection name.": "Можно задать источнику короткое имя для SQL. По умолчанию используется имя подключения.",
"Start each SQL alias with a letter or underscore, then use letters, digits or underscores.": "Начните псевдоним с буквы или подчёркивания. Дальше можно использовать также цифры.",
"Workspace actions": "Действия рабочей области",
"Insert JOIN": "Вставить JOIN",
"Query Workspace": "Рабочая область запросов",
"Workspace SQL": "SQL рабочей области",
"In memory": "В памяти",
"Workspace DuckDB driver": "Драйвер DuckDB рабочей области",
"Select DuckDB driver": "Выберите драйвер DuckDB",
"Running query": "Выполняется запрос",
"Workspace SQL exceeds 65,536 characters.": "Текст SQL в рабочей области превышает 65 536 символов.",
"Expected {expected} in the workspace query.": "В запросе рабочей области ожидается {expected}.",
"Expected an identifier in the workspace query.": "В запросе рабочей области ожидается идентификатор.",
"The workspace can run up to 12 statements at a time.": "В рабочей области можно выполнить до 12 выражений за запуск.",
"The workspace batch exceeds the result size limit.": "Общий размер результатов превышает лимит рабочей области.",
"Feedback": "Выполнение",
"Create function '{name}'": "Создать функцию '{name}'",
"Create class '{name}'": "Создать класс '{name}'",
"Create method '{name}' in '{owner}'": "Создать метод '{name}' в '{owner}'",
+33
Переглянути файл
@@ -2,6 +2,39 @@
"Enable Git integration": "启用 Git 集成",
"Off, the IDE runs no git: repositories are not detected, and Git actions, menus and tool windows are hidden. Applies to all projects.": "关闭后 IDE 不运行 git:不检测仓库,并隐藏 Git 操作、菜单和工具窗口。对所有项目生效。",
"No SQL client": "没有 SQL 客户端",
"The saved DuckDB driver is unavailable.": "已保存的 DuckDB 驱动程序不可用。",
"SQL aliases": "SQL 别名",
"Workspace Settings…": "工作区设置…",
"Workspace Settings": "工作区设置",
"Type # to choose a saved data source.": "输入 # 选择已保存的数据源。",
"Choose a DuckDB JDBC driver to run workspace SQL.": "选择 DuckDB JDBC 驱动程序以运行工作区 SQL。",
"Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.": "请先保存至少两个 PostgreSQL、ClickHouse、SQLite 或基于文件的 DuckDB 数据源。",
"SQL alias for {label}": "{label} 的 SQL 别名",
"Set unique SQL aliases…": "设置唯一的 SQL 别名…",
"Choose a SQL alias unique to this source.": "请为此数据源选择唯一的 SQL 别名。",
"Multiple sources match {name}. Set a unique SQL alias in Workspace Settings.": "名称 {name} 匹配多个数据源。请在工作区设置中指定唯一的 SQL 别名。",
"Data source {name} is unavailable. Type # to see available sources.": "数据源 {name} 不可用。输入 # 查看可用数据源。",
"A table reference can include a database and a schema.": "表引用可以包含数据库和架构。",
"Give each workspace table a distinct alias.": "请为工作区中的每个表指定不同的别名。",
"Unknown or ambiguous table qualifier: {name}.": "表限定符 {name} 不存在或有歧义。",
"Each JOIN must compare the new table with an earlier table.": "每个 JOIN 都必须比较新表与前面的一个表。",
"A workspace query can join up to eight tables.": "工作区查询最多可以联接八个表。",
"Expected one SELECT with direct equality JOINs.": "应使用一条包含直接等值 JOIN 的 SELECT 语句。",
"Use a short SQL name for a source. Leave it blank to use the connection name.": "可以为数据源设置简短的 SQL 名称。留空时使用连接名称。",
"Start each SQL alias with a letter or underscore, then use letters, digits or underscores.": "SQL 别名须以字母或下划线开头,后续可用字母、数字或下划线。",
"Workspace actions": "工作区操作",
"Insert JOIN": "插入 JOIN",
"Query Workspace": "查询工作区",
"Workspace SQL": "工作区 SQL",
"Workspace DuckDB driver": "工作区 DuckDB 驱动",
"Select DuckDB driver": "选择 DuckDB 驱动",
"Running query": "正在执行查询",
"Workspace SQL exceeds 65,536 characters.": "工作区 SQL 超过 65,536 个字符。",
"Expected {expected} in the workspace query.": "工作区查询中应为 {expected}。",
"Expected an identifier in the workspace query.": "工作区查询中应为标识符。",
"The workspace can run up to 12 statements at a time.": "工作区一次最多可运行 12 条语句。",
"The workspace batch exceeds the result size limit.": "工作区的批处理结果超出大小限制。",
"Feedback": "执行反馈",
"Quick Preview": "快速预览",
"No images to compare": "没有可比较的图像",
"Image diff": "图像差异",