From bd396485c2d2d6fec8ebedc42423829ddd2988a9 Mon Sep 17 00:00:00 2001 From: Vladislav Kuzmin <67874880+principalwater@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:07:53 +0300 Subject: [PATCH] feat(database): support DuckDB SQL and browse attached catalogs (#6254) DuckDB sources get DuckDB's SQL dialect (highlighting, completion, formatting and resolution) and the database tree lists attached catalogs with their schemas, tables and columns. The JDBC bridge gains a catalogs command and catalog-scoped schema and table metadata, matched by exact catalog and schema names; tables in another catalog open and page through the source session. DDL that attaches, detaches or changes a catalog refreshes the tree. Co-authored-by: principalwater <67874880+principalwater@users.noreply.github.com> --- crates/ide-db/src/jdbc/mod.rs | 82 +++++++ crates/ide-db/src/lib.rs | 151 ++++++++++-- crates/ide-db/tests/jdbc.rs | 111 ++++++++- crates/ide-host/src/ops/db.rs | 51 ++++ docs/en/guide/database.mdx | 11 + docs/zh/guide/database.mdx | 11 + e2e/duckdb-catalog.spec.ts | 113 +++++++++ java/jdbc-bridge/openidea-jdbc-bridge.jar | Bin 19469 -> 19935 bytes .../src/ai/openidea/jdbc/OpenIdeaJdbc.java | 76 ++++-- java/jdbc-bridge/tests/SelfTest.java | 64 ++++- src-tauri/tests/commands.snap | 2 + src/bindings.ts | 2 + src/features/database/DatabaseView.test.tsx | 55 ++++- src/features/database/DatabaseView.tsx | 96 +++++--- src/features/database/TableEditor.tsx | 23 +- src/features/database/console.tsx | 52 ++-- src/features/database/consolePreview.test.tsx | 49 +++- src/features/database/index.ts | 4 +- src/features/database/model.ts | 9 +- src/features/database/nodes.ts | 45 ++-- .../database/requestLifecycle.test.ts | 94 ++++++++ src/features/database/sql/analyze.ts | 108 ++++++--- src/features/database/sql/complete.ts | 127 +++++++--- src/features/database/sql/dialect.ts | 133 ++++++++++- src/features/database/sql/duckdbHighlight.ts | 31 +++ src/features/database/sql/format.test.ts | 9 + src/features/database/sql/format.ts | 35 ++- src/features/database/sql/lexer.ts | 29 ++- src/features/database/sql/resolve.ts | 47 +++- src/features/database/sql/sql.test.ts | 120 +++++++++- src/features/database/sqlSupport.ts | 16 +- src/features/database/store.ts | 224 ++++++++++++++---- src/features/database/table-editor.test.tsx | 35 ++- src/features/database/tableInput.ts | 11 +- src/features/database/treeActions.ts | 23 +- src/features/database/treeMenu.ts | 8 + src/platform/locales/text/zh-TW.json | 2 + src/platform/locales/text/zh.json | 2 + 38 files changed, 1743 insertions(+), 318 deletions(-) create mode 100644 e2e/duckdb-catalog.spec.ts create mode 100644 src/features/database/sql/duckdbHighlight.ts diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs index e2a3761bb..2ac936c77 100644 --- a/crates/ide-db/src/jdbc/mod.rs +++ b/crates/ide-db/src/jdbc/mod.rs @@ -426,6 +426,8 @@ impl JdbcPool { self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await } + /// Introspection on this connection. `catalogs` lists live catalogs with the current one marked. + /// `schemas`, `tables`, `schemaColumns`, and `columns` accept a final catalog argument. pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult>>> { Ok(self.request(fields, "", &CancellationToken::new()).await?.rows) } @@ -706,6 +708,86 @@ mod tests { assert_eq!(by_table.len(), 2); } + #[tokio::test] + #[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] + async fn duckdb_live_catalog_metadata_is_scoped_to_the_requested_namespace() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() }; + let driver = DbJdbcDriver { + id: "duckdb".into(), + name: "DuckDB".into(), + vendor: None, + jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR")], + class_name: "org.duckdb.DuckDBDriver".into(), + url_template: String::new(), + }; + let pool = JdbcPool::connect(&source, None, driver, tmp.path().join("jdbc")).await?; + let stop = CancellationToken::new(); + let path = |file| tmp.path().join(file).to_string_lossy().replace('\'', "''"); + let archive = "archive.db:1"; + for sql in [ + "SET threads = 1".into(), + "CREATE TABLE memory.main.dupe (root_only INT)".into(), + format!("ATTACH '{}' AS first", path("first.duckdb")), + format!(r#"ATTACH '{}' AS "archive.db:1""#, path("archive.duckdb")), + "CREATE TABLE first.main.dupe (first_only INT PRIMARY KEY)".into(), + r#"CREATE TABLE "archive.db:1".main.dupe (archive_only INT)"#.into(), + r#"CREATE SCHEMA "archive.db:1"."qa_%""#.into(), + r#"CREATE SCHEMA "archive.db:1".qaSimilar"#.into(), + r#"CREATE TABLE "archive.db:1"."qa_%"."t_%""q" (quoted_only INT PRIMARY KEY)"#.into(), + r#"COMMENT ON TABLE "archive.db:1"."qa_%"."t_%""q" IS 'Archive table'"#.into(), + r#"COMMENT ON COLUMN "archive.db:1"."qa_%"."t_%""q".quoted_only IS 'In the archive'"#.into(), + r#"CREATE TABLE "archive.db:1".qaSimilar."t_%""q" (wrong_schema INT)"#.into(), + r#"COMMENT ON TABLE "archive.db:1".qaSimilar."t_%""q" IS 'Wrong schema table'"#.into(), + r#"COMMENT ON COLUMN "archive.db:1".qaSimilar."t_%""q".wrong_schema IS 'Outside the schema'"#.into(), + ] { + pool.query(&sql, 0, 1, &stop).await?; + } + + let catalogs = pool.metadata(&["catalogs"]).await?; + assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())])); + assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())])); + assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())])); + let schemas = pool.metadata(&["schemas", archive]).await?; + assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())])); + let tables = pool.metadata(&["tables", "qa_%", archive]).await?; + assert_eq!(tables.len(), 1); + assert_eq!(tables[0][0].as_deref(), Some(r#"t_%"q"#)); + assert_eq!(tables[0][2].as_deref(), Some("Archive table")); + + for (catalog, column, primary) in + [("memory", "root_only", "0"), ("first", "first_only", "1"), (archive, "archive_only", "0")] + { + let columns = pool.metadata(&["columns", "main", "dupe", catalog]).await?; + assert_eq!(columns.len(), 1); + assert_eq!(columns[0][0].as_deref(), Some(column)); + assert_eq!(columns[0][4].as_deref(), Some(primary)); + } + let quoted = pool.metadata(&["columns", "qa_%", r#"t_%"q"#, archive]).await?; + assert_eq!(quoted.len(), 1); + assert_eq!(quoted[0][0].as_deref(), Some("quoted_only")); + assert_eq!(quoted[0][4].as_deref(), Some("1")); + let all = schema_columns(pool.metadata(&["schemaColumns", "qa_%", archive]).await?); + assert_eq!(all.len(), 1); + assert_eq!(all[r#"t_%"q"#][0].name, "quoted_only"); + assert_eq!(all[r#"t_%"q"#][0].comment.as_deref(), Some("In the archive")); + + pool.query("USE first", 0, 1, &stop).await?; + let catalogs = pool.metadata(&["catalogs"]).await?; + assert!(catalogs.contains(&vec![Some("first".into()), Some("1".into())])); + let legacy = pool.metadata(&["columns", "main", "dupe"]).await?; + assert_eq!(legacy[0][0].as_deref(), Some("first_only")); + pool.query("USE memory", 0, 1, &stop).await?; + pool.query("DETACH first", 0, 1, &stop).await?; + let catalogs = pool.metadata(&["catalogs"]).await?; + assert!(!catalogs.iter().any(|r| r[0].as_deref() == Some("first"))); + assert!(pool.metadata(&["schemas", "first"]).await?.is_empty()); + assert!(pool.metadata(&["tables", "main", "first"]).await?.is_empty()); + assert!(pool.metadata(&["columns", "main", "dupe", "first"]).await?.is_empty()); + pool.close().await; + Ok(()) + } + #[test] fn result_codec_preserves_null_and_rejects_incomplete_frames() { let mut frame = diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index fa072581f..a86904311 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -43,7 +43,7 @@ use parking_lot::Mutex; use secrets::SecretStore; use serde::{Deserialize, Serialize}; use specta::Type; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -435,6 +435,41 @@ fn tunnel_target(source: &DataSource) -> (&str, u16) { (if source.host.trim().is_empty() { "localhost" } else { source.host.trim() }, port) } +fn is_duckdb(source: &DataSource) -> bool { + const PREFIX: &str = "jdbc:duckdb:"; + source.driver == DbDriver::Jdbc + && (source.vendor == "duckdb" + || source.url.trim().get(..PREFIX.len()).is_some_and(|url| url.eq_ignore_ascii_case(PREFIX))) +} + +async fn duckdb_catalog(pool: &Pool, database: &str) -> IdeResult> { + // List empty schemas too and put all schema names before the bounded table rows. + const MAX_CATALOG_ROWS: usize = 20_000; + let name = sql::quote_literal(DbDriver::Jdbc, database); + let query = format!( + "SELECT schema_name AS schema, NULL::VARCHAR AS name, NULL::VARCHAR AS kind, NULL::VARCHAR AS comment \ + FROM system.main.duckdb_schemas() WHERE database_name = {name} \ + UNION ALL \ + SELECT table_schema, table_name, lower(table_type), table_comment \ + FROM system.information_schema.tables WHERE table_catalog = {name} \ + ORDER BY name NULLS FIRST, schema LIMIT {MAX_CATALOG_ROWS}" + ); + let mut schemas = BTreeMap::>::new(); + for row in pool.rows(&query, MAX_CATALOG_ROWS).await? { + let mut values = row.into_iter(); + let Some(Some(schema)) = values.next() else { continue }; + let tables = schemas.entry(schema).or_default(); + if let Some(Some(name)) = values.next() { + tables.push(TableInfo { + name, + kind: DbTableKind::from_catalog(values.next().flatten().as_deref()), + comment: values.next().flatten().filter(|comment| !comment.is_empty()), + }); + } + } + Ok(schemas.into_iter().map(|(name, tables)| CatalogSchema { name, tables }).collect()) +} + pub fn split_target(target: &str) -> (&str, Option<&str>) { match target.split_once(':') { Some((id, db)) if !db.is_empty() => (id, Some(db)), @@ -1024,12 +1059,30 @@ impl DbManager { Ok(()) } - /// The databases of the server of data source `id` (PostgreSQL), the connected one first. + /// What databases this data source can see, including DuckDB's live attachments. pub async fn databases(&self, id: &str) -> IdeResult { let id = split_target(id).0; - let introspection = self.source(id)?.introspection; + let source = self.source(id)?; + let introspection = &source.introspection; let system = introspection.show_system; let pool = self.pool(id).await?; + if let Pool::Jdbc(p) = &*pool + && is_duckdb(&source) + { + let mut current = String::new(); + let mut names = Vec::new(); + for mut row in p.metadata(&["catalogs"]).await? { + if let [Some(name), active] = row.as_mut_slice() { + if active.as_deref() == Some("1") { + current = name.clone(); + names.insert(0, std::mem::take(name)); + } else if system || name != "system" { + names.push(std::mem::take(name)); + } + } + } + return Ok(Databases { current, names }); + } if pool.driver() == DbDriver::SqlServer { let first = |rows: Vec>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten()); @@ -1068,12 +1121,13 @@ impl DbManager { Ok(Databases { current, names }) } - /// The schemas of `database` of data source `id` with their tables and views (Snowflake): - /// what completion needs to follow `database.schema.table` without the tree being opened. - /// The result is also saved ([`DbManager::saved_catalog`]) for the next run. + /// The schemas of `database` with their tables and views for qualified SQL completion. + /// Snowflake's result is also saved ([`DbManager::saved_catalog`]) for the next run. pub async fn database_catalog(&self, id: &str, database: &str) -> IdeResult> { let id = split_target(id).0; - let schemas = match &*self.pool(id).await? { + let pool = self.pool(id).await?; + let schemas = match &*pool { + Pool::Jdbc(_) if is_duckdb(&self.source(id)?) => return duckdb_catalog(&pool, database).await, Pool::Snowflake(p) => snowflake::meta::catalog(p, database).await?, _ => return Err(IdeError::invalid("this data source does not list other databases")), }; @@ -1178,14 +1232,45 @@ impl DbManager { .collect()) } + async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult> { + let source = self.source(id)?; + if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" { + return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source")); + } + self.pool(id).await + } + + pub async fn catalog_table_details( + &self, + id: &str, + catalog: &str, + schema: &str, + table: &str, + ) -> IdeResult { + let pool = self.duckdb_catalog_pool(id).await?; + Self::table_details_on(&pool, Some(catalog), schema, table).await + } + pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult { let pool = self.pool(id).await?; - if let Pool::Snowflake(p) = &*pool { + Self::table_details_on(&pool, None, schema, table).await + } + + async fn table_details_on( + pool: &Pool, + catalog: Option<&str>, + schema: &str, + table: &str, + ) -> IdeResult { + if let Pool::Snowflake(p) = pool { return snowflake::meta::table_details(p, schema, table).await; } let driver = pool.driver(); - let rows = match &*pool { - Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?, + let rows = match pool { + Pool::Jdbc(p) => match catalog { + Some(catalog) => p.metadata(&["columns", schema, table, catalog]).await?, + None => p.metadata(&["columns", schema, table]).await?, + }, _ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?, }; let columns = rows @@ -1997,18 +2082,54 @@ impl DbManager { limit: u64, cancel: &CancellationToken, ) -> IdeResult { - let details = self.table_details(id, schema, table).await?; let pool = self.pool(id).await?; - let mut result = if let Pool::Jdbc(p) = &*pool { + Self::table_page_on(&pool, None, schema, table, filter, sort, offset, limit, cancel).await + } + + #[allow(clippy::too_many_arguments)] + pub async fn catalog_table_page( + &self, + id: &str, + catalog: &str, + schema: &str, + table: &str, + filter: Option<&str>, + sort: &[SortKey], + offset: u64, + limit: u64, + cancel: &CancellationToken, + ) -> IdeResult { + let pool = self.duckdb_catalog_pool(id).await?; + Self::table_page_on(&pool, Some(catalog), schema, table, filter, sort, offset, limit, cancel).await + } + + #[allow(clippy::too_many_arguments)] + async fn table_page_on( + pool: &Pool, + catalog: Option<&str>, + schema: &str, + table: &str, + filter: Option<&str>, + sort: &[SortKey], + offset: u64, + limit: u64, + cancel: &CancellationToken, + ) -> IdeResult { + let details = Self::table_details_on(pool, catalog, schema, table).await?; + let mut result = if let Pool::Jdbc(p) = pool { let q = &p.identifier_quote; - let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str())); + let names = + catalog.into_iter().chain((catalog.is_some() || !schema.is_empty()).then_some(schema)).chain([table]); if q.is_empty() - && names.into_iter().any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) + && names + .clone() + .chain(sort.iter().map(|k| k.column.as_str())) + .any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) { return Err(IdeError::invalid("This JDBC driver cannot quote the selected identifier")); } let quote = |s: &str| format!("{q}{}{q}", s.replace(q, &format!("{q}{q}"))); - let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) }; + let name = names.map(quote).collect::>().join("."); let sql = sql::table_select(&name, filter, sort, quote); p.page(&sql, offset, limit, cancel).await? } else { diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs index e0a7a5253..bd4ed70b3 100644 --- a/crates/ide-db/tests/jdbc.rs +++ b/crates/ide-db/tests/jdbc.rs @@ -122,9 +122,12 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> { let db = manager(tmp.path()); let c = CancellationToken::new(); db.execute("test", "create table items(id int primary key, label varchar)", 1, &c).await?; + db.execute("test", "comment on table items is 'Local items'", 1, &c).await?; db.execute("test", "insert into items values (1, NULL), (2, 'row')", 1, &c).await?; assert!(db.schemas("test").await?.iter().any(|v| v == "main")); - assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "items")); + let tables = db.tables("test", "main").await?; + let items = tables.iter().find(|table| table.name == "items").expect("items"); + assert_eq!(items.comment.as_deref(), Some("Local items")); let details = db.table_details("test", "main", "items").await?; assert_eq!(details.columns.len(), 2); let result = db.execute("test", "select id, label from items order by id", 1, &c).await?; @@ -154,6 +157,40 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> { assert!(!last.has_more); let past = db.table_page("test", "main", "items", None, &sort, 2, 1, &c).await?.result; assert!(past.rows.is_empty() && !past.has_more); + let path = tmp.path().join("attachment.duckdb"); + let path = ide_db::sql::quote_literal(DbDriver::Jdbc, &path.to_string_lossy()); + let catalog = "archive.db:'1"; + let quoted = ide_db::sql::quote_ident(DbDriver::Jdbc, catalog); + for statement in [ + format!("ATTACH {path} AS {quoted}"), + format!("CREATE SCHEMA {quoted}.empty"), + format!("CREATE TABLE {quoted}.main.items(remote_only INTEGER)"), + format!("COMMENT ON TABLE {quoted}.main.items IS 'Archived items'"), + format!("CREATE VIEW {quoted}.main.remote_view AS SELECT * FROM {quoted}.main.items"), + format!("COMMENT ON VIEW {quoted}.main.remote_view IS 'Archived view'"), + ] { + db.execute("test", &statement, 1, &c).await?; + } + let databases = db.databases("test").await?; + assert_eq!(databases.current, "local"); + assert!(databases.names.iter().any(|name| name == catalog)); + let schemas = db.database_catalog("test", catalog).await?; + assert!(schemas.iter().any(|schema| schema.name == "empty" && schema.tables.is_empty())); + let main = schemas.iter().find(|schema| schema.name == "main").expect("main"); + assert_eq!( + main.tables.iter().map(|table| (table.name.as_str(), table.kind, table.comment.as_deref())).collect::>(), + [ + ("items", ide_db::DbTableKind::Table, Some("Archived items")), + ("remote_view", ide_db::DbTableKind::View, Some("Archived view")), + ] + ); + assert!(db.saved_catalog("test").await?.is_none()); + db.execute("test", &format!("USE {quoted}"), 1, &c).await?; + assert_eq!(db.databases("test").await?.current, catalog); + db.execute("test", "USE local", 1, &c).await?; + db.execute("test", &format!("DETACH {quoted}"), 1, &c).await?; + assert!(!db.databases("test").await?.names.iter().any(|name| name == catalog)); + assert!(db.database_catalog("test", catalog).await?.is_empty()); db.disconnect("test").await; let reopened = manager(tmp.path()); assert_eq!(reopened.execute("test", "select count(*) from items", 1, &c).await?.rows, [vec![Some("2".into())]]); @@ -276,6 +313,78 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> { Ok(()) } +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] +async fn duckdb_named_catalog_page_uses_the_source_session_and_exact_names() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + register_duckdb(&db, Some("duckdb"))?; + db.save_sources(vec![DataSource { + id: "test".into(), + name: "DuckDB".into(), + driver: DbDriver::Jdbc, + vendor: "duckdb".into(), + global: true, + jdbc_driver: "duck".into(), + url: "jdbc:duckdb:".into(), + ..Default::default() + }]) + .await?; + + let stop = CancellationToken::new(); + let file = tmp.path().join("attachment.duckdb"); + let file = ide_db::sql::quote_literal(DbDriver::Jdbc, &file.to_string_lossy()); + let catalog = r#"archive.db:with/"quote"#; + let schema = "some.schema_%"; + let table = r#"same."table"#; + let quote = |name: &str| ide_db::sql::quote_ident(DbDriver::Jdbc, name); + let base_table = format!("memory.{}.{}", quote(schema), quote(table)); + let attached_table = format!("{}.{}.{}", quote(catalog), quote(schema), quote(table)); + db.execute_in_console( + "test", + &format!("ATTACH {file} AS {}", quote(catalog)), + 0, + 1, + &stop, + None, + Some(ConsoleId::new("window", "/attach.sql")), + ) + .await?; + for statement in [ + "SET threads = 1".into(), + format!("CREATE SCHEMA memory.{}", quote(schema)), + format!("CREATE SCHEMA {}.{}", quote(catalog), quote(schema)), + format!("CREATE TABLE {base_table} (base_only INTEGER PRIMARY KEY)"), + format!("CREATE TABLE {attached_table} (attached_only INTEGER PRIMARY KEY)"), + format!("INSERT INTO {base_table} VALUES (3)"), + format!("INSERT INTO {attached_table} VALUES (42), (41)"), + ] { + db.execute("test", &statement, 1, &stop).await?; + } + + let details = db.catalog_table_details("test", catalog, schema, table).await?; + assert_eq!(details.columns.len(), 1); + assert_eq!(details.columns[0].name, "attached_only"); + assert!(details.columns[0].primary_key); + let sort = [SortKey { column: "attached_only".into(), descending: true }]; + let attached = db.catalog_table_page("test", catalog, schema, table, None, &sort, 0, 1, &stop).await?; + assert_eq!(attached.result.rows, [vec![Some("42".into())]]); + assert!(attached.result.has_more); + assert_eq!(db.connected(), ["test"]); + + db.execute("test", &format!("USE {}.{}", quote(catalog), quote(schema)), 1, &stop).await?; + let initial = db.catalog_table_page("test", "memory", schema, table, None, &[], 0, 1, &stop).await?; + assert_eq!(initial.result.rows, [vec![Some("3".into())]]); + assert_eq!(initial.details.columns[0].name, "base_only"); + assert_eq!(db.databases("test").await?.current, catalog); + db.execute("test", "USE memory", 1, &stop).await?; + db.execute("test", &format!("DETACH {}", quote(catalog)), 1, &stop).await?; + assert!(db.catalog_table_page("test", catalog, schema, table, None, &[], 0, 1, &stop).await.is_err()); + assert_eq!(db.connected(), ["test"]); + db.disconnect("test").await; + Ok(()) +} + #[tokio::test] #[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] async fn duckdb_consoles_share_catalog_but_isolate_transactions_and_temporary_tables() -> IdeResult<()> { diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index fed9b293c..88c9bf801 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -329,6 +329,20 @@ pub async fn db_table_details( db.table_details(&id, &schema, &table).await } +#[command(trust = trusted)] +pub async fn db_catalog_table_details( + host: &Host, + window: &str, + id: String, + catalog: String, + schema: String, + table: String, +) -> IdeResult { + // Columns and keys in an attached DuckDB catalog on the source session. + let db = host.project(window)?.db.clone(); + db.catalog_table_details(&id, &catalog, &schema, &table).await +} + #[command(trust = trusted)] pub async fn db_table_grants( host: &Host, @@ -657,6 +671,41 @@ pub async fn db_table_page( result } +#[allow(clippy::too_many_arguments)] +#[command(trust = trusted)] +pub async fn db_catalog_table_page( + host: &Host, + window: &str, + request: RequestId, + id: String, + catalog: String, + schema: String, + table: String, + filter: Option, + sort: Vec, + offset: u32, + limit: u32, +) -> IdeResult { + // One read-only page from the explicit DuckDB catalog on the source session. + let db = host.project(window)?.db.clone(); + let cancel = host.begin_request(request); + let result = db + .catalog_table_page( + &id, + &catalog, + &schema, + &table, + filter.as_deref(), + &sort, + offset.into(), + limit.max(1).into(), + &cancel, + ) + .await; + host.end_request(request); + result +} + #[command(trust = trusted)] pub async fn db_apply_edits( host: &Host, @@ -788,6 +837,8 @@ ide_command::domain!( db_consoles, db_create_database, db_database_catalog, + db_catalog_table_details, + db_catalog_table_page, db_databases, db_ddl, db_disconnect, diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index a6119637b..aa7afcafb 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -151,6 +151,17 @@ Statements are split on `;`, respecting strings, comments and PostgreSQL dollar SQL completion knows the connected schema: tables after `FROM`/`JOIN` (with join conditions from foreign keys), columns in scope, and each dialect's keywords and functions. Unresolved tables and columns are flagged, and Go to Declaration, Quick Documentation and Reformat Code work in the console. See [SQL](/en/languages/sql) for SQL files in general. +In a DuckDB console, syntax highlighting, completion, and formatting understand DuckDB SQL, including `FROM`-first queries, `QUALIFY`, and star modifiers such as `EXCLUDE`. + +Attach an existing DuckDB file in the console to browse it on the current connection: + +```sql +ATTACH '/path/to/archive.duckdb' AS sales_archive (READ_ONLY); +FROM sales_archive.main.orders; +``` + +The **Database** tree lists each attached catalog with its schemas, tables, and views. Complete a qualified table name as `catalog.schema.table`, use **Go to Declaration** on it to reveal the table, or double-click a table in the tree to preview its rows. Preview tabs keep the catalog in their title so equally named tables are distinct. Attachments stay with the connection and disappear when disconnected. + ## Results and data editing Query results open in **Database Output** without taking focus from the editor. The window follows the active SQL console or file. Use the **SQL client** selector to inspect another client's output, results or query plans. The selector includes the data source when available. Choose **Open Client in Editor** to focus the selected file. Running or explaining a query in the active editor returns the window to that client. diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index e0409c825..fb18582eb 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -151,6 +151,17 @@ DuckDB 的各个控制台共享同一个数据库,包括内存数据库。SQLi SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外键给出连接条件)、补全作用域内的列,以及各方言的关键字和函数。无法解析的表和列会被标出,控制台中可以使用转到声明、快速文档和重新格式化代码。一般 SQL 文件的支持见 [SQL](/zh/languages/sql)。 +在 DuckDB 控制台中,语法高亮、补全和格式化支持 DuckDB SQL,包括以 `FROM` 开头的查询、`QUALIFY` 和 `EXCLUDE` 等星号修饰符。 + +在控制台中附加已有的 DuckDB 文件,即可使用当前连接浏览该文件: + +```sql +ATTACH '/path/to/archive.duckdb' AS sales_archive (READ_ONLY); +FROM sales_archive.main.orders; +``` + +**数据库** 树会显示每个附加目录及其架构、表和视图。可补全 `目录.架构.表` 形式的表名,使用 **转到声明** 在树中定位该表,或者双击树中的表预览数据。预览标签页的标题包含目录名称,可区分同名表。附加目录仅在当前连接中可用,断开连接后会消失。 + ## 结果与数据编辑 查询结果在 **数据库输出** 工具窗口中打开,焦点保留在编辑器。该窗口跟随当前的 SQL 控制台或文件。使用 **SQL 客户端** 选择器查看其他客户端的输出、结果和查询计划。选择器会在有数据源时显示其名称。点击 **在编辑器中打开客户端**,可在编辑器中聚焦所选文件。在当前编辑器运行查询或查看查询计划时,窗口会切回该客户端。 diff --git a/e2e/duckdb-catalog.spec.ts b/e2e/duckdb-catalog.spec.ts new file mode 100644 index 000000000..d7528916b --- /dev/null +++ b/e2e/duckdb-catalog.spec.ts @@ -0,0 +1,113 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const source = "duckdb-sandbox"; +const catalog = "archive.db:2026"; +const path = "/app-data/consoles/db/duckdb-sandbox/console.sql"; + +test("completes and browses DuckDB attachments on one source", async ({ workbench: page }, info) => { + await page.evaluate(async (path) => { + const workbench = "/src/workbench/contributions.ts"; + const { editorService } = await import(/* @vite-ignore */ workbench); + await editorService().openFile(path, { focus: true }); + }, path); + await stubDesktop(page); + await page.evaluate( + async ({ source, catalog, path }) => { + const column = { name: "Description", dataType: "VARCHAR", primaryKey: false, nullable: false, default: null }; + const details = { columns: [column], indexes: [], foreignKeys: [], triggers: [] }; + const orders = { name: "orders", kind: "table" }; + Object.assign(window.__ipc.handlers, { + db_sources: () => [{ id: source, name: "DuckDB Demo", driver: "jdbc", vendor: "duckdb", url: "jdbc:duckdb:" }], + db_connected: () => [source], + db_connect: () => null, + cancel_request: () => null, + db_schemas: () => ["main"], + db_databases: () => ({ current: "memory", names: ["memory", catalog] }), + db_database_catalog: ({ database }: { database: string }) => [ + { + name: "main", + tables: database === catalog ? [orders, { name: "order audit", kind: "view" }] : [orders], + }, + ], + db_completion: () => ({ + defaultSchema: "main", + tables: [{ schema: "main", ...orders, columns: [{ ...column, hasDefault: false }] }], + foreignKeys: [], + }), + db_catalog_table_details: () => details, + db_catalog_table_page: ({ catalog: selected }: { catalog: string }) => ({ + details, + offset: 0, + result: { + statement: `SELECT * FROM "${selected}"."main"."orders"`, + columns: [{ name: column.name, typeName: column.dataType }], + rows: [[selected === "memory" ? "Current order" : "Archived order"]], + elapsedMs: 1, + executionMs: 1, + hasMore: false, + truncated: [], + }, + }), + }); + const database = "/src/features/database/store.ts"; + const workbench = "/src/workbench/contributions.ts"; + const { bindConsole, loadSources } = await import(/* @vite-ignore */ database); + const { toolWindowService } = await import(/* @vite-ignore */ workbench); + await loadSources(); + bindConsole(path, source); + toolWindowService().show("database"); + }, + { source, catalog, path }, + ); + + const tree = page.getByRole("tree", { name: "Data sources" }); + const expand = (label: string) => + tree + .getByText(label, { exact: true }) + .last() + .locator("xpath=ancestor::*[@role='treeitem'][1]") + .locator("[data-tree-toggle]") + .click(); + await expand("DuckDB Demo"); + await expand("memory"); + await expand("main"); + await expand("tables"); + await tree.getByText("orders", { exact: true }).dblclick(); + await expect(page.getByRole("gridcell", { name: "Current order" })).toBeVisible(); + + await expand(catalog); + await expand("main"); + await expand("tables"); + await tree.getByText("orders", { exact: true }).last().dblclick(); + await expect(page.getByRole("gridcell", { name: "Archived order" })).toBeVisible(); + await expect(page.getByRole("tab", { name: "memory.main.orders", exact: true })).toBeVisible(); + await expect(page.getByRole("tab", { name: `${catalog}.main.orders`, exact: true })).toBeVisible(); + const pages = await ipcCalls(page, "db_catalog_table_page"); + expect(pages).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id: source, catalog: "memory", schema: "main", table: "orders" }), + expect.objectContaining({ id: source, catalog, schema: "main", table: "orders" }), + ]), + ); + expect(await ipcCalls(page, "db_table_page")).toEqual([]); + expect((await ipcCalls(page, "db_connect")).every(({ id }) => id === source)).toBe(true); + await page.screenshot({ path: info.outputPath("catalog-tree-after.png"), animations: "disabled" }); + + await page.getByRole("tab", { name: "console [DuckDB Demo]" }).click(); + const editor = page.locator(".cm-content[contenteditable=true]").first(); + const query = `SELECT * EXCLUDE (InternalNote)\nFROM "${catalog}".main.`; + const completion = page.locator(".cm-tooltip-autocomplete"); + const showCompletion = async () => { + await editor.click(); + await page.keyboard.press("Meta+a"); + await page.keyboard.insertText(query); + await page.keyboard.press("Control+Space"); + await expect(completion.getByText("orders", { exact: true })).toBeVisible(); + await expect(completion.getByText("order audit", { exact: true })).toBeVisible(); + }; + await showCompletion(); + await completion.getByText("orders", { exact: true }).click(); + await expect(editor).toContainText(`FROM "${catalog}".main.orders`); + await showCompletion(); + await page.screenshot({ path: info.outputPath("catalog-completion-after.png"), animations: "disabled" }); +}); diff --git a/java/jdbc-bridge/openidea-jdbc-bridge.jar b/java/jdbc-bridge/openidea-jdbc-bridge.jar index 78a8deb97887dccc047cadc9c61af19f12d0706d..cceb90cb889e3144ef0c27d08451886489ef0f07 100644 GIT binary patch delta 9771 zcmV+`Ce+!Dm;v9L0kFm$3J0~Ff0`u#0LW33&>by*Q|0;a^Smd?IY~}$DJev5k!zba zAdD3ag0xVi*cPP)R+wUFPH7}fYLbHJrc;@_xw(tZfpa=^>o(n{PJ5vfbQj#k{daSd zZO%D2KX-9+ca;JCKhJwk(xeRq+`jMQXY-!(p7(v;=YBh9`_9ROhX7!?vfTv&6cubb z*ujB+PVf!e~62UV)%gR&7#2Lzo_pE==?o@o2;dFT5(U zy<_2ex@)Anb#$X3L3V)~bQOwpD25V*DH3cnv2b-b9bVs??&(dprjtgv8^M-}UTa9; zjVhEOl#OE07*88JjHC+X2*sn*O^Nsp7kHt6LWRjXOkwyrXcOFMdI35m;8WiFt6Y4zpl3g0?#uO&dfI5nS1S z$j|1&JQe2aPzhBC)5dXhgV7V)Q{UU!X(WmG?M7!JX*9$;5)nz<4C}xG99>4xolp%m zDg<>{01FY$m22a)xT7naOc`myF&vMClaW>CeG0+8v2D$^^AXNz8n@V5w2XPaNQcGn z7NTc|k*?p9Hd3Rw6xvd?wVt`~Rvl`8VJRIVxj%v~dmbX5j>M z6=Jal%MsK~bsJW#t=qsSU8KWGs6)`@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--- a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java @@ -124,45 +124,73 @@ public final class OpenIdeaJdbc { return literal.replace(escape, escape + escape).replace("%", escape + "%").replace("_", escape + "_"); } - void schemas(DataOutputStream out) throws Exception { + void catalogs(DataOutputStream out) throws Exception { + String current = connection.getCatalog(); + header(out, "catalog", "current"); + try (ResultSet rs = connection.getMetaData().getCatalogs()) { + int n = 0; + while (rs.next() && n < 20000) { + String name = rs.getString("TABLE_CAT"); + if (name == null || name.isEmpty()) continue; + row(out, name, name.equals(current) ? "1" : "0"); + n++; + } + } + } + + void schemas(String catalog, DataOutputStream out) throws Exception { var m = connection.getMetaData(); header(out, "schema"); Set names = new TreeSet<>(); - try (ResultSet rs = m.getSchemas()) { + try (ResultSet rs = catalog == null ? m.getSchemas() : m.getSchemas(catalog, "%")) { while (rs.next() && names.size() < 20000) { + if (catalog != null && !catalog.equals(rs.getString("TABLE_CATALOG"))) continue; String s = rs.getString("TABLE_SCHEM"); if (s != null && !s.isEmpty()) names.add(s); } - } catch (SQLFeatureNotSupportedException ignored) {} - catalogs = names.isEmpty(); - namespaceKnown = true; - if (catalogs) { - try (ResultSet rs = m.getCatalogs()) { - while (rs.next() && names.size() < 20000) { - String s = rs.getString(1); - if (s != null && !s.isEmpty()) names.add(s); - } - } catch (SQLFeatureNotSupportedException ignored) {} + } catch (SQLFeatureNotSupportedException e) { + if (catalog != null) throw e; + } + if (catalog == null) { + catalogs = names.isEmpty(); + namespaceKnown = true; + if (catalogs) { + try (ResultSet rs = m.getCatalogs()) { + while (rs.next() && names.size() < 20000) { + String s = rs.getString(1); + if (s != null && !s.isEmpty()) names.add(s); + } + } catch (SQLFeatureNotSupportedException ignored) {} + } + if (names.isEmpty()) names.add(""); } - if (names.isEmpty()) names.add(""); for (String s : names) row(out, s); } void discoverNamespace() throws Exception { - if (!namespaceKnown) schemas(new DataOutputStream(OutputStream.nullOutputStream())); + if (!namespaceKnown) schemas(null, new DataOutputStream(OutputStream.nullOutputStream())); + } + + static boolean inNamespace(ResultSet rs, String catalog, String schema) throws SQLException { + return catalog == null + || (catalog.equals(rs.getString("TABLE_CAT")) && schema.equals(rs.getString("TABLE_SCHEM"))); } void metadata(String op, List a, DataOutputStream out) throws Exception { - discoverNamespace(); + int catalogIndex = op.equals("columns") ? 2 : 1; + String scope = a.size() > catalogIndex ? a.get(catalogIndex) : null; + if (scope == null) discoverNamespace(); var m = connection.getMetaData(); String name = a.get(0); - String catalog = catalogs && !name.isEmpty() ? name : connection.getCatalog(); - String schema = catalogs || name.isEmpty() ? null : pattern(m, name); + String catalog = scope != null ? scope : catalogs && !name.isEmpty() ? name : connection.getCatalog(); + String schemaName = scope == null && (catalogs || name.isEmpty()) ? null : name; + String schema = schemaName == null ? null : pattern(m, schemaName); if (op.equals("tables")) { header(out, "name", "kind", "comment"); try (ResultSet rs = m.getTables(catalog, schema, "%", null)) { int n = 0; while (rs.next() && n < 20000) { + if (!inNamespace(rs, scope, name)) continue; String type = rs.getString("TABLE_TYPE").toLowerCase(Locale.ROOT); if (!Set.of("table","base table","view","materialized view","system table","local temporary","foreign table").contains(type)) continue; row(out, rs.getString("TABLE_NAME"), type, rs.getString("REMARKS")); @@ -175,6 +203,7 @@ public final class OpenIdeaJdbc { try (ResultSet rs = m.getColumns(catalog, schema, "%", "%")) { int n = 0; while (rs.next() && n < 100000) { + if (!inNamespace(rs, scope, name)) continue; row(out, rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("NULLABLE") == 0 ? "0" : "1", rs.getString("COLUMN_DEF"), rs.getString("REMARKS")); n++; @@ -184,13 +213,17 @@ public final class OpenIdeaJdbc { header(out, "name", "type", "nullable", "default", "primary"); String table = a.get(1); Set keys = new HashSet<>(); - try (ResultSet rs = m.getPrimaryKeys(catalog, catalogs || name.isEmpty() ? null : name, table)) { - while (rs.next()) keys.add(rs.getString("COLUMN_NAME")); + try (ResultSet rs = m.getPrimaryKeys(catalog, schemaName, table)) { + while (rs.next()) { + if (inNamespace(rs, scope, name) && (scope == null || table.equals(rs.getString("TABLE_NAME")))) { + keys.add(rs.getString("COLUMN_NAME")); + } + } } catch (SQLFeatureNotSupportedException ignored) {} try (ResultSet rs = m.getColumns(catalog, schema, pattern(m, table), "%")) { int n = 0; while (rs.next() && n < 20000) { - if (!table.equals(rs.getString("TABLE_NAME"))) continue; + if (!inNamespace(rs, scope, name) || !table.equals(rs.getString("TABLE_NAME"))) continue; String col = rs.getString("COLUMN_NAME"); row(out, col, rs.getString("TYPE_NAME"), rs.getInt("NULLABLE") == 0 ? "0" : "1", rs.getString("COLUMN_DEF"), keys.contains(col) ? "1" : "0"); @@ -307,7 +340,8 @@ public final class OpenIdeaJdbc { reply.writeBoolean(true); switch (op) { case "open" -> open(a, reply, opener); - case "schemas" -> schemas(reply); + case "catalogs" -> catalogs(reply); + case "schemas" -> schemas(a.isEmpty() ? null : a.get(0), reply); case "tables", "columns", "schemaColumns" -> metadata(op, a, reply); case "namespace" -> { header(reply, "namespace"); diff --git a/java/jdbc-bridge/tests/SelfTest.java b/java/jdbc-bridge/tests/SelfTest.java index 1b31979f7..76ba45f92 100644 --- a/java/jdbc-bridge/tests/SelfTest.java +++ b/java/jdbc-bridge/tests/SelfTest.java @@ -36,13 +36,36 @@ public class SelfTest { case "getDatabaseProductVersion" -> "1"; case "getIdentifierQuoteString" -> "\""; case "getSearchStringEscape" -> "\\"; - case "getSchemas" -> rows(List.of(Map.of("TABLE_SCHEM", "app"))); - case "getTables" -> rows(List.of(Map.of( - "TABLE_NAME", "orders", "TABLE_TYPE", "TABLE", "REMARKS", "Orders table"))); - case "getColumns" -> "app".equals(a[1]) && "%".equals(a[2]) ? rows(List.of( - Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "id", "TYPE_NAME", "INT", "NULLABLE", 0), - Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1, - "COLUMN_DEF", "'none'", "REMARKS", "free text"))) : rows(List.of()); + case "getCatalogs" -> rows(List.of( + Map.of("TABLE_CAT", "root"), Map.of("TABLE_CAT", "archive.db:1"))); + case "getSchemas" -> a == null + ? rows(List.of(Map.of("TABLE_SCHEM", "app"))) + : Arrays.equals(a, new Object[]{"archive.db:1", "%"}) + ? rows(List.of( + Map.of("TABLE_CATALOG", "archive.db:1", "TABLE_SCHEM", "qa_%"), + Map.of("TABLE_CATALOG", "root", "TABLE_SCHEM", "outside_catalog"))) + : rows(List.of()); + case "getTables" -> Arrays.equals(a, new Object[]{"archive.db:1", "qa\\_\\%", "%", null}) + ? rows(List.of( + Map.of("TABLE_CAT", "archive.db:1", "TABLE_SCHEM", "qa_%", "TABLE_NAME", "items", + "TABLE_TYPE", "BASE TABLE", "REMARKS", "Archived items"), + Map.of("TABLE_CAT", "root", "TABLE_SCHEM", "qa_%", "TABLE_NAME", "outside_catalog", + "TABLE_TYPE", "BASE TABLE", "REMARKS", "Wrong catalog comment"), + Map.of("TABLE_CAT", "archive.db:1", "TABLE_SCHEM", "qaABC", "TABLE_NAME", "outside_schema", + "TABLE_TYPE", "BASE TABLE", "REMARKS", "Wrong schema comment"))) + : Arrays.equals(a, new Object[]{"root", "app", "%", null}) + ? rows(List.of(Map.of("TABLE_NAME", "orders", "TABLE_TYPE", "TABLE", "REMARKS", "Orders table"))) + : rows(List.of()); + case "getColumns" -> Arrays.equals(a, new Object[]{"archive.db:1", "qa\\_\\%", "%", "%"}) + ? rows(List.of( + Map.of("TABLE_CAT", "archive.db:1", "TABLE_SCHEM", "qa_%", "TABLE_NAME", "items", + "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1, "REMARKS", "archive label"), + Map.of("TABLE_CAT", "root", "TABLE_SCHEM", "qa_%", "TABLE_NAME", "outside_catalog", + "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1, "REMARKS", "outside label"))) + : "app".equals(a[1]) && "%".equals(a[2]) ? rows(List.of( + Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "id", "TYPE_NAME", "INT", "NULLABLE", 0), + Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1, + "COLUMN_DEF", "'none'", "REMARKS", "free text"))) : rows(List.of()); default -> throw new SQLFeatureNotSupportedException(); }); return proxy(Connection.class, (p, m, a) -> switch (m.getName()) { @@ -55,7 +78,7 @@ public class SelfTest { case "createStatement" -> statement(); case "isClosed" -> false; case "isValid" -> !dropped; - case "getCatalog" -> null; + case "getCatalog" -> "root"; default -> throw new SQLFeatureNotSupportedException(); }); } @@ -434,9 +457,30 @@ public class SelfTest { var columns = new String(reply(in), StandardCharsets.UTF_8); assert columns.contains("orders") && columns.contains("note") && columns.contains("'none'") : columns; assert columns.contains("comment") && columns.contains("free text") : columns; - send(out, 10, "tables", "app"); + send(out, 10, "catalogs"); + var catalogs = reply(in); + assert catalogs[0] == 1 : new String(catalogs, StandardCharsets.UTF_8); + var catalogRows = new String(catalogs, StandardCharsets.UTF_8); + assert catalogRows.contains("archive.db:1") && catalogRows.contains("root") : catalogRows; + send(out, 11, "schemas", "archive.db:1"); + var scoped = new String(reply(in), StandardCharsets.UTF_8); + assert scoped.contains("qa_%") && !scoped.contains("outside_catalog") : scoped; + send(out, 12, "tables", "qa_%", "archive.db:1"); var tables = new String(reply(in), StandardCharsets.UTF_8); - assert tables.contains("orders") && tables.contains("Orders table") : tables; + assert tables.contains("items") && tables.contains("Archived items") + && !tables.contains("outside_catalog") && !tables.contains("outside_schema") + && !tables.contains("Wrong catalog comment") && !tables.contains("Wrong schema comment") : tables; + send(out, 13, "schemas"); + var unscoped = new String(reply(in), StandardCharsets.UTF_8); + assert unscoped.contains("app") && !unscoped.contains("qa_%") : unscoped; + send(out, 14, "tables", "app"); + var genericTables = new String(reply(in), StandardCharsets.UTF_8); + assert genericTables.contains("orders") && genericTables.contains("Orders table") + && !genericTables.contains("items") : genericTables; + send(out, 15, "schemaColumns", "qa_%", "archive.db:1"); + var scopedComments = new String(reply(in), StandardCharsets.UTF_8); + assert scopedComments.contains("comment") && scopedComments.contains("archive label") + && !scopedComments.contains("outside label") : scopedComments; } finally { child.destroyForcibly().waitFor(); } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 02926df27..51b2cad91 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -109,6 +109,8 @@ cucumber_sources trusted desktop bin db_apply_edits trusted project_host bindings async db_approve_external_tunnel trusted desktop bindings async db_approve_jdbc_source trusted project_host bindings sync +db_catalog_table_details trusted project_host bindings async +db_catalog_table_page trusted project_host bindings async db_completion trusted project_host bindings async db_connect trusted project_host bindings async db_connected trusted project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 1928e90ab..025fb8380 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -352,6 +352,8 @@ export const commands = { /** Records the exact helper and destination reviewed in the local data-source dialog. */ dbApproveExternalTunnel: (source: DataSource_Deserialize) => typedError(__TAURI_INVOKE("db_approve_external_tunnel", { source })), dbApproveJdbcSource: (source: DataSource_Deserialize) => typedError(__TAURI_INVOKE("db_approve_jdbc_source", { source })), + dbCatalogTableDetails: (id: string, catalog: string, schema: string, table: string) => typedError(__TAURI_INVOKE("db_catalog_table_details", { id, catalog, schema, table })), + dbCatalogTablePage: (request: RequestId, id: string, catalog: string, schema: string, table: string, filter: string | null, sort: DbSortKey[], offset: number, limit: number) => typedError(__TAURI_INVOKE("db_catalog_table_page", { request, id, catalog, schema, table, filter, sort, offset, limit })), dbCompletion: (id: string) => typedError(__TAURI_INVOKE("db_completion", { id })), dbConnect: (id: string) => typedError(__TAURI_INVOKE("db_connect", { id })), dbConnected: () => typedError(__TAURI_INVOKE("db_connected")), diff --git a/src/features/database/DatabaseView.test.tsx b/src/features/database/DatabaseView.test.tsx index dc37717fc..7af687854 100644 --- a/src/features/database/DatabaseView.test.tsx +++ b/src/features/database/DatabaseView.test.tsx @@ -4,7 +4,8 @@ import { DatabaseView } from "./DatabaseView"; import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { registerDatabaseTreeActions } from "./treeActions"; -import { tablesKey, useDatabase } from "./store"; +import { schemasKey, tablesKey, useDatabase } from "./store"; +import { databaseKey, schemaNodeKey, treeIdentifier } from "./model"; import { tableInput } from "./tableInput"; import { useEditorRegistry } from "@/editor/api"; import { provideEditorService, provideToolWindowService, type EditorInput } from "@/workbench/contributions"; @@ -208,6 +209,58 @@ describe("Select Opened File", () => { }); }); +it("opens and reveals distinct DuckDB tables when the catalog is their only difference", async () => { + const id = "duck"; + const schema = "main"; + const table = 'items/"quoted'; + const catalogs = ["memory", "other.db:archive/one"]; + const schemas = Object.fromEntries( + catalogs.map((catalog) => [schemasKey(id, catalog), { status: "ok" as const, value: [schema] }]), + ); + const tables = Object.fromEntries( + catalogs.map((catalog) => [ + tablesKey(id, schema, catalog), + { status: "ok" as const, value: [{ name: table, kind: "table" as const }] }, + ]), + ); + const openInput = vi.fn(); + let active: EditorInput | null = null; + provideEditorService({ openInput, activeInput: () => active } as never); + provideToolWindowService({ show: vi.fn() } as never); + useDatabase.setState({ + sources: [{ id, name: "DuckDB", driver: "jdbc", vendor: "duckdb" }], + databases: { duck: { status: "ok", value: { current: "memory", names: catalogs } } }, + schemas, + tables, + details: {}, + objects: {}, + treeExpanded: new Set([ + id, + ...catalogs.flatMap((catalog) => { + const key = schemaNodeKey(id, schema, catalog); + return [databaseKey(id, catalog, true), key, `${key}/tables`]; + }), + ]), + }); + render(); + const tree = within(screen.getByRole("tree", { name: "Data sources" })); + const entries = tree.getAllByText(table); + expect(entries).toHaveLength(2); + const first = tableInput(id, schema, table, catalogs[0]); + active = tableInput(id, schema, table, catalogs[1]); + fireEvent.doubleClick(entries[0]!); + expect(openInput).toHaveBeenNthCalledWith(1, first, { focus: true }); + fireEvent.mouseDown(entries[1]!, { button: 0 }); + await act(() => executeAction("db.editData")); + expect(openInput).toHaveBeenNthCalledWith(2, active, { focus: true }); + expect(first.key).not.toBe(active.key); + await act(() => executeAction("db.selectOpened")); + await act(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); + expect(useDatabase.getState().selectedNode?.key).toBe( + `${schemaNodeKey(id, schema, catalogs[1])}/tables/${treeIdentifier(table, catalogs[1])}`, + ); +}); + describe("Expand All", () => { it("opens every loaded node and leaves unloaded ones closed", async () => { useDatabase.setState({ diff --git a/src/features/database/DatabaseView.tsx b/src/features/database/DatabaseView.tsx index e932e2073..15d9841e7 100644 --- a/src/features/database/DatabaseView.tsx +++ b/src/features/database/DatabaseView.tsx @@ -24,7 +24,16 @@ import { type TreeHandle, T, } from "@/ui"; -import { databaseKey, passesObjectFilter, shownNames, sourceIcon, splitTarget, targetOf } from "./model"; +import { + databaseKey, + passesObjectFilter, + schemaNodeKey, + shownNames, + sourceIcon, + splitTarget, + targetOf, + treeIdentifier, +} from "./model"; import { IntrospectionPicker } from "./IntrospectionPicker"; import { nodeTarget, @@ -40,7 +49,8 @@ import { import { connect, detailsKey, - listsDatabases, + duckdbCatalogTree, + listsTreeDatabases, loadDatabases, loadDetails, loadSchemas, @@ -51,6 +61,7 @@ import { openConsole, openObjectDdl, saveSourceVisibility, + schemasKey, tablesKey, useDatabase, type Loaded, @@ -203,8 +214,8 @@ export function DatabaseView() { const filter = sourceOf(id)?.introspection?.objectFilter; return (o: { name: string }) => passesObjectFilter(o.name, filter); }; - const tablesOf = (id: string, schema: string) => { - const t = st.tables[tablesKey(id, schema)]; + const tablesOf = (id: string, schema: string, catalog?: string) => { + const t = st.tables[tablesKey(id, schema, catalog)]; return t?.status === "ok" ? t.value.filter(shown(id)) : null; }; const routinesOf = (id: string, schema: string) => @@ -216,7 +227,9 @@ export function DatabaseView() { const othersOf = (id: string, schema: string, folder: Folder) => (st.objects[tablesKey(id, schema)]?.others ?? []).filter((o) => otherFolder(o.kind) === folder).filter(shown(id)); /** Members of a schema folder, after object filtering. */ - const folderSize = (id: string, schema: string, folder: Folder): number => { + const folderSize = (id: string, schema: string, folder: Folder, catalog?: string): number => { + if (catalog !== undefined) + return (tablesOf(id, schema, catalog) ?? []).filter((t) => tableFolder(t.kind) === folder).length; if (isOtherFolder(folder)) return othersOf(id, schema, folder).length; if (folder === "routines" || folder === "procedures" || folder === "functions") return routinesOf(id, schema).filter( @@ -226,8 +239,8 @@ export function DatabaseView() { if (folder === "sequences") return sequencesOf(id, schema).length; return (tablesOf(id, schema) ?? []).filter((t) => tableFolder(t.kind) === folder).length; }; - const detailsOf = (id: string, schema: string, table: string) => { - const d = st.details[detailsKey(id, schema, table)]; + const detailsOf = (id: string, schema: string, table: string, catalog?: string) => { + const d = st.details[detailsKey(id, schema, table, catalog)]; return d?.status === "ok" ? d.value : null; }; @@ -254,9 +267,15 @@ export function DatabaseView() { return shownNames(v.names, i?.allDatabases, i?.databases, v.current); }; - const schemasOf = (key: string, id: string, database: string | null) => - status(key, st.schemas[id], (v) => - shownSchemas(id, v, database).map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node), + const schemasOf = (key: string, id: string, database: string | null, catalog?: string) => + status(key, st.schemas[schemasKey(id, catalog)], (v) => + shownSchemas(id, v, database).map((schema): Node => ({ + kind: "schema", + key: schemaNodeKey(id, schema, catalog), + id, + schema, + catalog, + })), ); const children = (n: Node): readonly Node[] | undefined => { @@ -268,34 +287,38 @@ export function DatabaseView() { }); case "source": { const id = n.source.id ?? ""; - if (listsDatabases(n.source)) + if (listsTreeDatabases(n.source)) { + const duckdb = duckdbCatalogTree(n.source); return status(n.key, st.databases[id], (v) => shownDatabases(id, v).map((name) => ({ kind: "database", - key: databaseKey(id, name), - id: targetOf(id, name, v.current), + key: databaseKey(id, name, duckdb), + id: duckdb ? id : targetOf(id, name, v.current), name, current: name === v.current, + catalog: duckdb ? name : undefined, })), ); + } return schemasOf(n.key, id, null); } case "database": - return schemasOf(n.key, n.id, n.name); + return schemasOf(n.key, n.id, n.name, n.catalog); case "schema": - return status(n.key, st.tables[tablesKey(n.id, n.schema)], () => + return status(n.key, st.tables[tablesKey(n.id, n.schema, n.catalog)], () => folders - .filter((f) => folderSize(n.id, n.schema, f) > 0) + .filter((f) => folderSize(n.id, n.schema, f, n.catalog) > 0) .map((folder): Node => ({ kind: "folder", key: `${n.key}/${folder}`, id: n.id, schema: n.schema, + catalog: n.catalog, folder, })), ); case "folder": { - const at = { id: n.id, schema: n.schema }; + const at = { id: n.id, schema: n.schema, catalog: n.catalog }; if (n.folder === "routines" || n.folder === "procedures" || n.folder === "functions") // Overloads share a name: the key tells them apart by their arguments. return routinesOf(n.id, n.schema) @@ -327,12 +350,12 @@ export function DatabaseView() { sequence, ...at, })); - return (tablesOf(n.id, n.schema) ?? []) + return (tablesOf(n.id, n.schema, n.catalog) ?? []) .filter((t) => tableFolder(t.kind) === n.folder) - .map((table) => ({ kind: "table", key: `${n.key}/${table.name}`, table, ...at })); + .map((table) => ({ kind: "table", key: `${n.key}/${treeIdentifier(table.name, n.catalog)}`, table, ...at })); } case "table": { - const d = st.details[detailsKey(n.id, n.schema, n.table.name)]; + const d = st.details[detailsKey(n.id, n.schema, n.table.name, n.catalog)]; if (!d || d.status === "loading") return undefined; if (d.status === "error") return [{ kind: "message", key: `${n.key}/err`, text: d.message, error: true }]; return groupsOf(d.value).map((group) => ({ @@ -341,19 +364,20 @@ export function DatabaseView() { id: n.id, schema: n.schema, table: n.table.name, + catalog: n.catalog, group, })); } case "group": { - const d = detailsOf(n.id, n.schema, n.table); + const d = detailsOf(n.id, n.schema, n.table, n.catalog); if (!d) return undefined; const fkCols = new Set(d.foreignKeys.flatMap((k) => k.columns)); - const at = { id: n.id, schema: n.schema, table: n.table }; + const at = { id: n.id, schema: n.schema, table: n.table, catalog: n.catalog }; switch (n.group) { case "columns": return d.columns.map((column) => ({ kind: "column", - key: `${n.key}/${column.name}`, + key: `${n.key}/${treeIdentifier(column.name, n.catalog)}`, column, foreignKey: fkCols.has(column.name), ...at, @@ -382,11 +406,11 @@ export function DatabaseView() { if (!current()) return; if (!connected) { const err = { status: "error" as const, message: tx("Cannot connect") }; - if (listsDatabases(n.source)) useDatabase.setState((s) => ({ databases: { ...s.databases, [id]: err } })); + if (listsTreeDatabases(n.source)) useDatabase.setState((s) => ({ databases: { ...s.databases, [id]: err } })); else useDatabase.setState((s) => ({ schemas: { ...s.schemas, [id]: err } })); return; } - if (listsDatabases(n.source)) await loadDatabases(id); + if (listsTreeDatabases(n.source)) await loadDatabases(id); else await loadSchemas(id); } else if (n.kind === "database") { const current = databaseRequest(n.id); @@ -394,13 +418,13 @@ export function DatabaseView() { if (!current()) return; if (!connected) { useDatabase.setState((s) => ({ - schemas: { ...s.schemas, [n.id]: { status: "error", message: tx("Cannot connect") } }, + schemas: { ...s.schemas, [schemasKey(n.id, n.catalog)]: { status: "error", message: tx("Cannot connect") } }, })); return; } - await loadSchemas(n.id); - } else if (n.kind === "schema") await loadTables(n.id, n.schema); - else if (n.kind === "table") await loadDetails(n.id, n.schema, n.table.name); + await loadSchemas(n.id, n.catalog); + } else if (n.kind === "schema") await loadTables(n.id, n.schema, n.catalog); + else if (n.kind === "table") await loadDetails(n.id, n.schema, n.table.name, n.catalog); }; const picker = (n: Node, lead: boolean) => { @@ -410,9 +434,11 @@ export function DatabaseView() { const sourceId = source.id; const database = n.kind === "database" ? n.name : null; const target = n.kind === "database" ? n.id : sourceId; - const listDatabases = database === null && listsDatabases(source); + const listDatabases = database === null && listsTreeDatabases(source); const databases = listDatabases ? st.databases[sourceId] : undefined; - const schemas = listDatabases ? undefined : st.schemas[target]; + const schemas = listDatabases + ? undefined + : st.schemas[schemasKey(target, n.kind === "database" ? n.catalog : undefined)]; const intro = source.introspection; const name = label(n); const kind = @@ -573,7 +599,7 @@ export function DatabaseView() { case "sourceFolder": return String(n.folder.sources.length); case "folder": - return String(folderSize(n.id, n.schema, n.folder)); + return String(folderSize(n.id, n.schema, n.folder, n.catalog)); case "routine": return `(${n.routine.arguments})${n.routine.returns ? `: ${n.routine.returns}` : ""}`; case "sequence": @@ -583,7 +609,7 @@ export function DatabaseView() { case "trigger": return `${n.trigger.timing} ${n.trigger.events}`.trim(); case "group": { - const d = detailsOf(n.id, n.schema, n.table); + const d = detailsOf(n.id, n.schema, n.table, n.catalog); return d ? String(groupSize(d, n.group)) : undefined; } case "column": @@ -759,9 +785,9 @@ export function DatabaseView() { }) } onActivate={(n) => { - if (n.kind === "table") openTableData(n.id, n.schema, n.table.name); + 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") void openConsole(n.id); + else if (n.kind === "database" && n.catalog === undefined) void openConsole(n.id); else { const o = schemaObjectOf(n); if (o) void openObjectDdl(o.id, o.schema, o.kind, o.name); diff --git a/src/features/database/TableEditor.tsx b/src/features/database/TableEditor.tsx index 1af497733..8f0aa41d8 100644 --- a/src/features/database/TableEditor.tsx +++ b/src/features/database/TableEditor.tsx @@ -108,7 +108,7 @@ export function TableEditor({ input }: { input: EditorInput }) { const [loadedPage, setLoadedPage] = useState<{ key: string; page: DbTablePage | null; error: string | null } | null>( null, ); - const key = JSON.stringify([ref.id, ref.schema, ref.table, filter, sort, offset, limit, nonce]); + const key = JSON.stringify([ref.id, ref.catalog, ref.schema, ref.table, filter, sort, offset, limit, nonce]); const loading = loadedPage?.key !== key; const page = loadedPage?.page ?? null; const error = loadedPage?.error ?? null; @@ -120,7 +120,21 @@ export function TableEditor({ input }: { input: EditorInput }) { void (async () => { try { const p = await withConnection(ref.id, () => - call(commands.dbTablePage(id, ref.id, ref.schema, ref.table, filter || null, sort, offset, limit)), + call( + ref.catalog === undefined + ? commands.dbTablePage(id, ref.id, ref.schema, ref.table, filter || null, sort, offset, limit) + : commands.dbCatalogTablePage( + id, + ref.id, + ref.catalog, + ref.schema, + ref.table, + filter || null, + sort, + offset, + limit, + ), + ), ); setLoadedPage({ key, page: p, error: null }); setEdits(emptyEdits()); @@ -138,14 +152,15 @@ export function TableEditor({ input }: { input: EditorInput }) { return () => { if (!done) void commands.cancelRequest(id); }; - }, [key, ref.id, ref.schema, ref.table, filter, sort, offset, limit]); + }, [key, ref.id, ref.catalog, ref.schema, ref.table, filter, sort, offset, limit]); const columns = page?.result.columns ?? []; const names = columns.map((c) => c.name); const pk = page?.details.columns.filter((c) => c.primaryKey).map((c) => c.name) ?? []; const fkColumns = new Set(page?.details.foreignKeys.flatMap((k) => k.columns) ?? []); const source = sourceById(ref.id); - const editable = pk.length > 0 && !source?.readOnly && canModifyTable(source?.driver ?? "sqlite"); + const editable = + ref.catalog === undefined && pk.length > 0 && !source?.readOnly && canModifyTable(source?.driver ?? "sqlite"); const loaded = page?.result.rows.length ?? 0; const rowCount = loaded + edits.inserts.length; const gridColumns = useMemo( diff --git a/src/features/database/console.tsx b/src/features/database/console.tsx index 4bf47890b..b5b50b391 100644 --- a/src/features/database/console.tsx +++ b/src/features/database/console.tsx @@ -49,14 +49,7 @@ 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 DbDriver, - type DbSessionContext, - type DbStatementOutcome, - type SqlStatement, -} from "@/platform/ipc"; +import { call, commands, type DbSessionContext, type DbStatementOutcome, type SqlStatement } from "@/platform/ipc"; import { shortcutLabel } from "@/platform/keymap"; import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui"; import { useProject } from "@/platform/project"; @@ -81,6 +74,8 @@ import { type SqlCandidate, type SqlCatalog, } 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"; @@ -103,6 +98,7 @@ import { runSql, listsDatabases, loadDatabases, + loadDuckdbCatalog, loadSchemas, loadSources, loadTables, @@ -1248,7 +1244,7 @@ function docNode(text: string): Node { return pre; } -function applyCandidate(c: SqlCandidate, driver: DbDriver, sql: SqlText) { +function applyCandidate(c: SqlCandidate, driver: SqlDriver, sql: SqlText) { return (view: EditorView, completion: Completion, from: number, to: number) => { // A selected template placeholder is replaced, as CodeMirror's own string completions do. const sel = view.state.selection.main; @@ -1381,7 +1377,7 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl const id = consoleSource(path); const current = id ? databaseRequest(id) : projectRequest(); const source = sourceById(id); - const driver: DbDriver = source?.driver ?? "sqlite"; + const driver = sqlDriverOf(source); // A custom JDBC source (`driver: "jdbc"`) says nothing about how its server folds // identifiers; its URL does (`jdbc:oracle:thin:@…`). Quoting follows that dialect. const dialect = driver === "jdbc" ? jdbcDialect(source?.url) : null; @@ -1398,18 +1394,26 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl ? analyze(doc.slice(0, sel.from) + doc.slice(sel.to), sel.from, driver) : analyze(doc, ctx.pos, driver); if (!ctx.explicit && !shouldAutoCompleteSql(analysis)) return null; - const cataloged = driver === "snowflake" && !!id; - if (cataloged && analysis.qualifier?.length) { - await loadQualified(id, analysis.qualifier).catch(() => {}); - if (ctx.aborted || !current()) return null; + let catalog: SqlCatalog | undefined; + if (id && driver === "snowflake") { + if (analysis.qualifier?.length) await loadQualified(id, analysis.qualifier).catch(() => {}); + catalog = catalogOf(id); + } else if ( + id && + driver === "duckdb" && + analysis.context.kind === "table" && + (analysis.qualifier?.length ?? 0) < 3 + ) { + catalog = await loadDuckdbCatalog(id, analysis.qualifier?.[0]).catch(() => undefined); } + if (ctx.aborted || !current() || consoleSource(path) !== id) return null; const candidates = sqlCandidates({ model: scoped, analysis, driver, dialect, sourceName: source?.name ?? undefined, - catalog: cataloged ? catalogOf(id) : undefined, + catalog, }); if (!candidates.length) return null; return { @@ -1431,8 +1435,8 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl const noKeywords: CompletionSource = (ctx) => ({ from: ctx.pos, options: [] }); -function driverOf(path: string): DbDriver { - return sourceById(consoleSource(path))?.driver ?? "sqlite"; +function editorDriverOf(path: string): SqlDriver { + return sqlDriverOf(sourceById(consoleSource(path))); } /** @@ -1441,15 +1445,17 @@ function driverOf(path: string): DbDriver { */ function dialectColours(path: string): Extension { const slot = new Compartment(); - const colours = (driver: DbDriver): Extension => - driver === "snowflake" ? Prec.high(snowflakeLanguage().extension) : []; - const initial = driverOf(path); + const colours = (driver: SqlDriver): Extension => { + if (driver === "duckdb") return Prec.high(duckdbLanguage().extension); + return driver === "snowflake" ? Prec.high(snowflakeLanguage().extension) : []; + }; + const initial = editorDriverOf(path); return [ slot.of(colours(initial)), ViewPlugin.define((view) => { let shown = initial; const stop = useDatabase.subscribe(() => { - const driver = driverOf(path); + const driver = editorDriverOf(path); if (driver === shown) return; shown = driver; view.dispatch({ effects: slot.reconfigure(colours(driver)) }); @@ -1462,7 +1468,7 @@ function dialectColours(path: string): Extension { /** Live template contexts at a position (`sql-statement` / `sql-query` / `sql-code`). */ function templateContextsAt(path: string) { return (state: EditorState, pos: number): readonly string[] => - templateContexts(analyze(state.doc.toString(), pos, driverOf(path))); + templateContexts(analyze(state.doc.toString(), pos, editorDriverOf(path))); } /** @@ -1486,7 +1492,7 @@ function valuesInfo(path: string) { const sel = state.selection.main; if (!sel.empty) return null; const id = consoleSource(path); - const slot = valuesSlot(state.doc.toString(), sel.head, driverOf(path)); + const slot = valuesSlot(state.doc.toString(), sel.head, editorDriverOf(path)); if (!slot) return null; const table = id ? useDatabase diff --git a/src/features/database/consolePreview.test.tsx b/src/features/database/consolePreview.test.tsx index 09f0a14ce..dac1609a7 100644 --- a/src/features/database/consolePreview.test.tsx +++ b/src/features/database/consolePreview.test.tsx @@ -1,9 +1,12 @@ +import { CompletionContext } from "@codemirror/autocomplete"; +import { StandardSQL } from "@codemirror/lang-sql"; +import { ensureSyntaxTree } from "@codemirror/language"; import { act } from "@testing-library/react"; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useProject } from "@/platform/project"; -import { consoleExtension, executeInView, previewRanges } from "./console"; +import { completionSource, consoleExtension, executeInView, previewRanges } from "./console"; import { SQL_LANGUAGE } from "./sqlLanguage"; import { streamExecution } from "./executeStream.fixture"; import { useDatabase } from "./store"; @@ -106,7 +109,7 @@ function makeView(doc: string, anchor: number, head = anchor) { state: EditorState.create({ doc, selection: { anchor, head }, - extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never), + extensions: [StandardSQL.extension, consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never)], }), }); return view; @@ -115,6 +118,48 @@ function makeView(doc: string, anchor: number, head = anchor) { /** The text each execution-range box surrounds (jsdom has no layout to draw the boxes in). */ const bordered = (view: EditorView) => previewRanges(view.state).map((r) => view.state.sliceDoc(r.from, r.to)); +it("uses DuckDB completion and highlighting only for a bound DuckDB source", async () => { + const doc = "FROM read_parquet('sample.parquet') SELECT * EXCLUDE (\"My Col\") QUALIFY row_number() OVER () = 1"; + const view = makeView(doc, 0); + const parsed = (kind: string) => { + const found: string[] = []; + ensureSyntaxTree(view.state, doc.length, 1000)?.iterate({ + enter: (n) => { + if (n.name === kind) found.push(doc.slice(n.from, n.to)); + }, + }); + return found; + }; + const statements = async () => + (await completionSource(PATH)(new CompletionContext(EditorState.create(), 0, true)))?.options.map((o) => o.label); + try { + useDatabase.setState({ + sources: [ + { id: "named", driver: "jdbc", vendor: "duckdb", name: "DuckDB" }, + { id: "custom", driver: "jdbc", url: " JDBC:DUCKDB:example.duckdb ", name: "Custom DuckDB" }, + { id: "other", driver: "jdbc", vendor: "postgres", url: "jdbc:postgresql://localhost/duckdb" }, + ], + completion: Object.fromEntries( + ["named", "custom", "other"].map((id) => [id, { defaultSchema: "main", tables: [], foreignKeys: [] }]), + ), + }); + const checkDuckDB = async (id: string) => { + useDatabase.setState({ consoles: { [PATH]: id } }); + expect(parsed("Keyword")).toEqual(expect.arrayContaining(["FROM", "SELECT", "EXCLUDE", "QUALIFY", "OVER"])); + expect(parsed("Builtin")).toEqual(["read_parquet", "row_number"]); + expect(parsed("QuotedIdentifier")).toEqual(['"My Col"']); + expect(await statements()).toEqual(expect.arrayContaining(["FROM", "SUMMARIZE"])); + }; + await checkDuckDB("named"); + await checkDuckDB("custom"); + useDatabase.setState({ consoles: { [PATH]: "other" } }); + expect(parsed("Keyword")).not.toContain("QUALIFY"); + expect(await statements()).not.toContain("FROM"); + } finally { + view.destroy(); + } +}); + describe("the execution range preview", () => { it("borders the statement the caret is in, asking the splitter the run asks", async () => { const doc = "SELECT 1;\nSELECT 2;\nSELECT 3;"; diff --git a/src/features/database/index.ts b/src/features/database/index.ts index 3d4cab068..431534c4e 100644 --- a/src/features/database/index.ts +++ b/src/features/database/index.ts @@ -55,7 +55,7 @@ import { connect, loadSchemas, loadDatabases, - listsDatabases, + listsTreeDatabases, sourceById, newConsole, openConsole, @@ -354,7 +354,7 @@ export function activate(): () => void { const connected = await connect(id); if (!current()) return; if (!connected) throw new Error(tx("Database connection failed")); - if (listsDatabases(sourceById(id))) await loadDatabases(id); + if (listsTreeDatabases(sourceById(id))) await loadDatabases(id); else await loadSchemas(id); }, }, diff --git a/src/features/database/model.ts b/src/features/database/model.ts index 2aed387ac..cfcdec650 100644 --- a/src/features/database/model.ts +++ b/src/features/database/model.ts @@ -368,7 +368,14 @@ export function targetOf(id: string, database: string | null, current: string | } /** Key of the Database tree node of database `name` of data source `id`. */ -export const databaseKey = (id: string, name: string) => `${id}/@${name}`; +export const databaseKey = (id: string, name: string, catalog = false) => + `${id}/@${catalog ? encodeURIComponent(name) : name}`; + +export const treeIdentifier = (name: string, catalog?: string) => + catalog === undefined ? name : encodeURIComponent(name); + +export const schemaNodeKey = (id: string, schema: string, catalog?: string) => + catalog === undefined ? `${id}/${schema}` : `${databaseKey(id, catalog, true)}/${treeIdentifier(schema, catalog)}`; /** * `expanded` without the Database tree nodes that show what target `id` loaded (a data source diff --git a/src/features/database/nodes.ts b/src/features/database/nodes.ts index 6f086e4a6..7127e66f1 100644 --- a/src/features/database/nodes.ts +++ b/src/features/database/nodes.ts @@ -15,6 +15,7 @@ import type { DbTriggerInfo, } from "@/platform/ipc"; import type { DbObjectRef } from "./objects"; +import type { TableRef } from "./tableInput"; export type Group = "columns" | "keys" | "foreignKeys" | "indexes" | "triggers"; @@ -59,32 +60,27 @@ export function routineFolder(kind: DbRoutineInfo["kind"], separate = false): "r return kind === "procedure" ? "procedures" : "functions"; } -/** Where a table-level node lives: connection target, schema, table. */ -interface InTable { - id: string; - schema: string; - table: string; -} +type InSchema = Pick; export type DbNode = | { kind: "source"; key: string; source: DataSource } | { kind: "sourceFolder"; key: string; folder: DbSourceFolder } - /** A database of a PostgreSQL / SQL Server host; `id` is its connection target. */ - | { kind: "database"; key: string; id: string; name: string; current: boolean } - | { kind: "schema"; key: string; id: string; schema: string } - | { kind: "folder"; key: string; id: string; schema: string; folder: Folder } - | { kind: "table"; key: string; id: string; schema: string; table: DbTableInfo } + /** DuckDB's `catalog` stays on the session of `id`; other databases have their own target. */ + | { kind: "database"; key: string; id: string; name: string; current: boolean; catalog?: string } + | ({ kind: "schema"; key: string } & InSchema) + | ({ kind: "folder"; key: string; folder: Folder } & InSchema) + | ({ kind: "table"; key: string; table: DbTableInfo } & InSchema) | { kind: "routine"; key: string; id: string; schema: string; routine: DbRoutineInfo } | { kind: "package"; key: string; id: string; schema: string; package: DbPackageInfo } | { kind: "sequence"; key: string; id: string; schema: string; sequence: DbSequenceInfo } /** A stage, stream, task, pipe or file format: listed by name. */ | { kind: "object"; key: string; id: string; schema: string; object: DbSchemaObject } - | ({ kind: "group"; key: string; group: Group } & InTable) - | ({ kind: "column"; key: string; column: DbColumnInfo; foreignKey: boolean } & InTable) - | ({ kind: "key"; key: string; columns: string[] } & InTable) - | ({ kind: "foreignKey"; key: string; fk: DbForeignKey } & InTable) - | ({ kind: "index"; key: string; index: DbIndexInfo } & InTable) - | ({ kind: "trigger"; key: string; trigger: DbTriggerInfo } & InTable) + | ({ kind: "group"; key: string; group: Group } & TableRef) + | ({ kind: "column"; key: string; column: DbColumnInfo; foreignKey: boolean } & TableRef) + | ({ kind: "key"; key: string; columns: string[] } & TableRef) + | ({ kind: "foreignKey"; key: string; fk: DbForeignKey } & TableRef) + | ({ kind: "index"; key: string; index: DbIndexInfo } & TableRef) + | ({ kind: "trigger"; key: string; trigger: DbTriggerInfo } & TableRef) | { kind: "message"; key: string; text: string; error?: boolean }; /** The connection target a node belongs to. */ @@ -101,13 +97,18 @@ export function nodeSchema(n: DbNode): string | null { } /** The table (or view) a node is, or is inside of. */ -export function tableOf( - n: DbNode, -): { id: string; schema: string; table: string; view: boolean; kind: DbTableKind } | null { +export function tableOf(n: DbNode): (TableRef & { view: boolean; kind: DbTableKind }) | null { if (n.kind === "table") - return { id: n.id, schema: n.schema, table: n.table.name, view: n.table.kind !== "table", kind: n.table.kind }; + return { + id: n.id, + catalog: n.catalog, + schema: n.schema, + table: n.table.name, + view: n.table.kind !== "table", + kind: n.table.kind, + }; if ("table" in n && typeof n.table === "string") - return { id: n.id, schema: n.schema, table: n.table, view: false, kind: "table" }; + return { id: n.id, catalog: n.catalog, schema: n.schema, table: n.table, view: false, kind: "table" }; return null; } diff --git a/src/features/database/requestLifecycle.test.ts b/src/features/database/requestLifecycle.test.ts index 1e93bc86c..ba8078d47 100644 --- a/src/features/database/requestLifecycle.test.ts +++ b/src/features/database/requestLifecycle.test.ts @@ -1,13 +1,17 @@ +import { CompletionContext } from "@codemirror/autocomplete"; +import { EditorState } from "@codemirror/state"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { DataSource, ProjectInfo } from "@/platform/ipc"; import { useProject } from "@/platform/project"; const backend = vi.hoisted(() => ({ databases: vi.fn(), + catalog: vi.fn(), schemas: vi.fn(), tables: vi.fn(), objects: vi.fn(), details: vi.fn(), + catalogDetails: vi.fn(), connect: vi.fn(), disconnect: vi.fn(), completion: vi.fn(), @@ -31,10 +35,12 @@ vi.mock("@/platform/ipc", async (importOriginal) => { commands: { ...actual.commands, dbDatabases: backend.databases, + dbDatabaseCatalog: backend.catalog, dbSchemas: backend.schemas, dbTables: backend.tables, dbSchemaObjects: backend.objects, dbTableDetails: backend.details, + dbCatalogTableDetails: backend.catalogDetails, dbConnect: backend.connect, dbDisconnect: backend.disconnect, dbCompletion: backend.completion, @@ -62,11 +68,15 @@ import { renameSource, revealInTree, saveSource, + schemasKey, + tablesKey, + detailsKey, runSql, executeConsole, useDatabase, withConnection, } from "./store"; +import { completionSource } from "./console"; import { provideToolWindowService } from "@/workbench/contributions"; const initial = useDatabase.getState(); @@ -156,6 +166,90 @@ afterEach(() => { useDatabase.setState(initial, true); }); +it("loads distinct DuckDB catalog metadata on one source and discards detached entries on refresh", async () => { + const duck: DataSource = { id: "duck", name: "DuckDB", driver: "jdbc", vendor: "duckdb" }; + const catalog = "other.db:archive/one"; + const schema = "main"; + const table = "items"; + useDatabase.setState({ sources: [duck], loaded: true, connected: new Set(["duck"]) }); + backend.databases.mockResolvedValue(ok({ current: "memory", names: ["memory", catalog] })); + backend.catalog.mockImplementation(async (_id, name) => + ok([{ name: schema, tables: [{ name: table, kind: name === catalog ? "view" : "table" }] }]), + ); + backend.catalogDetails.mockResolvedValue(ok({ columns: [], indexes: [], foreignKeys: [], triggers: [] })); + + await loadDatabases("duck"); + await loadSchemas("duck", "memory"); + await loadSchemas("duck", catalog); + await loadDetails("duck", schema, table, catalog); + expect(backend.catalog).toHaveBeenCalledWith("duck", "memory"); + expect(backend.catalog).toHaveBeenCalledWith("duck", catalog); + expect(backend.catalogDetails).toHaveBeenCalledWith("duck", catalog, schema, table); + expect(backend.details).not.toHaveBeenCalled(); + expect(useDatabase.getState().tables[tablesKey("duck", schema, "memory")]).toEqual({ + status: "ok", + value: [{ name: table, kind: "table" }], + }); + expect(useDatabase.getState().tables[tablesKey("duck", schema, catalog)]).toEqual({ + status: "ok", + value: [{ name: table, kind: "view" }], + }); + + backend.catalog.mockClear(); + backend.databases.mockResolvedValue(ok({ current: "memory", names: ["memory"] })); + await refresh("duck"); + expect(backend.catalog.mock.calls).toEqual([["duck", "memory"]]); + expect(useDatabase.getState().schemas[schemasKey("duck", catalog)]).toBeUndefined(); + expect(useDatabase.getState().tables[tablesKey("duck", schema, catalog)]).toBeUndefined(); + expect(useDatabase.getState().details[detailsKey("duck", schema, table, catalog)]).toBeUndefined(); + expect([...useDatabase.getState().connected]).toEqual(["duck"]); +}); + +it("completes live DuckDB attachments through the source and refreshes after session commands", async () => { + const id = "duck"; + const path = "console.sql"; + const name = "archive.db:1"; + const duck: DataSource = { id, name: "DuckDB", driver: "jdbc", url: "jdbc:duckdb:" }; + useDatabase.setState({ sources: [duck], consoles: { [path]: id }, completion: { [id]: completion } }); + backend.databases.mockResolvedValue(ok({ current: "memory", names: ["memory", name] })); + backend.catalog.mockResolvedValue(ok([{ name: "Main", tables: [{ name: "archive_only", kind: "table" }] }])); + const complete = async (doc: string) => + (await completionSource(path)(new CompletionContext(EditorState.create({ doc }), doc.length, true)))?.options.map( + (option) => option.label, + ) ?? []; + + expect(await complete("select * from ")).toContain(name); + expect(backend.catalog).not.toHaveBeenCalled(); + expect(await complete('select * from "ARCHIVE.db:1".')).toEqual(["Main"]); + expect(await complete('select * from "archive.db:1".main.')).toEqual(["archive_only"]); + expect(backend.databases.mock.calls).toEqual([[id]]); + expect(backend.catalog.mock.calls).toEqual([[id, name]]); + expect(useDatabase.getState().databases[id]).toBeUndefined(); + expect(useDatabase.getState().catalogs[id]).toBeUndefined(); + + const success = (text: string) => ok([{ statement: { text, from: 0, to: text.length }, result: null, error: null }]); + const detach = '/* comment */ DETACH "archive.db:1"'; + backend.execute.mockResolvedValueOnce(success(detach)); + backend.databases.mockResolvedValueOnce(ok({ current: "memory", names: ["memory"] })); + expect(await runSql(id, [detach])).toBe(true); + expect(await complete('select * from "archive.db:1".main.')).toEqual([]); + expect(backend.catalog).toHaveBeenCalledOnce(); + + const next = deferred(); + backend.databases.mockResolvedValue(ok({ current: "memory", names: ["memory", name] })); + const attach = "ATTACH " + "':memory:'" + ' AS "archive.db:1"'; + backend.execute.mockResolvedValueOnce(success(attach)); + expect(await runSql(id, [attach])).toBe(true); + backend.catalog.mockReturnValueOnce(next.promise); + const pending = complete('select * from "archive.db:1".main.'); + await vi.waitFor(() => expect(backend.catalog).toHaveBeenCalledTimes(2)); + const use = 'USE "archive.db:1"'; + backend.execute.mockResolvedValueOnce(success(use)); + expect(await runSql(id, [use])).toBe(true); + next.resolve(ok([{ name: "Main", tables: [{ name: "stale", kind: "table" }] }])); + expect(await pending).toEqual([]); +}); + describe("database metadata request lifetimes", () => { it.each(cases)("loads $name normally", async (spec) => { await spec.load("pg"); diff --git a/src/features/database/sql/analyze.ts b/src/features/database/sql/analyze.ts index 87f330d0d..14f361502 100644 --- a/src/features/database/sql/analyze.ts +++ b/src/features/database/sql/analyze.ts @@ -5,8 +5,7 @@ * the caret (a statement, a table, a column expression, a join condition…). * Purely lexical: works on half-typed statements a parser would reject. */ -import type { DbDriver } from "@/platform/ipc"; -import { CLAUSE_WORDS, isReserved } from "./dialect"; +import { CLAUSE_WORDS, isReserved, nameMatcher, type SqlDriver } from "./dialect"; import { identName, inLiteral, lex, type Lexed, type Token } from "./lexer"; export interface TableRef { @@ -38,6 +37,7 @@ export type Clause = | "group" | "order" | "having" + | "qualify" | "limit" | "set" | "values" @@ -52,6 +52,7 @@ export type SqlContext = /** Right after a FROM / JOIN item (alias, JOIN, WHERE…). */ | { kind: "afterTable"; ref: TableRef } | { kind: "column"; clause: Clause } + | { kind: "exclude"; owner: string | null } | { kind: "joinCondition"; ref: TableRef } | { kind: "insertColumns"; target: TableRef } | { kind: "afterInsertColumns" }; @@ -74,6 +75,12 @@ export interface Analysis { lowerKeywords: boolean; /** The token before the caret word (and its qualifier), upper-cased: `(`, `UNION`… */ previous: string | null; + /** DuckDB: whether FROM precedes the projection in this block. */ + fromFirst?: boolean; + /** DuckDB: a projection star may take EXCLUDE, REPLACE or RENAME here. */ + projectionStar?: boolean; + /** DuckDB: projection names available in QUALIFY. */ + selectColumns?: string[]; } const WORD_BEFORE = /[\p{L}\p{N}_$]*$/u; @@ -100,8 +107,13 @@ const SET_OPS = new Set(["UNION", "INTERSECT", "EXCEPT"]); const QUERY_START = new Set(["SELECT", "WITH", "VALUES", "TABLE"]); /** The clause a keyword starts (Snowflake's QUALIFY filters like HAVING). */ -const clauseOf = (t: Token, driver: DbDriver): Clause | undefined => - CLAUSES[t.upper] ?? (driver === "snowflake" && t.upper === "QUALIFY" ? "having" : undefined); +const clauseOf = (t: Token, driver: SqlDriver): Clause | undefined => { + if (t.upper === "QUALIFY") { + if (driver === "duckdb") return "qualify"; + if (driver === "snowflake") return "having"; + } + return CLAUSES[t.upper]; +}; const isIdent = (t: Token | undefined): t is Token => !!t && (t.kind === "quoted" || (t.kind === "word" && !CLAUSE_WORDS.has(t.upper))); @@ -135,7 +147,7 @@ class Parens { } } -export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexed = lex(text, driver)): Analysis { +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; @@ -171,15 +183,19 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe if (isP(st[i], "(")) open.push(i); else if (isP(st[i], ")")) open.pop(); } - const isQuery = (p: number) => p === -1 || (st[p + 1]?.kind === "word" && QUERY_START.has(st[p + 1]!.upper)); + const duckdb = driver === "duckdb"; + const isQuery = (p: number) => + st[p + 1]?.kind === "word" && (QUERY_START.has(st[p + 1]!.upper) || (duckdb && isW(st[p + 1], "FROM"))); const blocks = [...open.filter(isQuery).reverse(), -1]; + const block = blocks[0]!; + const range = blockRange(st, parens, block, nb); - const ctes = parseCtes(st, parens); + const { ctes, bodyStart } = parseCtes(st, parens, driver); const refs: TableRef[] = []; const refEnds = new Map(); blocks.forEach((g, depth) => { // Within an enclosing block, the "caret" is the paren of the block nested in it. - const [ra, rb] = blockRange(st, parens, g, depth === 0 ? nb : blocks[depth - 1]!); + const [ra, rb] = depth === 0 ? range : blockRange(st, parens, g, blocks[depth - 1]!); for (const r of parseRefs(st, parens, g, ra, rb, ctes, depth, driver)) { refs.push(r.ref); if (depth === 0) refEnds.set(r.end, r.ref); @@ -199,15 +215,21 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe } const p = before[k]; const pi = k; - const block = blocks[0]!; - const clause = clauseAt(st, parens, block, open.length ? open.at(-1)! : -1, nb, driver); + const innermost = open.at(-1) ?? -1; + const clause = clauseAt(st, parens, block, innermost, nb, driver); + const starAt = (i: number) => duckdb && clause === "select" && parens.parent[i] === block && isProjectionStar(st, i); + const projectionStar = starAt(pi); + const excludedStar = isW(p, "EXCLUDE") ? pi - 1 : isW(st[innermost - 1], "EXCLUDE") ? innermost - 2 : -1; // Snowflake `col:path`: the keys of a VARIANT are not in the model. const variantPath = driver === "snowflake" && isP(p, ":") && p!.to === (pi + 1 < before.length ? before[pi + 1]!.from : prefix.from); let context: SqlContext; if (literal) context = { kind: "none" }; - else if (!p) context = qualifier.length ? { kind: "column", clause: "other" } : { kind: "statement" }; + else if (starAt(excludedStar)) { + const owner = st[excludedStar - 2]; + context = { kind: "exclude", owner: isP(st[excludedStar - 1], ".") && owner ? identName(owner) : null }; + } else if (!p) context = qualifier.length ? { kind: "column", clause: "other" } : { kind: "statement" }; else if ( p.kind === "word" && TABLE_INTRO.has(p.upper) && @@ -232,6 +254,11 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe else context = { kind: "column", clause }; } + const queryStart = block === -1 ? Math.max(range[0], bodyStart) : range[0]; + const firstProjectionClause = + duckdb && !isW(st[queryStart], "DELETE", "UPDATE") + ? parens.level(block, queryStart, Math.min(nb, range[1])).find((i) => isW(st[i], "SELECT", "FROM")) + : undefined; return { context, qualifier: qualifier.length ? qualifier : null, @@ -243,9 +270,22 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe fromInsert: fromInsertPos(st, parens, block, pos), lowerKeywords, previous: p ? p.upper : null, + ...(duckdb && { + projectionStar, + fromFirst: firstProjectionClause !== undefined && isW(st[firstProjectionClause], "FROM"), + selectColumns: clause === "qualify" ? outputColumns(st, parens, block, ...range, driver) : undefined, + }), }; } +/** A bare or qualified projection star. A multiplication operator is part of an expression. */ +function isProjectionStar(st: Token[], i: number): boolean { + if (!isP(st[i], "*")) return false; + let prev = i - 1; + while (isP(st[prev], ".") && isIdent(st[prev - 1])) prev -= 2; + return isW(st[prev], "SELECT", "DISTINCT", "ALL") || isP(st[prev], ","); +} + /** Token range of block `g`, cut to the UNION / INTERSECT / EXCEPT branch containing `caret` (a token index). */ function blockRange(st: Token[], parens: Parens, g: number, caret: number): [number, number] { let a = g + 1; @@ -268,7 +308,7 @@ function clauseAt( block: number, innermost: number, caret: number, - driver: DbDriver, + driver: SqlDriver, ): Clause { // Inside a non-query paren (function call, IN list), the clause is the one around that paren. const limit = innermost > block ? innermost : caret; @@ -283,9 +323,10 @@ function clauseAt( return clause; } -function parseCtes(st: Token[], parens: Parens): TableRef[] { - const out: TableRef[] = []; - if (!isW(st[0], "WITH")) return out; +function parseCtes(st: Token[], parens: Parens, driver: SqlDriver): { ctes: TableRef[]; bodyStart: number } { + const ctes: TableRef[] = []; + let bodyStart = 0; + if (!isW(st[0], "WITH")) return { ctes, bodyStart }; let i = 1; if (isW(st[i], "RECURSIVE")) i++; while (i < st.length && isIdent(st[i])) { @@ -305,8 +346,8 @@ function parseCtes(st: Token[], parens: Parens): TableRef[] { while (isW(st[i], "NOT", "MATERIALIZED")) i++; if (!isP(st[i], "(")) break; const c = parens.close.get(i)!; - columns ??= outputColumns(st, parens, i, i + 1, c); - out.push({ + columns ??= outputColumns(st, parens, i, i + 1, c, driver); + ctes.push({ schema: null, name: identName(nameTok), alias: null, @@ -318,15 +359,22 @@ function parseCtes(st: Token[], parens: Parens): TableRef[] { depth: 0, viaJoin: false, }); - i = c + 1; + i = bodyStart = c + 1; if (!isP(st[i], ",")) break; i++; } - return out; + return { ctes, bodyStart }; } /** Output column names of the query in group `g` (`a..b`): aliases and plain column references. */ -export function outputColumns(st: Token[], parens: Parens, g: number, a: number, b: number): string[] { +export function outputColumns( + st: Token[], + parens: Parens, + g: number, + a: number, + b: number, + driver: SqlDriver, +): string[] { const level = parens.level(g, a, b); const sel = level.find((i) => isW(st[i], "SELECT")); if (sel === undefined) return []; @@ -358,6 +406,7 @@ export function outputColumns(st: Token[], parens: Parens, g: number, a: number, t.upper === "GROUP" || t.upper === "ORDER" || t.upper === "LIMIT" || + (driver === "duckdb" && isW(t, "HAVING", "WINDOW", "QUALIFY", "OFFSET")) || SET_OPS.has(t.upper)) ) break; @@ -378,10 +427,11 @@ function parseRefs( b: number, ctes: TableRef[], depth: number, - driver: DbDriver, + driver: SqlDriver, ): Array<{ ref: TableRef; end: number }> { const out: Array<{ ref: TableRef; end: number }> = []; const level = parens.level(g, a, b); + const eq = nameMatcher(driver); let clause: Clause = "other"; const item = (j: number, viaJoin = false, into = false) => { while (isW(st[j], "LATERAL", "ONLY")) j++; @@ -389,7 +439,7 @@ function parseRefs( if (!t || j >= b) return; if (isP(t, "(")) { const c = parens.close.get(j)!; - const columns = outputColumns(st, parens, j, j + 1, c); + const columns = outputColumns(st, parens, j, j + 1, c, driver); const al = alias(st, c + 1, b, driver); if (al) out.push({ @@ -426,10 +476,7 @@ function parseRefs( const name = identName(last); const schema = parts.length > 1 ? identName(parts.at(-2)!) : null; const al = alias(st, k, b, driver); - const cte = - schema === null - ? ctes.find((c) => (driver === "clickhouse" ? c.name === name : c.name.toLowerCase() === name.toLowerCase())) - : undefined; + const cte = schema === null ? ctes.find((c) => eq(c.name, name)) : undefined; out.push({ ref: { ...(parts.length > 2 ? { database: identName(parts.at(-3)!) } : {}), @@ -464,13 +511,16 @@ function parseRefs( } /** An alias at `k` (`AS x`, or a bare non-keyword identifier). */ -function alias(st: Token[], k: number, b: number, driver: DbDriver): { name: string; tok: Token; end: number } | null { +function alias(st: Token[], k: number, b: number, driver: SqlDriver): { name: string; tok: Token; end: number } | null { let j = k; const as = isW(st[j], "AS"); if (as) j++; const t = st[j]; if (j >= b || !t) return null; - if (t.kind === "quoted" || (t.kind === "word" && !CLAUSE_WORDS.has(t.upper) && (as || !isReserved(t.text, driver)))) { + if ( + t.kind === "quoted" || + (t.kind === "word" && !CLAUSE_WORDS.has(t.upper) && ((as && driver !== "duckdb") || !isReserved(t.text, driver))) + ) { return { name: identName(t), tok: t, end: j }; } return null; @@ -529,7 +579,7 @@ export interface ValuesSlot { index: number; } -export function valuesSlot(text: string, pos: number, driver: DbDriver): ValuesSlot | null { +export function valuesSlot(text: string, pos: number, driver: SqlDriver): ValuesSlot | null { const a = analyze(text, pos, driver); if (a.verb !== "INSERT" && a.verb !== "REPLACE") return null; const target = a.refs.find((r) => r.depth === 0 && r.kind === "table"); diff --git a/src/features/database/sql/complete.ts b/src/features/database/sql/complete.ts index d1ac22519..8d2bab920 100644 --- a/src/features/database/sql/complete.ts +++ b/src/features/database/sql/complete.ts @@ -5,16 +5,19 @@ * of the tables in scope with their owner and type, join conditions after ON, * dialect functions and the keywords that may follow. */ -import type { DbCompletion, DbCompletionColumn, DbCompletionTable, DbDriver } from "@/platform/ipc"; +import type { DbCompletion, DbCompletionColumn, DbCompletionTable } from "@/platform/ipc"; import type { Analysis, Clause, TableRef } from "./analyze"; import { DATA_TYPES, functions, + identifierKey, isReserved, joinKeywords, nameMatcher, predicateKeywords, statementStarters, + type SqlDriver, + type SqlFunction, } from "./dialect"; export type CandidateKind = @@ -69,7 +72,7 @@ const MAX_ALL_COLUMNS = 3000; * what is not a plain word is quoted, which is right for the dialects that fold case * neither way. */ -export function quoteIdent(name: string, driver: DbDriver, dialect?: DbDriver | null): string { +export function quoteIdent(name: string, driver: SqlDriver, dialect?: SqlDriver | null): string { const d = driver === "jdbc" && dialect ? dialect : driver; const plain = d === "postgres" @@ -106,7 +109,7 @@ export function aliasFor(table: string, taken: ReadonlySet): string { } /** - * What lies outside the schema model, for `database.schema.table` names (Snowflake): the data + * What lies outside the schema model, for `database.schema.table` names: the data * source's databases, and the schemas and tables of one, as far as they are loaded. Names are * matched the way the dialect matches them. */ @@ -126,9 +129,9 @@ export interface CompletionInput { catalog?: SqlCatalog; model: DbCompletion | null; analysis: Analysis; - driver: DbDriver; + driver: SqlDriver; /** The dialect a `jdbc` source speaks, from its URL (`jdbcDialect`); quoting follows it. */ - dialect?: DbDriver | null; + dialect?: SqlDriver | null; /** Data source name, shown next to tables like IDEA does. */ sourceName?: string; } @@ -142,6 +145,7 @@ export function sqlCandidates({ catalog, }: CompletionInput): SqlCandidate[] { const eq = nameMatcher(driver); + const columnKey = (name: string) => (driver === "duckdb" ? identifierKey(name, driver) : name.toLowerCase()); const ctx = a.context; if (ctx.kind === "none") return []; const typedLower = /[a-z]/.test(a.prefix.text) && !/[A-Z]/.test(a.prefix.text); @@ -182,13 +186,15 @@ export function sqlCandidates({ schema ? tables.find((t) => eq(t.schema, schema) && eq(t.name, name)) : (tables.find((t) => eq(t.schema, defaultSchema) && eq(t.name, name)) ?? tables.find((t) => eq(t.name, name))); + const refTable = (r: TableRef): DbCompletionTable | undefined => + r.kind === "table" && !(driver === "duckdb" && r.database !== undefined) ? findTable(r.schema, r.name) : undefined; const columnsOf = (r: TableRef): Array & Partial> => - r.columns ? r.columns.map((name) => ({ name })) : (findTable(r.schema, r.name)?.columns ?? []); + r.columns ? r.columns.map((name) => ({ name })) : (refTable(r)?.columns ?? []); const refName = (r: TableRef) => r.alias ?? r.name; /** Owner shown after a column: the alias, else the table qualified by its schema (IDEA's `(main.users)`). */ const ownerOf = (r: TableRef) => { if (r.alias || r.kind !== "table") return refName(r); - const t = findTable(r.schema, r.name); + const t = refTable(r); return t?.schema ? `${t.schema}.${t.name}` : r.name; }; /** One candidate inserting several columns: `id, email, name`. */ @@ -236,30 +242,47 @@ export function sqlCandidates({ : undefined, }); + if (ctx.kind === "exclude") { + const seen = new Set(); + const qualifier = a.qualifier?.at(-1); + for (const r of a.refs) { + if (r.depth !== 0 || (ctx.owner && !eq(refName(r), ctx.owner)) || (qualifier && !eq(refName(r), qualifier))) + continue; + const t = refTable(r); + for (const c of columnsOf(r)) { + const key = columnKey(c.name); + if (seen.has(key)) continue; + seen.add(key); + out.push(columnCandidate(c, ownerOf(r), t, 40)); + } + } + return out; + } + // ---- `qualifier.` ---------------------------------------------------------- if (a.qualifier) { const [first, second] = a.qualifier; if (a.qualifier.length === 1 && ctx.kind !== "table") { const ref = a.refs.find((r) => eq(r.alias, first) || (!r.alias && eq(r.name, first))); if (ref) { - const t = ref.kind === "table" ? findTable(ref.schema, ref.name) : undefined; + const t = refTable(ref); return columnsOf(ref).map((c) => columnCandidate(c, refName(ref), t, 50)); } } if (a.qualifier.length === 1) { - const inSchema: SqlCandidate[] = tables - .filter((t) => eq(t.schema, first)) - .map((t) => ({ ...tableCandidate(t, 30), insert: qn(t.name) })); - // `database.`: its schemas (a name can be a schema here and a database too). + // DuckDB rejects two-part names when a catalog and a schema share the qualifier. const db = database(first!); + const inSchema: SqlCandidate[] = + driver === "duckdb" && db + ? [] + : tables.filter((t) => eq(t.schema, first)).map((t) => ({ ...tableCandidate(t, 30), insert: qn(t.name) })); if (db) inSchema.push(...(catalog?.schemas(db) ?? []).map((s) => schemaCandidate(s, 20, `(${db})`))); if (inSchema.length) return inSchema; const t = findTable(null, first!); if (t && ctx.kind !== "table") return t.columns.map((c) => columnCandidate(c, t.name, t, 50)); return []; } - // Snowflake `database.schema.table`: the model holds the session's database only, keyed by the last two parts. - if (driver === "snowflake" && ctx.kind === "table") { + if ((driver === "snowflake" || driver === "duckdb") && ctx.kind === "table") { // `database.schema.`: the tables of that schema, wherever the database is. const db = a.qualifier.length === 2 ? database(first!) : undefined; if (!db) return []; @@ -273,6 +296,12 @@ export function sqlCandidates({ })); } const [schema, name] = driver === "snowflake" ? a.qualifier.slice(-2) : [first, second]; + if ( + driver === "duckdb" && + (a.qualifier.length > 2 || + a.refs.some((r) => r.database !== undefined && eq(r.schema, schema) && eq(r.name, name))) + ) + return []; const t = findTable(schema!, name!); return t ? t.columns.map((c) => columnCandidate(c, t.name, t, 50)) : []; } @@ -307,6 +336,7 @@ export function sqlCandidates({ boost: -5, }); if (ctx.join) keywords(["LATERAL"], -10); + if (driver === "duckdb") for (const f of functions(driver)) if (f.table) addFunction(f, 10); return out; } @@ -334,6 +364,10 @@ export function sqlCandidates({ } keywords(["AS", "WHERE", ...joinKeywords(driver), "GROUP BY", "ORDER BY", "LIMIT", "UNION", "UNION ALL"], 10); if (driver === "snowflake") keywords(["QUALIFY", "SAMPLE", "PIVOT", "UNPIVOT", "MATCH_RECOGNIZE"], 10); + if (driver === "duckdb") { + keywords(["QUALIFY", "GROUP BY ALL", "ORDER BY ALL"], 10); + if (a.fromFirst) keywords(["SELECT"], 15); + } } return out; } @@ -344,7 +378,7 @@ export function sqlCandidates({ return out; case "insertColumns": { - const t = ctx.target.kind === "table" ? findTable(ctx.target.schema, ctx.target.name) : undefined; + const t = refTable(ctx.target); const all = columnsOf(ctx.target); // The columns an INSERT needs (no default), then all of them. const required = all.filter((c) => !c.hasDefault).map((c) => c.name); @@ -380,16 +414,16 @@ export function sqlCandidates({ // Column names in several tables of the block are inserted qualified. const count = new Map(); for (const r of inner) - for (const c of columnsOf(r)) count.set(c.name.toLowerCase(), (count.get(c.name.toLowerCase()) ?? 0) + 1); + for (const c of columnsOf(r)) count.set(columnKey(c.name), (count.get(columnKey(c.name)) ?? 0) + 1); const seen = new Set(); for (const r of visible) { - const t = r.kind === "table" ? findTable(r.schema, r.name) : undefined; + const t = refTable(r); const owner = ownerOf(r); for (const c of columnsOf(r)) { const key = `${owner}\u0000${c.name}`; if (seen.has(key)) continue; seen.add(key); - const ambiguous = r.depth > 0 || (count.get(c.name.toLowerCase()) ?? 0) > 1; + const ambiguous = r.depth > 0 || (count.get(columnKey(c.name)) ?? 0) > 1; out.push( columnCandidate( c, @@ -421,28 +455,38 @@ export function sqlCandidates({ } for (const c of a.ctes) if (!visible.some((r) => eq(r.name, c.name))) out.push({ label: c.name, kind: "table", tail: "(CTE)", boost: 0 }); - const fnBoost = clause === "select" || clause === "having" ? 15 : 8; + for (const name of a.selectColumns ?? []) { + if (!out.some((c) => c.kind === "column" && eq(c.label, name))) + out.push({ label: name, kind: "column", insert: qn(name), boost: 45 }); + } + const selectLike = clause === "select" || clause === "having" || clause === "qualify"; for (const f of functions(driver)) { - const name = lower || driver === "clickhouse" ? f.name : f.name.toUpperCase(); - out.push({ - label: name, - kind: "function", - tail: `(${f.params})`, - type: f.returns?.toUpperCase(), - snippet: f.params ? `${name}(\${})` : `${name}()\${0}`, - boost: f.aggregate && clause !== "select" && clause !== "having" ? fnBoost - 4 : fnBoost, - }); + if (f.table && f.name !== "range" && f.name !== "generate_series") continue; + addFunction(f, selectLike ? 15 : f.aggregate ? 4 : 8); } keywords(clauseKeywords(clause, driver, a), 5); } + + function addFunction(f: SqlFunction, boost: number) { + const name = lower || driver === "clickhouse" ? f.name : f.name.toUpperCase(); + out.push({ + label: name, + kind: "function", + tail: `(${f.params})`, + type: f.returns?.toUpperCase(), + snippet: f.params ? `${name}(\${})` : `${name}()\${0}`, + boost, + }); + } } -function clauseKeywords(clause: Clause, driver: DbDriver, a: Analysis): string[] { +function clauseKeywords(clause: Clause, driver: SqlDriver, a: Analysis): string[] { const pred = predicateKeywords(driver); switch (clause) { case "select": return [ - "FROM", + ...(a.fromFirst ? [] : ["FROM"]), + ...(a.projectionStar ? ["EXCLUDE", "REPLACE", "RENAME"] : []), "DISTINCT", "AS", "CASE", @@ -459,9 +503,17 @@ function clauseKeywords(clause: Clause, driver: DbDriver, a: Analysis): string[] case "where": case "on": case "having": - return [...pred, "GROUP BY", "ORDER BY", "LIMIT", ...(driver === "snowflake" ? ["QUALIFY"] : [])]; + return [ + ...pred, + "GROUP BY", + "ORDER BY", + "LIMIT", + ...(driver === "snowflake" || driver === "duckdb" ? ["QUALIFY"] : []), + ]; + case "qualify": + return [...pred, "ORDER BY", "LIMIT"]; case "group": - return ["HAVING", "ORDER BY", "LIMIT", ...(driver === "snowflake" ? ["QUALIFY"] : [])]; + return ["HAVING", "ORDER BY", "LIMIT", ...(driver === "snowflake" || driver === "duckdb" ? ["QUALIFY"] : [])]; case "order": return ["ASC", "DESC", "LIMIT", "OFFSET", ...(driver === "mysql" ? [] : ["NULLS FIRST", "NULLS LAST"])]; case "set": @@ -486,8 +538,8 @@ type Kw = (k: string) => string; function joinCandidates( a: Analysis, model: DbCompletion | null, - driver: DbDriver, - dialect: DbDriver | null | undefined, + driver: SqlDriver, + dialect: SqlDriver | null | undefined, taken: Set, kw: Kw, ): SqlCandidate[] { @@ -499,6 +551,7 @@ function joinCandidates( const local = (s: string) => eq(s, model.defaultSchema) || driver === "sqlite"; const tableText = (schema: string, name: string) => (local(schema) ? q(name) : `${q(schema)}.${q(name)}`); for (const r of a.refs.filter((x) => x.depth === 0 && x.kind === "table")) { + if (driver === "duckdb" && r.database !== undefined) continue; const rt = model.tables.find((t) => eq(t.name, r.name) && (r.schema ? eq(t.schema, r.schema) : true)); if (!rt) continue; const ra = r.alias ?? r.name; @@ -554,13 +607,15 @@ function conditionCandidates( model: DbCompletion | null, ref: TableRef, kw: Kw, - driver: DbDriver, + driver: SqlDriver, ): SqlCandidate[] { if (!model || ref.kind !== "table") return []; const eq = nameMatcher(driver); const out: SqlCandidate[] = []; const find = (r: TableRef) => - model.tables.find((t) => eq(t.name, r.name) && (r.schema ? eq(t.schema, r.schema) : true)); + driver === "duckdb" && r.database !== undefined + ? undefined + : model.tables.find((t) => eq(t.name, r.name) && (r.schema ? eq(t.schema, r.schema) : true)); const mine = find(ref); if (!mine) return out; const ma = ref.alias ?? ref.name; diff --git a/src/features/database/sql/dialect.ts b/src/features/database/sql/dialect.ts index d5a6a3831..7dd5766b1 100644 --- a/src/features/database/sql/dialect.ts +++ b/src/features/database/sql/dialect.ts @@ -1,5 +1,14 @@ /** Per-dialect SQL vocabulary: reserved words, statement starters and built-in functions. */ -import type { DbDriver } from "@/platform/ipc"; +import type { DataSource, DbDriver } from "@/platform/ipc"; + +/** DuckDB speaks its own SQL over the generic JDBC transport. */ +export type SqlDriver = DbDriver | "duckdb"; + +export function sqlDriverOf(source: Pick | null | undefined): SqlDriver { + if (source?.driver === "jdbc" && (source.vendor === "duckdb" || /^jdbc:duckdb:/i.test(source.url?.trim() ?? ""))) + return "duckdb"; + return source?.driver ?? "sqlite"; +} export interface SqlFunction { name: string; @@ -7,6 +16,7 @@ export interface SqlFunction { params: string; returns?: string; aggregate?: boolean; + table?: boolean; } /** Words that must be quoted when used as identifiers (the common core of the three dialects). */ @@ -29,13 +39,35 @@ const SNOWFLAKE_RESERVED = new Set( ).split(" "), ); -export function isReserved(word: string, driver?: DbDriver): boolean { - const upper = word.toUpperCase(); - return RESERVED.has(upper) || (driver === "snowflake" && SNOWFLAKE_RESERVED.has(upper)); +// Public keyword categories from DuckDB 1.5's duckdb_keywords(). +const DUCKDB_RESERVED = new Set( + ( + "ANALYSE ANALYZE ARRAY ASYMMETRIC BOTH DEFERRABLE DESCRIBE DO INITIALLY LAMBDA LATERAL LEADING ONLY " + + "PIVOT PIVOT_LONGER PIVOT_WIDER PLACING QUALIFY RETURNING SHOW SOME SUMMARIZE SYMMETRIC TRAILING UNPIVOT VARIADIC" + ).split(" "), +); + +export function isReserved(word: string, driver?: SqlDriver): boolean { + const upper = sqlWordUpper(word, driver); + return ( + RESERVED.has(upper) || + (driver === "snowflake" && SNOWFLAKE_RESERVED.has(upper)) || + (driver === "duckdb" && DUCKDB_RESERVED.has(upper)) + ); } -export const nameMatcher = (driver: DbDriver) => (a: string | null | undefined, b: string | null | undefined) => - !!a && !!b && (driver === "clickhouse" ? a === b : a.toLowerCase() === b.toLowerCase()); +export function sqlWordUpper(word: string, driver?: SqlDriver): string { + return driver === "duckdb" ? word.replace(/[a-z]/g, (letter) => letter.toUpperCase()) : word.toUpperCase(); +} + +export function identifierKey(name: string, driver: SqlDriver): string { + if (driver === "clickhouse") return name; + // DuckDB folds ASCII letters in quoted and unquoted names. + return driver === "duckdb" ? name.replace(/[A-Z]/g, (letter) => letter.toLowerCase()) : name.toLowerCase(); +} + +export const nameMatcher = (driver: SqlDriver) => (a: string | null | undefined, b: string | null | undefined) => + !!a && !!b && identifierKey(a, driver) === identifierKey(b, driver); /** Clause keywords: a word in this set ends a table alias or expression. */ export const CLAUSE_WORDS = new Set( @@ -46,7 +78,7 @@ export const CLAUSE_WORDS = new Set( ).split(" "), ); -export function statementStarters(driver: DbDriver): string[] { +export function statementStarters(driver: SqlDriver): string[] { if (driver === "clickhouse") return [ "SELECT", @@ -143,6 +175,23 @@ export function statementStarters(driver: DbDriver): string[] { "ROLLBACK", ]; if (driver === "jdbc") return common; + if (driver === "duckdb") + return [ + ...common, + "FROM", + "ATTACH", + "DETACH", + "USE", + "COPY", + "CREATE SCHEMA", + "CREATE MACRO", + "DESCRIBE", + "SHOW TABLES", + "SHOW DATABASES", + "SUMMARIZE", + "PIVOT", + "UNPIVOT", + ]; if (driver === "sqlite") return [...common, "PRAGMA", "VACUUM", "ATTACH DATABASE", "REPLACE INTO", "CREATE TRIGGER"]; if (driver === "mysql") return [ @@ -183,7 +232,7 @@ export function statementStarters(driver: DbDriver): string[] { ]; } -export function joinKeywords(driver: DbDriver): string[] { +export function joinKeywords(driver: SqlDriver): string[] { const j = ["JOIN", "LEFT JOIN", "INNER JOIN", "CROSS JOIN", "RIGHT JOIN"]; if (driver !== "mysql") j.push("FULL JOIN"); if (driver === "postgres") j.push("JOIN LATERAL", "LEFT JOIN LATERAL"); @@ -193,7 +242,7 @@ export function joinKeywords(driver: DbDriver): string[] { } /** Comparison / predicate keywords of WHERE, ON and HAVING. */ -export function predicateKeywords(driver: DbDriver): string[] { +export function predicateKeywords(driver: SqlDriver): string[] { const k = [ "AND", "OR", @@ -214,10 +263,40 @@ export function predicateKeywords(driver: DbDriver): string[] { if (driver === "sqlite") k.push("GLOB", "REGEXP"); if (driver === "oracle") k.push("CONNECT BY PRIOR", "START WITH", "NOT IN", "IS NOT NULL"); if (driver === "snowflake") k.push("ILIKE", "RLIKE", "REGEXP", "IS DISTINCT FROM", "ANY"); + if (driver === "duckdb") k.push("ILIKE", "GLOB", "IS DISTINCT FROM", "SIMILAR TO"); return k; } -export const DATA_TYPES: Record = { +export const DATA_TYPES: Record = { + duckdb: [ + "TINYINT", + "SMALLINT", + "INTEGER", + "BIGINT", + "HUGEINT", + "UTINYINT", + "USMALLINT", + "UINTEGER", + "UBIGINT", + "UHUGEINT", + "DECIMAL", + "FLOAT", + "DOUBLE", + "VARCHAR", + "BOOLEAN", + "DATE", + "TIME", + "TIMESTAMP", + "TIMESTAMPTZ", + "INTERVAL", + "BLOB", + "UUID", + "JSON", + "STRUCT", + "MAP", + "UNION", + "ARRAY", + ], jdbc: ["INTEGER", "BIGINT", "DECIMAL", "DOUBLE PRECISION", "VARCHAR", "BOOLEAN", "DATE", "TIME", "TIMESTAMP"], snowflake: [ "NUMBER", @@ -398,8 +477,38 @@ const COMMON: SqlFunction[] = [ f("cast", "expr AS type"), ]; -const FUNCTIONS: Record = { +const FUNCTIONS: Record = { jdbc: COMMON, + duckdb: [ + ...COMMON, + f("count_if", "condition", "bigint", true), + f("string_agg", "expr, delimiter", "varchar", true), + f("list", "expr", undefined, true), + f("arg_max", "arg, value", undefined, true), + f("arg_min", "arg, value", undefined, true), + f("approx_count_distinct", "expr", "bigint", true), + f("quantile_cont", "expr, fraction", undefined, true), + f("regexp_matches", "text, pattern", "boolean"), + f("date_trunc", "part, timestamp"), + f("date_diff", "part, start, end", "bigint"), + f("list_transform", "list, lambda"), + f("list_filter", "list, lambda"), + f("struct_pack", "name := expr, ...", "struct"), + f("json_extract", "json, path", "json"), + f("unnest", "value"), + f("row_number", "", "bigint"), + f("rank", "", "bigint"), + f("dense_rank", "", "bigint"), + f("lag", "expr, offset, default"), + f("lead", "expr, offset, default"), + { ...f("read_csv", "path, options..."), table: true }, + { ...f("read_parquet", "path, options..."), table: true }, + { ...f("read_json", "path, options..."), table: true }, + { ...f("range", "start, stop, step"), table: true }, + { ...f("generate_series", "start, stop, step"), table: true }, + { ...f("duckdb_tables", ""), table: true }, + { ...f("duckdb_columns", ""), table: true }, + ], snowflake: [ ...COMMON, f("listagg", "expr, delimiter", "varchar", true), @@ -654,6 +763,6 @@ const FUNCTIONS: Record = { ], }; -export function functions(driver: DbDriver): SqlFunction[] { +export function functions(driver: SqlDriver): SqlFunction[] { return FUNCTIONS[driver]; } diff --git a/src/features/database/sql/duckdbHighlight.ts b/src/features/database/sql/duckdbHighlight.ts new file mode 100644 index 000000000..1529bda1a --- /dev/null +++ b/src/features/database/sql/duckdbHighlight.ts @@ -0,0 +1,31 @@ +import { SQLDialect } from "@codemirror/lang-sql"; +import type { LRLanguage } from "@codemirror/language"; +import { CLAUSE_WORDS, DATA_TYPES, functions, predicateKeywords, statementStarters } from "./dialect"; + +let language: LRLanguage | undefined; + +/** Token colouring for DuckDB; scope and completion come from the SQL editor. */ +export function duckdbLanguage(): LRLanguage { + return (language ??= SQLDialect.define({ + keywords: [ + ...CLAUSE_WORDS, + ...statementStarters("duckdb"), + ...predicateKeywords("duckdb"), + "ASOF ANTI SEMI EXCLUDE REPLACE RENAME COLUMNS QUALIFY OVER PARTITION FILTER NULLS FIRST LAST", + "IF RECURSIVE DESCRIBE SUMMARIZE COMMENT INSTALL LOAD EXPORT IMPORT PRAGMA RESET VACUUM", + "SAMPLE REPEATABLE PERCENT ROWS MATERIALIZED TEMPORARY LAMBDA TRY_CAST AT TIME ZONE", + ] + .join(" ") + .toLowerCase(), + types: DATA_TYPES.duckdb + .filter((type) => type !== "UNION") + .join(" ") + .toLowerCase(), + builtin: functions("duckdb") + .map((f) => f.name) + .join(" "), + caseInsensitiveIdentifiers: true, + doubleDollarQuotedStrings: true, + specialVar: "?$", + }).language); +} diff --git a/src/features/database/sql/format.test.ts b/src/features/database/sql/format.test.ts index 68e4fa0ca..16218c4fa 100644 --- a/src/features/database/sql/format.test.ts +++ b/src/features/database/sql/format.test.ts @@ -71,6 +71,15 @@ describe("formatSql", () => { expect(edits).toEqual([{ from: sql.lastIndexOf("select"), to: sql.length, insert: "select 1;" }]); }); + it("keeps DuckDB integer division, escaped strings and non-ASCII identifier letters", () => { + expect( + formatted(String.raw`from sales select Äscii // 2, E'it\'s ok' qualify row_number() over ()=1;`, "duckdb", { + keywords: "upper", + identifiers: "lower", + }), + ).toBe("FROM sales\nSELECT Äscii // 2,\n E'it\\'s ok'\nQUALIFY row_number() OVER() = 1;"); + }); + it("keeps Snowflake dollar strings, comments, casts, variant paths and stages", () => { const sf = (sql: string) => formatted(sql, "snowflake"); expect(sf("select src:customer.name::string,src['k'].v[0] from t where x=$$ a b $$ // why\n;")).toBe( diff --git a/src/features/database/sql/format.ts b/src/features/database/sql/format.ts index a994a4ef0..36fcd99c8 100644 --- a/src/features/database/sql/format.ts +++ b/src/features/database/sql/format.ts @@ -7,9 +7,15 @@ * take the case of Code Style › SQL › Case; each statement is replaced on its * own, so text between statements is left alone. */ -import type { DbDriver } from "@/platform/ipc"; import type { SqlCaseStyle, SqlWordCase } from "@/platform/editorSettings"; -import { CLAUSE_WORDS, isReserved, joinKeywords, predicateKeywords, statementStarters } from "./dialect"; +import { + CLAUSE_WORDS, + isReserved, + joinKeywords, + predicateKeywords, + statementStarters, + type SqlDriver, +} from "./dialect"; import { lex, type Token } from "./lexer"; export interface SqlEdit { @@ -29,7 +35,7 @@ interface Item { /** Edits formatting every statement (or those overlapping `range`). */ export function formatSql( text: string, - driver: DbDriver, + driver: SqlDriver, range: { from: number; to: number } | null = null, wordCase: SqlCaseStyle = KEEP_CASE, ): SqlEdit[] { @@ -122,10 +128,10 @@ const MORE_KEYWORDS = "IF IGNORE INDEX KEY LIMIT MERGE NOTHING NULLS OFFSET OVER PARTITION RECURSIVE RENAME REPLACE RESTRICT " + "RETURNING ROLLBACK SCHEMA TEMPORARY TRUNCATE VIEW"; -const keywordSets = new Map>(); +const keywordSets = new Map>(); /** The words Reformat Code treats as keywords for `driver`. */ -function keywordsOf(driver: DbDriver): Set { +function keywordsOf(driver: SqlDriver): Set { let set = keywordSets.get(driver); if (!set) { const phrases = [...statementStarters(driver), ...joinKeywords(driver), ...predicateKeywords(driver)]; @@ -148,17 +154,19 @@ function applyCase(text: string, wordCase: SqlWordCase): string { * the keyword case, any other unquoted name the identifier case — except on ClickHouse, whose names * are case-sensitive, and for bind parameters (`:name`, `@name`) and Snowflake paths (`col:Key`). */ -function casedWord(it: Item, prev: Item | null, next: Item | undefined, driver: DbDriver, wordCase: SqlCaseStyle) { +function casedWord(it: Item, prev: Item | null, next: Item | undefined, driver: SqlDriver, wordCase: SqlCaseStyle) { if (it.kind !== "word" || (wordCase.keywords === "keep" && wordCase.identifiers === "keep")) return it.text; if (isP(prev, ":") || isP(prev, "@") || isP(prev, "$")) return it.text; const qualified = isP(prev, ".") || isP(next, ".") || isP(prev, "::"); const keyword = !qualified && (isReserved(it.text, driver) || keywordsOf(driver).has(it.upper)); if (keyword) return applyCase(it.text, wordCase.keywords); if (!/^[\p{L}_][\p{L}\p{N}_$]*$/u.test(it.text)) return it.text; - return driver === "clickhouse" ? it.text : applyCase(it.text, wordCase.identifiers); + if (driver === "clickhouse") return it.text; + if (driver === "duckdb") return it.text.replace(/[A-Za-z]+/g, (part) => applyCase(part, wordCase.identifiers)); + return applyCase(it.text, wordCase.identifiers); } -function formatStatement(items: Item[], base: string, driver: DbDriver, wordCase: SqlCaseStyle): string { +function formatStatement(items: Item[], base: string, driver: SqlDriver, wordCase: SqlCaseStyle): string { const lines: string[] = []; let line = ""; const newline = (column: number) => { @@ -170,8 +178,8 @@ function formatStatement(items: Item[], base: string, driver: DbDriver, wordCase const frames: Frame[] = [{ kind: "query", indent: 0, clause: "", count: 0, between: false }]; let prev: Item | null = null; let unary = false; - // Snowflake's QUALIFY is a clause of its own, like HAVING. - const isClause = (word: string) => NEWLINE_CLAUSES.has(word) || (driver === "snowflake" && word === "QUALIFY"); + const isClause = (word: string) => + NEWLINE_CLAUSES.has(word) || ((driver === "snowflake" || driver === "duckdb") && word === "QUALIFY"); items.forEach((it, i) => { const frame = frames.at(-1)!; @@ -232,7 +240,10 @@ function formatStatement(items: Item[], base: string, driver: DbDriver, wordCase line += "("; frames.push({ kind: "create", indent: frame.indent + 4, clause: "", count: 0, between: false }); newline(frame.indent + 4); - } else if (next?.kind === "word" && (next.upper === "SELECT" || next.upper === "WITH")) { + } else if ( + next?.kind === "word" && + (next.upper === "SELECT" || next.upper === "WITH" || (driver === "duckdb" && next.upper === "FROM")) + ) { frames.push({ kind: "query", indent: line.length, clause: "", count: 0, between: false }); } else { frames.push({ kind: "plain", indent: frame.indent, clause: "", count: 0, between: false }); @@ -308,7 +319,7 @@ function isCreateBodyParen(items: Item[], i: number): boolean { } /** `text` with every statement formatted. */ -export function formatted(text: string, driver: DbDriver, wordCase: SqlCaseStyle = KEEP_CASE): string { +export function formatted(text: string, driver: SqlDriver, wordCase: SqlCaseStyle = KEEP_CASE): string { let out = text; for (const e of formatSql(text, driver, null, wordCase).reverse()) out = out.slice(0, e.from) + e.insert + out.slice(e.to); diff --git a/src/features/database/sql/lexer.ts b/src/features/database/sql/lexer.ts index 2c98416d6..0387155ba 100644 --- a/src/features/database/sql/lexer.ts +++ b/src/features/database/sql/lexer.ts @@ -5,7 +5,7 @@ * PostgreSQL dollar quoting, Snowflake `$$` strings / `//` comments / stages / * variant paths). Offsets are UTF-16, like the editor's. */ -import type { DbDriver } from "@/platform/ipc"; +import { sqlWordUpper, type SqlDriver } from "./dialect"; export type TokenKind = "word" | "quoted" | "string" | "number" | "param" | "punct"; @@ -33,10 +33,22 @@ const STAGE_END = /[\s(),;']/; const PATH_OWNER = /[\p{L}\p{N}_$)\]"']/u; const TWO_CHAR = new Set(["::", "<=", ">=", "<>", "!=", "||", "->", "=>", ":="]); -export function lex(text: string, driver: DbDriver = "sqlite"): Lexed { +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; + } + return -1; +} + +export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed { const mysql = driver === "mysql"; const clickhouse = driver === "clickhouse"; const snowflake = driver === "snowflake"; + const duckdb = driver === "duckdb"; const tokens: Token[] = []; const comments: Lexed["comments"] = []; const n = text.length; @@ -48,7 +60,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed { text: t, from, to, - upper: kind === "word" ? t.toUpperCase() : t, + upper: kind === "word" ? sqlWordUpper(t, driver) : t, ...(kind === "quoted" && clickhouse ? { value: t.slice(1, t.endsWith(t[0]!) ? -1 : undefined).replace(/\\([\\'"`])/g, "$1") } : {}), @@ -78,10 +90,14 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed { comments.push({ from: i, to, open: true }); i = to; } else if (c === "/" && next === "*") { - const end = text.indexOf("*/", i + 2); + const end = duckdb ? duckdbBlockCommentEnd(text, i) : text.indexOf("*/", i + 2); const to = end < 0 ? n : end + 2; comments.push({ from: i, to, open: end < 0 }); i = to; + } else if (duckdb && (c === "E" || c === "e") && next === "'") { + const to = quoted(i + 1, "'", true); + push("string", i, to); + i = to; } else if (c === "'") { const to = quoted(i, "'", mysql || clickhouse || snowflake); push("string", i, to); @@ -94,7 +110,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed { const to = quoted(i, "`", clickhouse); push("quoted", i, to); i = to; - } else if (c === "$" && driver === "postgres") { + } else if (c === "$" && (driver === "postgres" || duckdb)) { const m = /^\$([\p{L}_][\p{L}\p{N}_]*)?\$/u.exec(text.slice(i, i + 64)); if (m) { const tag = m[0]; @@ -155,7 +171,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed { i = j; } else { const two = text.slice(i, i + 2); - const len = two === "->" && text[i + 2] === ">" ? 3 : TWO_CHAR.has(two) ? 2 : 1; + const len = two === "->" && text[i + 2] === ">" ? 3 : TWO_CHAR.has(two) || (duckdb && two === "//") ? 2 : 1; push("punct", i, i + len); i += len; } @@ -177,6 +193,7 @@ export function inLiteral(lexed: Lexed, pos: number): "string" | "quoted" | "com function closed(t: Token): boolean { if (t.text.length < 2) return false; const open = t.text[0]!; + if ((open === "E" || open === "e") && t.text[1] === "'") return t.text.length > 2 && t.text.endsWith("'"); if (open === "$") { const tag = /^\$[\p{L}\p{N}_]*\$/u.exec(t.text)?.[0] ?? "$"; return t.text.length >= tag.length * 2 && t.text.endsWith(tag); diff --git a/src/features/database/sql/resolve.ts b/src/features/database/sql/resolve.ts index b4ada6032..a6fee916d 100644 --- a/src/features/database/sql/resolve.ts +++ b/src/features/database/sql/resolve.ts @@ -5,9 +5,9 @@ * as lexical and forgiving as completion; names it cannot judge (unknown * tables' columns, dialect pseudo-columns) are left alone. */ -import type { DbCompletion, DbCompletionColumn, DbCompletionTable, DbDriver } from "@/platform/ipc"; +import type { DbCompletion, DbCompletionColumn, DbCompletionTable } from "@/platform/ipc"; import { analyze, type TableRef } from "./analyze"; -import { CLAUSE_WORDS, DATA_TYPES, functions, isReserved, nameMatcher } from "./dialect"; +import { CLAUSE_WORDS, DATA_TYPES, functions, identifierKey, isReserved, nameMatcher, type SqlDriver } from "./dialect"; import { identName, lex, type Lexed, type Token } from "./lexer"; export type SqlSymbol = @@ -25,6 +25,7 @@ export interface Span { export interface Resolved extends Span { symbol: SqlSymbol | null; + catalogTable?: { catalog: string; schema: string; table: string }; /** Set when the name should resolve but doesn't. */ problem?: string; } @@ -61,7 +62,7 @@ export function findTable( model: DbCompletion | null, schema: string | null, name: string, - driver: DbDriver = "sqlite", + driver: SqlDriver = "sqlite", ): DbCompletionTable | undefined { const eq = nameMatcher(driver); const tables = model?.tables ?? []; @@ -84,7 +85,7 @@ export class SqlResolver { constructor( readonly text: string, - readonly driver: DbDriver, + readonly driver: SqlDriver, readonly model: DbCompletion | null, ) { this.lexed = lex(text, driver); @@ -143,7 +144,7 @@ export class SqlResolver { const name = identName(t); const span = { from: t.from, to: t.to }; const a = analyze(this.text, t.from, this.driver, this.lexedFor(i)); - const checked = CHECKED.has(a.verb); + const checked = CHECKED.has(a.verb) || (this.driver === "duckdb" && a.verb === "FROM"); const loaded = !!this.model?.tables.length; const ctx = a.context; const qualifier = a.qualifier; @@ -157,8 +158,13 @@ export class SqlResolver { if (cte) return { ...span, symbol: { kind: "cte", name: cte.name, def: { from: cte.from, to: cte.to } } }; if (this.model?.tables.some((x) => eq(x.schema, name))) return this.schema(name, span); if (!checked || PSEUDO_TABLES.has(name.toUpperCase()) || ctx.kind === "none") return { ...span, symbol: null }; - // Snowflake `database.schema.table.column`: other databases are not in the model. - if (this.driver === "snowflake" && isP(toks[i + 3], ".") && isP(toks[i + 5], ".") && isName(toks[i + 6])) + // A fully qualified column may live in a catalog the model does not hold. + if ( + (this.driver === "snowflake" || this.driver === "duckdb") && + isP(toks[i + 3], ".") && + isP(toks[i + 5], ".") && + isName(toks[i + 6]) + ) return { ...span, symbol: null }; return { ...span, symbol: null, problem: `Unable to resolve symbol '${name}'` }; } @@ -175,6 +181,11 @@ export class SqlResolver { // Table functions (`generate_series(1, 3)`), `DROP TABLE IF EXISTS`. if (isP(next, "(") && !isIntoTarget(toks, i)) return null; if (t.kind === "word" && (t.upper === "IF" || t.upper === "ONLY" || t.upper === "LATERAL")) return null; + if (this.driver === "duckdb" && qualifier && qualifier.length > 1) { + const catalogTable = + qualifier.length === 2 ? { catalog: qualifier[0]!, schema: qualifier[1]!, table: name } : undefined; + return { ...span, symbol: null, catalogTable }; + } const schema = qualifier?.at(-1) ?? null; const cte = schema ? undefined : a.ctes.find((c) => eq(c.name, name)); if (cte) return { ...span, symbol: { kind: "cte", name: cte.name, def: { from: cte.from, to: cte.to } } }; @@ -198,11 +209,13 @@ export class SqlResolver { case "afterInsertColumns": return null; case "column": + case "exclude": case "joinCondition": break; } if (qualifier) { + if (this.driver === "duckdb" && qualifier.length > 2) return { ...span, symbol: null }; const ref = qualifier.length === 1 ? this.findRef(a.refs, null, qualifier[0]!) @@ -223,6 +236,7 @@ export class SqlResolver { (isReserved(t.text, this.driver) || NOT_COLUMNS.has(t.upper) || this.words.has(t.upper) || + (this.driver === "duckdb" && t.upper === "EXCLUDE" && isP(prev, "*")) || (this.driver === "snowflake" && (SNOWFLAKE_NOT_COLUMNS.has(t.upper) || t.upper.startsWith("METADATA$")))) ) return null; @@ -233,7 +247,9 @@ export class SqlResolver { prev.kind === "number" || prev.kind === "string" || isP(prev, ")") || - (prev.kind === "word" && !CLAUSE_WORDS.has(prev.upper))) + (prev.kind === "word" && + !CLAUSE_WORDS.has(prev.upper) && + !(this.driver === "duckdb" && prev.upper === "QUALIFY"))) ) return null; for (const ref of a.refs) { @@ -251,7 +267,7 @@ export class SqlResolver { clause !== "other" && clause !== "values" && clause !== "limit" && - !this.outputAliases(i).has(this.driver === "clickhouse" ? name : name.toLowerCase()); + !this.outputAliases(i).has(identifierKey(name, this.driver)); return judged ? { ...span, symbol: null, problem: `Unable to resolve column '${name}'` } : { ...span, symbol: null }; @@ -279,8 +295,13 @@ export class SqlResolver { return refs.find((r) => (r.alias ? eq(r.alias, name) : eq(r.name, name) && (!schema || eq(r.schema, schema)))); } + private refTable(ref: TableRef): DbCompletionTable | undefined { + if (ref.kind !== "table" || (this.driver === "duckdb" && ref.database !== undefined)) return undefined; + return findTable(this.model, ref.schema, ref.name, this.driver); + } + private refSymbol(ref: TableRef): SqlSymbol { - const table = ref.kind === "table" ? findTable(this.model, ref.schema, ref.name, this.driver) : undefined; + const table = this.refTable(ref); if (ref.alias && ref.aliasAt) return { kind: "alias", name: ref.alias, def: ref.aliasAt, table }; if (table) return { kind: "table", table }; return { kind: "cte", name: ref.name, def: { from: ref.from, to: ref.to } }; @@ -289,13 +310,13 @@ export class SqlResolver { /** Columns of a FROM item; `null` when unknown (not in the model, `select *` subqueries). */ private columnsOf(ref: TableRef): Array<{ name: string; column?: DbCompletionColumn }> | null { if (ref.columns) return ref.columns.length ? ref.columns.map((name) => ({ name })) : null; - const table = findTable(this.model, ref.schema, ref.name, this.driver); + const table = this.refTable(ref); // A table listed without columns is one whose columns were not read (a large Snowflake database). return table?.columns.length ? table.columns.map((c) => ({ name: c.name, column: c })) : null; } private columnSymbol(ref: TableRef, col: { name: string; column?: DbCompletionColumn }): SqlSymbol { - const table = ref.kind === "table" ? findTable(this.model, ref.schema, ref.name, this.driver) : undefined; + const table = this.refTable(ref); return { kind: "column", name: col.name, column: col.column, table, owner: ref.alias ?? ref.name }; } @@ -313,7 +334,7 @@ export class SqlResolver { prev.kind === "number" || prev.kind === "string" ) - out.add(this.driver === "clickhouse" ? identName(t) : identName(t).toLowerCase()); + out.add(identifierKey(identName(t), this.driver)); } return out; } diff --git a/src/features/database/sql/sql.test.ts b/src/features/database/sql/sql.test.ts index 7a279c639..9d1effd1c 100644 --- a/src/features/database/sql/sql.test.ts +++ b/src/features/database/sql/sql.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from "vitest"; import { EditorState } from "@codemirror/state"; import { snippet } from "@codemirror/autocomplete"; -import type { DbCompletion, DbDriver } from "@/platform/ipc"; +import type { DbCompletion } from "@/platform/ipc"; import { analyze, templateContexts, valuesSlot } from "./analyze"; import { aliasFor, quoteIdent, sqlCandidates, type SqlCandidate } from "./complete"; import { identName, inLiteral, lex } from "./lexer"; -import { DATA_TYPES, statementStarters } from "./dialect"; +import { DATA_TYPES, statementStarters, type SqlDriver } from "./dialect"; import { bindParams, findParams, unbindRange } from "./params"; import { SqlResolver } from "./resolve"; import { jdbcDialect } from "../vendors"; @@ -69,13 +69,13 @@ const model: DbCompletion = { }; /** Analysis at the `|` of `sql`. */ -function at(sql: string, driver: DbDriver = "sqlite") { +function at(sql: string, driver: SqlDriver = "sqlite") { const pos = sql.indexOf("|"); const text = sql.slice(0, pos) + sql.slice(pos + 1); return analyze(text, pos, driver); } -function complete(sql: string, driver: DbDriver = "sqlite", m: DbCompletion = model): SqlCandidate[] { +function complete(sql: string, driver: SqlDriver = "sqlite", m: DbCompletion = model): SqlCandidate[] { return sqlCandidates({ model: m, analysis: at(sql, driver), driver, sourceName: "shop" }).sort( (a, b) => b.boost - a.boost, ); @@ -97,6 +97,118 @@ const sf: DbCompletion = { const labels = (c: SqlCandidate[], kind?: string) => c.filter((x) => !kind || x.kind === kind).map((x) => x.label); +describe("DuckDB SQL", () => { + it("recognizes FROM-first query blocks and keeps their source columns in scope", () => { + expect(statementStarters("duckdb")).toContain("FROM"); + expect(labels(complete("from orders |", "duckdb"), "keyword")).toContain("select"); + expect(labels(complete("from orders select |", "duckdb"), "column")).toContain("total"); + expect(labels(complete("from orders select |", "duckdb"), "keyword")).not.toContain("from"); + const nested = at("select * from (from orders select |) as o", "duckdb"); + expect(nested.refs.find((r) => r.name === "orders")?.depth).toBe(0); + expect(nested.fromInsert).toBeNull(); + }); + + it.each(["delete from orders |", "update orders set total = 1 from users |"])( + "omits a SELECT continuation after %s", + (sql) => { + const withCte = "with source as (select id from users) " + sql; + expect(labels(complete(withCte, "duckdb"), "keyword")).not.toContain("select"); + expect(at(sql, "duckdb").fromFirst).toBe(false); + }, + ); + + it("offers SELECT when a query begins with FROM after a CTE or a set operator", () => { + expect(labels(complete("with source as (select id from users) from source |", "duckdb"), "keyword")).toContain( + "select", + ); + expect(labels(complete("select 1 union all from orders |", "duckdb"), "keyword")).toContain("select"); + expect(at("insert into orders from users |", "duckdb").fromFirst).toBe(true); + }); + + it("recognizes QUALIFY and suggests the window result alias", () => { + const sql = "select row_number() over (order by id) as WinRank from orders qualify |"; + expect(at(sql, "duckdb").context).toEqual({ kind: "column", clause: "qualify" }); + expect(at(sql, "duckdb").refs[0]?.alias).toBeNull(); + expect(labels(complete(sql, "duckdb"))).toContain("WinRank"); + expect(labels(complete(sql, "duckdb"), "keyword")).not.toContain("qualify"); + expect(new SqlResolver(sql.replace("|", "winrank = 1"), "duckdb", model).problems()).toEqual([]); + }); + + it("completes EXCLUDE after a projection star and its list from catalog columns", () => { + expect(labels(complete("select * excl| from orders", "duckdb"), "keyword")).toContain("exclude"); + expect(labels(complete("select id * ex| from orders", "duckdb"), "keyword")).not.toContain("exclude"); + const candidates = complete("select o.* exclude (|) from orders o join users u on o.user_id = u.id", "duckdb"); + expect(labels(candidates)).toContain("total"); + expect(labels(candidates)).not.toContain("email"); + expect(candidates.every((c) => c.kind === "column")).toBe(true); + expect(labels(complete("select * excl| from orders", "jdbc"), "keyword")).not.toContain("exclude"); + }); + + it("completes table functions and preserves spelling of identifiers using DuckDB quoting", () => { + expect(labels(complete("from read_par|", "duckdb"), "function")).toContain("read_parquet"); + expect(quoteIdent("MixedCase", "duckdb")).toBe("MixedCase"); + expect(quoteIdent("qualify", "duckdb")).toBe('"qualify"'); + expect(quoteIdent("exclude", "duckdb")).toBe("exclude"); + expect(quoteIdent('a"b', "duckdb")).toBe('"a""b"'); + const sql = 'from orders as "ÄÖrder" select "ÄörDER".|'; + expect(labels(complete(sql, "duckdb"), "column")).toEqual([]); + expect(labels(complete(sql.replace("ÄörDER", "ÄÖrDER"), "duckdb"), "column")).toContain("total"); + }); + + it("inserts three-part DuckDB paths and keeps columns from same-named local tables out of them", () => { + const database = "Archive.db:1"; + const schema = "Mixed.Schema"; + const catalog = { + databases: [database, "memory"], + schemas: (name: string) => (name === database ? [schema, "main"] : null), + tables: (name: string, namespace: string) => + name === database && namespace.toLowerCase() === schema.toLowerCase() + ? [{ name: 'Remote "view"', view: true }] + : null, + }; + const local = { + ...model, + tables: [...model.tables, { ...model.tables[0]!, schema: database, name: "local_table" }], + }; + const run = (sql: string) => + sqlCandidates({ model: local, analysis: at(sql, "duckdb"), driver: "duckdb", catalog }); + expect(run("from Arch|")).toContainEqual( + expect.objectContaining({ label: database, insert: '"Archive.db:1".', retrigger: true }), + ); + expect(run('from "ARCHIVE.db:1".|')).toEqual([ + expect.objectContaining({ label: schema, insert: '"Mixed.Schema".', retrigger: true }), + expect.objectContaining({ label: "main", insert: "main." }), + ]); + expect(run('from "archive.db:1"."mixed.schema".|')).toEqual([ + expect.objectContaining({ kind: "view", insert: '"Remote ""view"""' }), + ]); + expect(run('from "archive.db:1".missing.|')).toEqual([]); + expect(run("from main.|").map((c) => c.label)).toContain("orders"); + + const remote = '"Archive.db:1".main.orders'; + for (const select of ["select |", "select o.|", "select main.orders.|", 'select "Archive.db:1".main.orders.|']) { + expect(labels(run(select + " from " + remote + " o"), "column")).toEqual([]); + } + expect(labels(run("select o.| from main.orders o"), "column")).toContain("total"); + const sql = "select o.total from " + remote + " o"; + const resolver = new SqlResolver(sql, "duckdb", model); + expect(resolver.resolveAt(sql.indexOf(".orders") + 2)?.catalogTable).toEqual({ + catalog: database, + schema: "main", + table: "orders", + }); + expect(resolver.problems()).toEqual([]); + expect(resolver.resolveAt(sql.indexOf("total"))?.symbol).toBeNull(); + expect(resolver.resolveAt(sql.indexOf("orders"))?.symbol).toBeNull(); + }); + + it("keeps nested comments and dollar-quoted SQL out of caret analysis", () => { + expect(at("select /* outer /* nested */ here| */ 1", "duckdb").context.kind).toBe("none"); + expect(at("select $body$ from not_a_table; here| $body$", "duckdb").context.kind).toBe("none"); + expect(at("select 5 // 2, | from orders", "duckdb").refs[0]?.name).toBe("orders"); + }); +}); + describe("lexer", () => { it("reads ClickHouse backticks and escaped quotes without exposing literal parameters", () => { const sql = String.raw`select "a\\b\"c", ` + "`my column`" + String.raw`, 'it\'s ?; text', ?`; diff --git a/src/features/database/sqlSupport.ts b/src/features/database/sqlSupport.ts index 38a6b0fcb..3bd70c24b 100644 --- a/src/features/database/sqlSupport.ts +++ b/src/features/database/sqlSupport.ts @@ -17,25 +17,26 @@ import { } from "@/editor/api"; import { setFileDiagnostics } from "@/editor/lsp/diagnostics"; import { showHint } from "@/editor/lsp/hint"; -import type { DbCompletion, DbCompletionTable, DbDriver } from "@/platform/ipc"; +import type { DbCompletion, DbCompletionTable } from "@/platform/ipc"; +import { sqlDriverOf, type SqlDriver } from "./sql/dialect"; import { formatSql } from "./sql/format"; import { editorPrefs, sqlCaseStyle } from "@/platform/editorSettings"; import { SqlResolver, type SqlSymbol } from "./sql/resolve"; import { useProject } from "@/platform/project"; -import { consoleSchema, consoleSource, revealInTree, sourceById, useDatabase } from "./store"; +import { consoleSchema, consoleSource, duckdbCatalogTree, revealInTree, sourceById, useDatabase } from "./store"; /** Producer id of the console's diagnostics (Problems view, hover). */ const INSPECTIONS = "sql-inspections"; const INSPECT_DELAY = 400; -function sourceOf(path: string): { id: string | null; driver: DbDriver; model: DbCompletion | null } { +function sourceOf(path: string): { id: string | null; driver: SqlDriver; model: DbCompletion | null } { const id = consoleSource(path); const model = id ? (useDatabase.getState().completion[id] ?? null) : null; // Unqualified names resolve in the console's active schema (IDEA's schema dropdown). const schema = consoleSchema(path); return { id, - driver: sourceById(id)?.driver ?? "sqlite", + driver: sqlDriverOf(sourceById(id)), model: model && schema ? { ...model, defaultSchema: schema } : model, }; } @@ -113,9 +114,14 @@ function definition(path: string, sql: SqlText): ContributedDefinition { if (sql.at && !sql.at(view.state, pos)) return false; const r = resolver(path, view.state, sql).resolveAt(pos); const sym = r?.symbol; + const id = consoleSource(path); + if (r?.catalogTable && id && duckdbCatalogTree(sourceById(id))) { + const { catalog, schema, table } = r.catalogTable; + void revealInTree(id, schema, table, undefined, undefined, catalog); + return true; + } // Outside SQL names, other providers (the XML language server) may know the place. if (!sym && sql.at) return false; - const id = consoleSource(path); const reveal = (t: DbCompletionTable, column?: string) => { if (id) void revealInTree(id, t.schema, t.name, t.kind, column); }; diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 9eeadaacb..b60ded8e2 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -50,6 +50,8 @@ import { colorVar, connectRemedy, databaseKey, + schemaNodeKey, + treeIdentifier, effectiveSsh, idleTargets, newSourceId, @@ -64,9 +66,12 @@ import { TABLE_KIND, type TableRef } from "./tableInput"; import type { DiagramData } from "./erDiagram"; import type { ExportData, ExportFormat } from "./export"; import type { DbObjectRef } from "./objects"; +import type { SqlCatalog } from "./sql/complete"; +import { nameMatcher, sqlDriverOf } from "./sql/dialect"; import { formatted } from "./sql/format"; -import { unsafeStatement, type UnsafeStatement } from "./sql/unsafe"; +import { lex } from "./sql/lexer"; import { bindParams, findParams, unbindRange } from "./sql/params"; +import { unsafeStatement, type UnsafeStatement } from "./sql/unsafe"; import { isReadOnlyQuery } from "./sql/readOnly"; import { pageFetch } from "./resultView"; import type { TableSnapshot } from "./schemaCompare"; @@ -400,8 +405,11 @@ function saveViewOptions() { } } -export const tablesKey = (id: string, schema: string) => `${id}\u0000${schema}`; -export const detailsKey = (id: string, schema: string, table: string) => `${id}\u0000${schema}\u0000${table}`; +const catalogKey = (key: string, catalog?: string) => (catalog === undefined ? key : `${key}\u0000${catalog}`); +export const schemasKey = catalogKey; +export const tablesKey = (id: string, schema: string, catalog?: string) => catalogKey(`${id}\u0000${schema}`, catalog); +export const detailsKey = (id: string, schema: string, table: string, catalog?: string) => + catalogKey(`${id}\u0000${schema}\u0000${table}`, catalog); function message(e: unknown): string { return e instanceof Error ? e.message : String(e); @@ -657,6 +665,7 @@ function expandSourceFolder(id: string) { /** Drops cached metadata of target `id` (refresh, disconnect); a data source id drops all its databases. */ function forget(id: string) { invalidateDatabaseRequests(id); + duckdbCatalogLoads.delete(id); const whole = !splitTarget(id).database; const ofTarget = (t: string) => t === id || (whole && splitTarget(t).id === id); const dropKeys = (m: Record) => @@ -1026,6 +1035,14 @@ export function listsDatabases(source: DataSource | undefined): boolean { ); } +export function duckdbCatalogTree(source: DataSource | undefined): boolean { + return source?.driver === "jdbc" && source.vendor === "duckdb"; +} + +export function listsTreeDatabases(source: DataSource | undefined): boolean { + return listsDatabases(source) || duckdbCatalogTree(source); +} + /** New › Database and Drop on database nodes: PostgreSQL and SQL Server data sources that show their databases. */ export function createsDatabases(source: DataSource | undefined): boolean { return listsDatabases(source) && source?.driver !== "snowflake"; @@ -1041,9 +1058,9 @@ export function newSchemaTarget(n: DbNode): string | null { } interface LoadedLevels { - schemas: string[]; - tables: [string, string][]; - details: [string, string, string][]; + schemas: [id: string, catalog?: string][]; + tables: [id: string, schema: string, catalog?: string][]; + details: [id: string, schema: string, table: string, catalog?: string][]; } /** The metadata of target `id` (a data source id: all its databases) the tree has loaded. */ @@ -1057,9 +1074,9 @@ function loadedLevels(id: string): LoadedLevels { const loaded = (m: Record>) => Object.keys(m).filter((k) => ofTarget(k) && m[k]!.status === "ok"); return { - schemas: loaded(st.schemas), - tables: loaded(st.tables).map((k) => k.split("\u0000") as [string, string]), - details: loaded(st.details).map((k) => k.split("\u0000") as [string, string, string]), + schemas: loaded(st.schemas).map((k) => k.split("\u0000") as LoadedLevels["schemas"][number]), + tables: loaded(st.tables).map((k) => k.split("\u0000") as LoadedLevels["tables"][number]), + details: loaded(st.details).map((k) => k.split("\u0000") as LoadedLevels["details"][number]), }; } @@ -1074,26 +1091,30 @@ export async function refresh(id: string, levels = loadedLevels(id)): Promise t), ...details.map(([t]) => t)])].map((target) => [ + [...new Set([...schemas, ...tables, ...details].map(([target]) => target))].map((target) => [ target, databaseRequest(target), ]), ); const valid = (target: string) => targets.get(target)?.() ?? current(); - if (whole && listsDatabases(sourceById(id))) await loadDatabases(id); - else if (!schemas.includes(id)) schemas.push(id); + if (whole && listsTreeDatabases(sourceById(id))) await loadDatabases(id); + else if (!schemas.some(([t, catalog]) => t === id && catalog === undefined)) schemas.push([id]); if (!current()) return; - await Promise.all(schemas.filter(valid).map((t) => loadSchemas(t))); + const listed = useDatabase.getState().databases[id]; + const present = (catalog?: string) => + catalog === undefined || (listed?.status === "ok" && listed.value.names.includes(catalog)); + await Promise.all(schemas.filter(([t, catalog]) => valid(t) && present(catalog)).map(([t, c]) => loadSchemas(t, c))); if (!current()) return; - await Promise.all(tables.filter(([t]) => valid(t)).map(([t, schema]) => loadTables(t, schema))); + // Loading a DuckDB catalog already loaded its tables along with its schemas. + await Promise.all( + tables.filter(([t, , catalog]) => valid(t) && catalog === undefined).map(([t, schema]) => loadTables(t, schema)), + ); if (!current()) return; - const exists = (t: string, schema: string, table: string) => { - const l = useDatabase.getState().tables[tablesKey(t, schema)]; + const exists = (t: string, schema: string, table: string, catalog?: string) => { + const l = useDatabase.getState().tables[tablesKey(t, schema, catalog)]; return l?.status === "ok" && l.value.some((x) => x.name === table); }; - await Promise.all( - details.filter((d) => valid(d[0]) && exists(...d)).map(([t, schema, table]) => loadDetails(t, schema, table)), - ); + await Promise.all(details.filter((d) => valid(d[0]) && exists(...d)).map((d) => loadDetails(...d))); } function metadataRequest(id: string, cache: "databases" | "schemas" | "tables" | "details", key = id) { @@ -1115,19 +1136,35 @@ export async function loadDatabases(id: string): Promise { } } -export async function loadSchemas(id: string): Promise { - const current = metadataRequest(id, "schemas"); +export async function loadSchemas(id: string, catalog?: string): Promise { + const key = schemasKey(id, catalog); + const current = metadataRequest(id, "schemas", key); try { + if (catalog !== undefined) { + const catalogSchemas = await withConnection(id, () => call(commands.dbDatabaseCatalog(id, catalog))); + if (!current()) return; + useDatabase.setState((s) => { + const tables = { ...s.tables }; + for (const schema of catalogSchemas) + tables[tablesKey(id, schema.name, catalog)] = { status: "ok", value: schema.tables }; + return { + schemas: { ...s.schemas, [key]: { status: "ok", value: catalogSchemas.map((schema) => schema.name) } }, + tables, + }; + }); + return; + } const value = await withConnection(id, () => call(commands.dbSchemas(id))); if (!current()) return; useDatabase.setState((s) => ({ schemas: { ...s.schemas, [id]: { status: "ok", value } } })); } catch (e) { if (!current()) return; - useDatabase.setState((s) => ({ schemas: { ...s.schemas, [id]: { status: "error", message: message(e) } } })); + useDatabase.setState((s) => ({ schemas: { ...s.schemas, [key]: { status: "error", message: message(e) } } })); } } -export async function loadTables(id: string, schema: string): Promise { +export async function loadTables(id: string, schema: string, catalog?: string): Promise { + if (catalog !== undefined) return loadSchemas(id, catalog); const key = tablesKey(id, schema); const current = metadataRequest(id, "tables", key); try { @@ -1166,11 +1203,17 @@ export async function schemaSnapshot(id: string, schema: string, signal?: AbortS return out; } -export async function loadDetails(id: string, schema: string, table: string): Promise { - const key = detailsKey(id, schema, table); +export async function loadDetails(id: string, schema: string, table: string, catalog?: string): Promise { + const key = detailsKey(id, schema, table, catalog); const current = metadataRequest(id, "details", key); try { - const value = await withConnection(id, () => call(commands.dbTableDetails(id, schema, table))); + const value = await withConnection(id, () => + call( + catalog === undefined + ? commands.dbTableDetails(id, schema, table) + : commands.dbCatalogTableDetails(id, catalog, schema, table), + ), + ); if (!current()) return; useDatabase.setState((s) => ({ details: { ...s.details, [key]: { status: "ok", value } } })); } catch (e) { @@ -1195,12 +1238,16 @@ export async function revealInTree( table: string, kind: DbTableKind | undefined, column?: string, + catalog?: string, ): Promise { const current = databaseRequest(id); const loaded = (l: Loaded | undefined) => l?.status === "ok"; const { id: sourceId, database } = splitTarget(id); + const source = sourceById(id); + const duck = duckdbCatalogTree(source) || catalog !== undefined; + const eq = nameMatcher("duckdb"); let databaseNode: string[] = []; - if (listsDatabases(sourceById(id))) { + if (listsTreeDatabases(source) || duck) { if (!loaded(useDatabase.getState().databases[sourceId])) { if (!(await connect(sourceId))) return; if (!current()) return; @@ -1208,27 +1255,42 @@ export async function revealInTree( if (!current()) return; } const dbs = useDatabase.getState().databases[sourceId]; - const name = database ?? (dbs?.status === "ok" ? dbs.value.current : null); - if (name) databaseNode = [databaseKey(sourceId, name)]; + if (duck) { + if (dbs?.status !== "ok") return selectInTree([], sourceId); + catalog = catalog === undefined ? dbs.value.current : dbs.value.names.find((name) => eq(name, catalog)); + if (!catalog) return selectInTree([], sourceId); + } + const name = catalog ?? database ?? (dbs?.status === "ok" ? dbs.value.current : null); + if (name) databaseNode = [databaseKey(sourceId, name, duck)]; } - if (!loaded(useDatabase.getState().schemas[id])) { + const schemaKey = schemasKey(id, catalog); + if (!loaded(useDatabase.getState().schemas[schemaKey])) { if (!(await connect(id))) return; if (!current()) return; - await loadSchemas(id); + await loadSchemas(id, catalog); if (!current()) return; } - if (!loaded(useDatabase.getState().tables[tablesKey(id, schema)])) await loadTables(id, schema); + if (duck) { + const schemas = useDatabase.getState().schemas[schemaKey]; + if (schemas?.status === "ok") schema = schemas.value.find((name) => eq(name, schema)) ?? schema; + } + const key = tablesKey(id, schema, catalog); + if (!loaded(useDatabase.getState().tables[key])) await loadTables(id, schema, catalog); if (!current()) return; - if (column && !loaded(useDatabase.getState().details[detailsKey(id, schema, table)])) - await loadDetails(id, schema, table); + const tables = useDatabase.getState().tables[key]; + const match = + tables?.status === "ok" ? tables.value.find((t) => (duck ? eq(t.name, table) : t.name === table)) : undefined; + if (match) table = match.name; + if (column && !loaded(useDatabase.getState().details[detailsKey(id, schema, table, catalog)])) + await loadDetails(id, schema, table, catalog); if (!current()) return; - const tables = useDatabase.getState().tables[tablesKey(id, schema)]; - kind ??= (tables?.status === "ok" ? tables.value.find((t) => t.name === table)?.kind : undefined) ?? "table"; - const folder = `${id}/${schema}/${tableFolder(kind)}`; - const tableKey = `${folder}/${table}`; + kind ??= match?.kind ?? "table"; + const schemaNode = schemaNodeKey(id, schema, catalog); + const folder = `${schemaNode}/${tableFolder(kind)}`; + const tableKey = `${folder}/${treeIdentifier(table, catalog)}`; selectInTree( - [sourceId, ...databaseNode, `${id}/${schema}`, folder, ...(column ? [tableKey, `${tableKey}/columns`] : [])], - column ? `${tableKey}/columns/${column}` : tableKey, + [sourceId, ...databaseNode, schemaNode, folder, ...(column ? [tableKey, `${tableKey}/columns`] : [])], + column ? `${tableKey}/columns/${treeIdentifier(column, catalog)}` : tableKey, ); } @@ -1253,8 +1315,8 @@ function selectInTree(open: string[], key: string) { export async function revealOpened(): Promise { const input = maybeEditorService()?.activeInput?.(); if (input?.kind === TABLE_KIND) { - const { id, schema, table } = input.data as TableRef; - return revealInTree(id, schema, table, undefined); + const { id, schema, table, catalog } = input.data as TableRef; + return revealInTree(id, schema, table, undefined, undefined, catalog); } const editor = activeEditor(); if (editor?.ctx.language !== SQL_LANGUAGE || (input && input.path !== editor.ctx.path)) return; @@ -1265,24 +1327,31 @@ export async function revealOpened(): Promise { const open: string[] = []; let key = sourceId; let nodeTarget = target; - if (listsDatabases(sourceById(sourceId))) { + const source = sourceById(sourceId); + let catalog: string | undefined; + if (listsTreeDatabases(source)) { const dbs = s.databases[sourceId]; const name = database ?? (dbs?.status === "ok" ? dbs.value.current : null); if (dbs?.status !== "ok" || !name) return selectInTree(open, key); open.push(key); - key = databaseKey(sourceId, name); - nodeTarget = targetOf(sourceId, name, dbs.value.current); + if (duckdbCatalogTree(source)) catalog = name; + key = databaseKey(sourceId, name, catalog !== undefined); + nodeTarget = catalog === undefined ? targetOf(sourceId, name, dbs.value.current) : sourceId; } const schema = consoleSchema(editor.ctx.path); - const schemas = s.schemas[nodeTarget]; + const schemas = s.schemas[schemasKey(nodeTarget, catalog)]; if (schema && schemas?.status === "ok" && schemas.value.includes(schema)) { open.push(key); - key = `${nodeTarget}/${schema}`; + key = schemaNodeKey(nodeTarget, schema, catalog); } selectInTree(open, key); } const completionLoads = new Map boolean; promise: Promise }>(); +const duckdbCatalogLoads = new Map< + string, + { names: Promise; catalog?: { name: string; schemas: Promise } } +>(); const preparingConsoles = new Map(); interface ConsoleScope { id: string; @@ -1321,6 +1390,51 @@ export function loadCompletion(id: string): Promise { return pending.promise; } +/** DuckDB attachments belong to this JDBC session. The catalog name is never a connection target. */ +export async function loadDuckdbCatalog(id: string, wanted?: string): Promise { + const sourceId = splitTarget(id).id; + if (!allowsPassiveConsoleMetadata(sourceId)) return undefined; + let live = duckdbCatalogLoads.get(sourceId); + if (!live) { + const names = call(commands.dbDatabases(sourceId)).catch((error) => { + if (duckdbCatalogLoads.get(sourceId)?.names === names) duckdbCatalogLoads.delete(sourceId); + throw error; + }); + live = { names }; + duckdbCatalogLoads.set(sourceId, live); + } + const { names } = await live.names; + if (duckdbCatalogLoads.get(sourceId) !== live) return undefined; + const eq = nameMatcher("duckdb"); + const database = wanted === undefined ? undefined : names.find((name) => eq(name, wanted)); + let schemas: DbCatalogSchema[] = []; + if (database !== undefined) { + if (live.catalog?.name !== database) { + const entry = live; + const schemas = call(commands.dbDatabaseCatalog(sourceId, database)).catch((error) => { + if (entry.catalog?.schemas === schemas) delete entry.catalog; + throw error; + }); + live.catalog = { name: database, schemas }; + } + schemas = await live.catalog.schemas; + } + if (duckdbCatalogLoads.get(sourceId) !== live) return undefined; + return { + databases: names, + schemas: (name) => (name === database ? schemas.map((schema) => schema.name) : null), + tables: (name, schema) => + name === database + ? (schemas + .find((s) => eq(s.name, schema)) + ?.tables.map((table) => ({ + name: table.name, + view: table.kind !== "table", + })) ?? null) + : null, + }; +} + useProject.subscribe((state, previous) => { if (state.project?.root === previous.project?.root) return; sourcesRequest++; @@ -1328,6 +1442,7 @@ useProject.subscribe((state, previous) => { sourceConnectionIntents.clear(); sourceMutations.clear(); completionLoads.clear(); + duckdbCatalogLoads.clear(); preparingConsoles.clear(); for (const scope of consoleScopes.values()) scope.retired = true; consoleScopes.clear(); @@ -1516,8 +1631,14 @@ function promptOf(id: string): string { return useDatabase.getState().completion[id]?.defaultSchema || sourceById(id)?.name || id; } -function changesSchema(outcome: DbStatementOutcome): boolean { - return !outcome.error && /^\s*(create|drop|alter|rename)\b/i.test(outcome.statement.text); +function changesSchema(id: string, outcome: DbStatementOutcome): boolean { + if (outcome.error) return false; + const { text } = outcome.statement; + if (sqlDriverOf(sourceById(id)) === "duckdb") { + const first = /^\s*([a-z_][\w$]*)/i.exec(text)?.[1]?.toUpperCase() ?? lex(text, "duckdb").tokens[0]?.upper; + return /^(ATTACH|DETACH|USE|CREATE|DROP|ALTER|RENAME)$/.test(first ?? ""); + } + return /^\s*(create|drop|alter|rename)\b/i.test(text); } function outcomeUpdates( @@ -1561,6 +1682,7 @@ async function syncDropped(id: string, path?: string) { const current = databaseRequest(id); const server = await call(commands.dbConnected()).catch(() => null); if (!current() || !server || server.includes(id) || !useDatabase.getState().connected.has(id)) return; + duckdbCatalogLoads.delete(id); useDatabase.setState((s) => { const connected = new Set(s.connected); connected.delete(id); @@ -1791,7 +1913,7 @@ async function run( // Consoles publish the same outcome updates alongside their progress and grids. if (progress) return outcomes; useDatabase.setState((s) => outcomeUpdates(s, id, schema, outcomes, !wasConnected, path)); - if (outcomes.some(changesSchema)) void refresh(id); + if (outcomes.some((outcome) => changesSchema(id, outcome))) void refresh(id); return outcomes; } @@ -2034,7 +2156,7 @@ export async function executeConsole( if (!inline) streamingResultTabs.add(tab.id); tabs.push(tab); } - schemaChanged ||= completed.some(changesSchema); + schemaChanged ||= completed.some((outcome) => changesSchema(id, outcome)); useDatabase.setState((s) => { const executions = { ...s.executions, [path]: { ...execution, active } }; const state = completed.length diff --git a/src/features/database/table-editor.test.tsx b/src/features/database/table-editor.test.tsx index 8620dcfe7..20734baca 100644 --- a/src/features/database/table-editor.test.tsx +++ b/src/features/database/table-editor.test.tsx @@ -11,12 +11,21 @@ import { tableInput } from "./tableInput"; const backend = vi.hoisted(() => ({ driver: "clickhouse" as DbDriver, page: vi.fn(), + catalogPage: vi.fn(), applyEdits: vi.fn(), })); vi.mock("@/platform/ipc", async (importOriginal) => { const actual = await importOriginal(); - return { ...actual, commands: { ...actual.commands, dbTablePage: backend.page, dbApplyEdits: backend.applyEdits } }; + return { + ...actual, + commands: { + ...actual.commands, + dbTablePage: backend.page, + dbCatalogTablePage: backend.catalogPage, + dbApplyEdits: backend.applyEdits, + }, + }; }); vi.mock("./store", () => ({ @@ -67,6 +76,30 @@ beforeEach(() => { }); describe("table editor capabilities", () => { + it("routes a catalog preview to its explicit catalog on the base connection", async () => { + backend.driver = "jdbc"; + backend.page.mockClear(); + backend.catalogPage.mockResolvedValue({ status: "ok", data: page }); + const catalog = 'other.db:"part'; + await act(async () => { + render(); + }); + expect(await screen.findByRole("gridcell", { name: "Ann" })).toBeVisible(); + expect(backend.catalogPage).toHaveBeenCalledWith( + expect.any(Number), + "source", + catalog, + "main", + "users", + null, + [], + 0, + 500, + ); + expect(backend.page).not.toHaveBeenCalled(); + expect(screen.queryByRole("button", { name: "Add Row" })).toBeNull(); + }); + it.each(["clickhouse", "jdbc"] as const)( "keeps %s rows read-only even when metadata marks a primary key", async (driver) => { diff --git a/src/features/database/tableInput.ts b/src/features/database/tableInput.ts index 72d247dfa..0f51931bf 100644 --- a/src/features/database/tableInput.ts +++ b/src/features/database/tableInput.ts @@ -6,13 +6,16 @@ export interface TableRef { id: string; schema: string; table: string; + catalog?: string; } export function tableTitle(input: EditorInput): string { - return (input.data as TableRef).table; + const { catalog, schema, table } = input.data as TableRef; + return catalog === undefined ? table : `${catalog}.${schema}.${table}`; } -export function tableInput(id: string, schema: string, table: string): EditorInput { - const data: TableRef = { id, schema, table }; - return { kind: TABLE_KIND, key: `${TABLE_KIND}:${id}:${schema}.${table}`, data }; +export function tableInput(id: string, schema: string, table: string, catalog?: string): EditorInput { + const data: TableRef = catalog === undefined ? { id, schema, table } : { id, schema, table, catalog }; + const key = catalog === undefined ? `${id}:${schema}.${table}` : JSON.stringify([id, catalog, schema, table]); + return { kind: TABLE_KIND, key: `${TABLE_KIND}:${key}`, data }; } diff --git a/src/features/database/treeActions.ts b/src/features/database/treeActions.ts index ab7830a27..244336609 100644 --- a/src/features/database/treeActions.ts +++ b/src/features/database/treeActions.ts @@ -11,7 +11,7 @@ import { registerActions, type Action } from "@/platform/actions"; import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions"; import { splitTarget } from "./model"; import { nodeTarget, objectOf, schemaObjectOf, tableFolder, tableOf, type DbNode } from "./nodes"; -import { canDrop, canModifyTable, canRename, reference, scriptSql, type ScriptKind } from "./objects"; +import { canDrop, canModifyTable, canRename, quoteIdent, reference, scriptSql, type ScriptKind } from "./objects"; import { DB_TOOL_WINDOW, OUTPUT_TAB, @@ -98,8 +98,8 @@ function rowAnchor(): { x: number; y: number } { return r ? { x: r.left + 24, y: r.bottom + 2 } : { x: window.innerWidth / 2, y: window.innerHeight / 3 }; } -export function openTableData(id: string, schema: string, table: string) { - void editorService().openInput(tableInput(id, schema, table), { focus: true }); +export function openTableData(id: string, schema: string, table: string, catalog?: string) { + void editorService().openInput(tableInput(id, schema, table, catalog), { focus: true }); } /** Tables of a schema, loading them if needed. */ @@ -190,6 +190,7 @@ async function showDiagram(nodes: DbNode[], popup: boolean): Promise { const add = (id: string, schema: string, name: string) => refs.set(detailsKey(id, schema, name), { id, schema, name }); for (const n of nodes) { + if ("catalog" in n && n.catalog !== undefined) continue; if (n.kind === "table") add(n.id, n.schema, n.table.name); else if ( n.kind === "schema" || @@ -359,10 +360,10 @@ function refreshNode(n: DbNode | null) { } const id = nodeTarget(n); if (!id) return; - if (n.kind === "schema" || n.kind === "folder") void loadTables(id, n.schema); + if (n.kind === "schema" || n.kind === "folder") void loadTables(id, n.schema, n.catalog); else if (tableOf(n)) { const t = tableOf(n)!; - void loadDetails(t.id, t.schema, t.table); + void loadDetails(t.id, t.schema, t.table, t.catalog); } else void refresh(id); } @@ -448,7 +449,7 @@ export function registerDatabaseTreeActions(): () => void { run: ({ arg }) => { const n = nodeFrom(arg); const t = n && tableOf(n); - if (t) openTableData(t.id, t.schema, t.table); + if (t) openTableData(t.id, t.schema, t.table, t.catalog); }, }), tree({ @@ -461,7 +462,7 @@ export function registerDatabaseTreeActions(): () => void { const o = n && schemaObjectOf(n); if (o) return void openObjectDdl(o.id, o.schema, o.kind, o.name); const t = n && tableOf(n); - if (t) void openDdl(t.id, t.schema, t.table); + if (t && t.catalog === undefined) void openDdl(t.id, t.schema, t.table); }, }), tree({ @@ -680,7 +681,13 @@ export function registerDatabaseTreeActions(): () => void { if (n.kind === "source") return void copy(n.source.name ?? "", tx("Cannot copy the name")); if (n.kind === "database") return void copy(n.name, tx("Cannot copy the name")); const o = objectOf(n); - if (id && o) void copy(reference(driverOf(id), o), tx("Cannot copy the reference")); + if (!id || !o) return; + if ("catalog" in n && n.catalog !== undefined) { + const parts = n.kind === "schema" ? [n.catalog, n.schema] : [n.catalog, o.schema, o.name]; + if (n.kind === "column") parts.push(n.column.name); + return void copy(parts.map((name) => quoteIdent("jdbc", name)).join("."), tx("Cannot copy the reference")); + } + void copy(reference(driverOf(id), o), tx("Cannot copy the reference")); }, }), tree({ diff --git a/src/features/database/treeMenu.ts b/src/features/database/treeMenu.ts index 9e6d960f9..8e25576f7 100644 --- a/src/features/database/treeMenu.ts +++ b/src/features/database/treeMenu.ts @@ -193,6 +193,14 @@ export function nodeMenu(n: DbNode | null, selection: readonly DbNode[] = []): M submenu: [...extra, act("db.jumpToConsole", n)], }); + if ("catalog" in n && n.catalog !== undefined) { + return [ + ...(t ? [act("db.editData", n, { label: "View Data" })] : []), + refresh, + { label: "Copy/Paste", submenu: [copyRef] }, + ]; + } + if (driver === "jdbc" && n.kind !== "source" && n.kind !== "sourceFolder") { return [ newConsole, diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index bbbc04161..d06affa32 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -1305,6 +1305,8 @@ "Database": "資料庫", "Database actions": "資料庫操作", "Database output": "資料庫輸出", + "Catalog browsing requires a DuckDB data source": "瀏覽目錄需要 DuckDB 資料來源", + "View Data": "檢視資料", "Database:": "資料庫:", "Date": "日期", "Date Formats": "日期格式", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 63b8ae63a..59ea5fd90 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10699,6 +10699,8 @@ "Blocked command pattern": "阻止的命令模式", "Mode applies to": "模式作用范围", "Could not load the frames: {0}": "无法加载栈帧:{0}", + "Catalog browsing requires a DuckDB data source": "浏览目录需要 DuckDB 数据源", + "View Data": "查看数据", "Allow all optional permissions": "允许全部可选权限", "Extract Embedded Images…": "提取嵌入的图片…", "The document changed or is no longer editable.": "文档已更改或无法再编辑。",