diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index cc3cb6753..26314ee65 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -25,8 +25,8 @@ pub use conn::{Held, Pool, QueryResult, ResultColumn}; pub use history::HistoryEntry; pub use plan::{PlanNode, PlanProperty}; pub use source::{ - DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSnowflake, DbSnowflakeAuth, DbSsh, - DbSshAuth, DbSslMode, DbTxMode, + DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection, DbSnowflake, + DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange, }; pub use sql::{CellValue, DbRowEdit, SortKey}; @@ -518,7 +518,7 @@ impl DbManager { Ok(source) } - /// Saves the data source list; connections of removed or changed sources are closed. + /// Saves the data source list, preserving connections when only visibility rules change. /// Global ones (`global`) go to the app-wide list, the others to the project's. pub async fn save_sources(&self, mut sources: Vec) -> IdeResult<()> { if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) { @@ -551,7 +551,7 @@ impl DbManager { }; for o in old { match sources.iter().find(|s| s.id == o.id) { - Some(n) if *n == o => {} + Some(n) if o.same_except_visibility(n) => {} gone_or_changed => { let keys = [o.id.clone(), secrets::jdbc_key(&o.id), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)]; @@ -585,6 +585,31 @@ impl DbManager { Ok(()) } + /// Updates one scope of a source's visibility against its latest saved rules. + pub fn save_source_visibility(&self, id: &str, available: &[String], change: DbVisibilityChange) -> IdeResult<()> { + let _guard = plugin::EDIT.lock(); + let mut sources = source::load(&self.root)?; + let scoped_global = self.global.as_ref().filter(|_| !sources.iter().any(|source| source.id == id)); + if let Some((dir, _)) = scoped_global { + sources = source::load_global(dir)?; + } + let selected = sources + .iter_mut() + .find(|source| source.id == id) + .ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?; + let previous = selected.introspection.clone(); + change.apply(&mut selected.introspection, available); + if selected.introspection == previous { + return Ok(()); + } + if let Some((dir, _)) = scoped_global { + source::save_global(dir, &sources)?; + } else { + source::save(&self.root, &sources)?; + } + Ok(()) + } + /// Watches the data source files (the project's and the global one) for edits made /// outside the IDE; `on_change` runs on a background thread once they settle, and /// should call [`DbManager::reconcile_sources`]. Stops when the result is dropped. @@ -593,9 +618,9 @@ impl DbManager { SourcesWatch::start(&self.root, self.global.as_ref().map(|(dir, _)| dir.as_path()), on_change) } - /// Re-reads the data sources after their files changed on disk: connections of - /// removed or changed sources close, as on [`DbManager::save_sources`] (saved - /// passwords stay, the source may come back). Returns whether the list the tree + /// Re-reads the data sources after their files changed on disk and closes affected + /// connections as on [`DbManager::save_sources`] (saved passwords stay, the source + /// may come back). Returns whether the list the tree /// shows changed, or the files no longer parse (the tree reports the error). pub async fn reconcile_sources(&self) -> bool { let now = match self.sources() { @@ -610,7 +635,7 @@ impl DbManager { return false; } for o in &before { - if now.iter().find(|s| s.id == o.id) != Some(o) { + if now.iter().find(|s| s.id == o.id).is_none_or(|n| !o.same_except_visibility(n)) { self.disconnect_source(&o.id).await; } } diff --git a/crates/ide-db/src/source.rs b/crates/ide-db/src/source.rs index 28ad3a719..f3408b47f 100644 --- a/crates/ide-db/src/source.rs +++ b/crates/ide-db/src/source.rs @@ -6,6 +6,7 @@ use ide_core::{IdeError, IdeResult, IpcPath, project_dir}; use serde::{Deserialize, Serialize}; use specta::Type; +use std::collections::BTreeMap; use std::path::Path; pub(crate) const FILE: &str = "data-sources.toml"; @@ -101,6 +102,9 @@ pub struct DbIntrospection { pub databases: Vec, pub all_schemas: bool, pub schemas: Vec, + /// A database can replace the source's schema rules with all schemas or a list of exact names. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub schemas_by_database: BTreeMap, /// `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…). pub show_system: bool, /// PostgreSQL template databases (`template0`, `template1`). @@ -117,6 +121,7 @@ impl Default for DbIntrospection { databases: Vec::new(), all_schemas: true, schemas: Vec::new(), + schemas_by_database: BTreeMap::new(), show_system: false, show_templates: false, object_filter: String::new(), @@ -125,6 +130,18 @@ impl Default for DbIntrospection { } impl DbIntrospection { + pub(crate) fn with_visibility_from(self, source: &Self) -> Self { + Self { + all_databases: source.all_databases, + databases: source.databases.clone(), + all_schemas: source.all_schemas, + schemas: source.schemas.clone(), + schemas_by_database: source.schemas_by_database.clone(), + object_filter: source.object_filter.clone(), + ..self + } + } + /// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to /// match one of the `schemas` patterns. The completion model uses the same test, so it /// offers exactly the tables the tree lists (and does not read the ones it never shows). @@ -163,6 +180,60 @@ fn schema_matches(pattern: &str, name: &str) -> bool { p[pi..].iter().all(|&c| c == '*') } +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default)] +pub struct DbSchemaSelection { + pub all: bool, + pub names: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum DbVisibilityChange { + Databases { selection: DbSchemaSelection }, + Schemas { selection: DbSchemaSelection }, + DatabaseSchemas { database: String, selection: Option }, +} + +impl DbVisibilityChange { + pub(crate) fn apply(self, introspection: &mut DbIntrospection, available: &[String]) { + let available: std::collections::HashSet<_> = available.iter().map(String::as_str).collect(); + let keep_names = |before: &mut Vec, selection: DbSchemaSelection, exact: bool| { + if selection.all || (!exact && before.iter().any(|name| name.contains(['*', '?']))) { + return; + } + before.retain(|name| !available.contains(if exact { name.as_str() } else { name.trim() })); + let mut seen: std::collections::HashSet<_> = before.iter().cloned().collect(); + before.extend( + selection + .names + .into_iter() + .filter(|name| (exact || !name.contains(['*', '?'])) && seen.insert(name.clone())), + ); + }; + match self { + Self::Databases { selection } => { + introspection.all_databases = selection.all; + keep_names(&mut introspection.databases, selection, false); + } + Self::Schemas { selection } => { + introspection.all_schemas = selection.all; + keep_names(&mut introspection.schemas, selection, false); + } + Self::DatabaseSchemas { database, selection } => match selection { + Some(selection) => { + let rule = introspection.schemas_by_database.entry(database).or_default(); + rule.all = selection.all; + keep_names(&mut rule.names, selection, true); + } + None => { + introspection.schemas_by_database.remove(&database); + } + }, + } + } +} + /// Advanced tab: a driver property. PostgreSQL: run-time parameters (and /// `application_name`); MySQL: session variables (and `charset`, `collation`); /// SQLite: pragmas. See [`crate::conn`]. @@ -430,6 +501,14 @@ pub fn parse_url(raw: &str) -> IdeResult { } impl DataSource { + pub(crate) fn same_except_visibility(&self, other: &Self) -> bool { + if self == other { + return true; + } + let introspection = other.introspection.clone().with_visibility_from(&self.introspection); + *self == Self { introspection, ..other.clone() } + } + /// The settings to connect with: with [`DataSource::url_only`], host, port, /// database, user, SSL and driver properties come from the URL (properties /// of the Advanced tab still apply after the URL's). @@ -661,6 +740,81 @@ mod tests { assert_eq!(load(tmp.path()).unwrap(), vec![s]); } + #[test] + fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() { + let mut introspection = DbIntrospection { + schemas: vec!["app_*".into(), "unavailable_?".into()], + databases: vec!["reporting".into(), "offline".into()], + schemas_by_database: BTreeMap::from([ + ("reporting".into(), DbSchemaSelection { all: false, names: vec!["private".into()] }), + ("sandbox".into(), DbSchemaSelection { all: false, names: vec!["experiments".into()] }), + ]), + show_system: true, + ..Default::default() + }; + DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: false, names: vec!["demo".into()] } } + .apply(&mut introspection, &["app_sales".into(), "demo".into()]); + assert_eq!(introspection.schemas, ["app_*", "unavailable_?"]); + DbVisibilityChange::Databases { selection: DbSchemaSelection { all: false, names: vec!["sandbox".into()] } } + .apply(&mut introspection, &["reporting".into(), "sandbox".into()]); + assert_eq!(introspection.databases, ["offline", "sandbox"]); + DbVisibilityChange::DatabaseSchemas { + database: "reporting".into(), + selection: Some(DbSchemaSelection { + all: false, + names: vec!["finance".into(), "finance".into(), "private".into()], + }), + } + .apply(&mut introspection, &["public".into(), "finance".into()]); + assert_eq!(introspection.schemas_by_database["reporting"].names, ["private", "finance"]); + assert_eq!(introspection.schemas_by_database["sandbox"].names, ["experiments"]); + assert!(introspection.show_system); + } + + #[test] + fn schema_override_can_omit_default_fields() { + let introspection: DbIntrospection = toml::from_str( + r#" + [schemasByDatabase.reporting] + all = true + + [schemasByDatabase.sandbox] + names = ["finance"] + "#, + ) + .unwrap(); + assert_eq!( + introspection.schemas_by_database, + BTreeMap::from([ + ("reporting".into(), DbSchemaSelection { all: true, names: vec![] }), + ("sandbox".into(), DbSchemaSelection { all: false, names: vec!["finance".into()] }), + ]) + ); + } + + #[test] + fn round_trips_database_schema_overrides() { + let tmp = tempfile::tempdir().unwrap(); + let source = DataSource { + id: "postgres".into(), + name: "PostgreSQL Demo".into(), + driver: DbDriver::Postgres, + introspection: DbIntrospection { + all_schemas: false, + schemas: vec!["app_*".into()], + schemas_by_database: BTreeMap::from([ + ("analytics".into(), DbSchemaSelection { all: true, names: vec![] }), + ("reporting.eu".into(), DbSchemaSelection { all: false, names: vec!["public".into()] }), + ("sandbox".into(), DbSchemaSelection { all: false, names: vec![] }), + ]), + ..Default::default() + }, + ..Default::default() + }; + save(tmp.path(), std::slice::from_ref(&source)).unwrap(); + assert_eq!(load(tmp.path()).unwrap(), vec![source]); + } + #[test] fn sqlserver_defaults() { assert_eq!(DbDriver::SqlServer.default_port(), Some(1433)); diff --git a/crates/ide-db/tests/sqlite.rs b/crates/ide-db/tests/sqlite.rs index b68b9b5c1..683755e82 100644 --- a/crates/ide-db/tests/sqlite.rs +++ b/crates/ide-db/tests/sqlite.rs @@ -2,7 +2,8 @@ use ide_core::{CancellationToken, IdeResult}; use ide_db::{ - CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbTableKind, QueryResult, SortKey, + CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection, DbTableKind, + DbVisibilityChange, QueryResult, SortKey, }; async fn setup() -> (tempfile::TempDir, DbManager) { @@ -242,6 +243,72 @@ async fn manual_commit_keeps_a_transaction_until_commit_or_rollback() -> IdeResu Ok(()) } +#[tokio::test] +async fn visibility_edits_preserve_the_held_transaction() -> IdeResult<()> { + let (tmp, db) = setup().await; + let c = CancellationToken::new(); + db.set_manual_commit("s1", true).await?; + db.execute("s1", "INSERT INTO users (name) VALUES ('dee')", 1, &c).await?; + assert_eq!(count(&db).await, "4"); + + let mut source = db.source("s1")?; + source.introspection.all_schemas = false; + source.introspection.schemas.clear(); + db.save_sources(vec![source.clone()]).await?; + assert!(db.is_connected("s1"), "saving rules must keep the active connection"); + assert_eq!(count(&db).await, "4", "the held transaction must still see its uncommitted row"); + db.save_source_visibility( + "s1", + &["main".into()], + DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: true, names: vec![] } }, + )?; + assert!(db.source("s1")?.introspection.all_schemas); + assert_eq!(count(&db).await, "4", "the scoped save must keep the live transaction"); + + db.reconcile_sources().await; + let root = tmp.path(); + let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json"))); + let other = DbManager::new(root.to_path_buf(), root.join("passwords.json"), root.join("history.json"), ssh); + source = db.source("s1")?; + source.introspection.object_filter = "user*".into(); + other.save_sources(vec![source.clone()]).await?; + assert!(db.reconcile_sources().await); + assert_eq!(count(&db).await, "4", "a visibility edit from another window must keep the transaction"); + db.finish_transaction("s1", true).await?; + assert_eq!(count(&db).await, "4"); + + source.introspection.show_system = true; + db.save_sources(vec![source]).await?; + assert!(!db.is_connected("s1"), "raw metadata option changes keep their invalidation path"); + Ok(()) +} + +#[tokio::test] +async fn visibility_save_does_not_mask_an_unreconciled_connection_edit() -> IdeResult<()> { + let (tmp, db) = setup().await; + let first = db.source("s1")?; + let second = DataSource { id: "s2".into(), name: "Another source".into(), ..first.clone() }; + db.save_sources(vec![first.clone(), second.clone()]).await?; + db.reconcile_sources().await; + assert!(db.is_connected("s1")); + + let root = tmp.path(); + let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json"))); + let external = DbManager::new(root.to_path_buf(), root.join("passwords.json"), root.join("history.json"), ssh); + external.save_sources(vec![DataSource { read_only: true, ..first }, second]).await?; + db.save_source_visibility( + "s2", + &["main".into()], + DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: false, names: vec![] } }, + )?; + + assert!(db.is_connected("s1")); + assert!(db.reconcile_sources().await); + assert!(!db.is_connected("s1")); + assert!(!db.source("s2")?.introspection.all_schemas); + Ok(()) +} + #[tokio::test] async fn targets_name_a_database_of_a_data_source() -> IdeResult<()> { let (_tmp, db) = setup().await; diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index 18f08c4a1..6c07ddebb 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -8,8 +8,8 @@ use ide_command::command; use ide_core::{IdeError, IdeResult, IpcPath, RequestId}; use ide_db::split::SqlStatement; use ide_db::{ - CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, HistoryEntry, PlanNode, QueryResult, - SchemaObjects, SortKey, TableDetails, TableInfo, TablePage, + CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode, + QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage, }; use serde::{Deserialize, Serialize}; use specta::Type; @@ -72,6 +72,25 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec // Replaces the project's data sources with `sources`. let db = host.project(window)?.db.clone(); db.save_sources(sources).await?; + sources_changed(host, window) +} + +#[command(trust = trusted)] +pub async fn db_save_source_visibility( + host: &Host, + window: &str, + id: String, + available: Vec, + change: DbVisibilityChange, +) -> IdeResult<()> { + let db = host.project(window)?.db.clone(); + tokio::task::spawn_blocking(move || db.save_source_visibility(&id, &available, change)) + .await + .map_err(|e| IdeError::internal(e.to_string()))??; + sources_changed(host, window) +} + +fn sources_changed(host: &Host, window: &str) -> IdeResult<()> { let root = host.project(window)?.root.clone(); for project in host.projects().into_iter().filter(|p| p.root == root) { project.sink.emit(ide_core::IdeEvent::DbSourcesChanged); @@ -603,6 +622,7 @@ ide_command::domain!( db_object_ddl, db_remove_history, db_retain_catalog, + db_save_source_visibility, db_save_sources, db_saved_catalog, db_schema_objects, diff --git a/e2e/databaseIntrospectionChooser.spec.ts b/e2e/databaseIntrospectionChooser.spec.ts new file mode 100644 index 000000000..6bd3ff314 --- /dev/null +++ b/e2e/databaseIntrospectionChooser.spec.ts @@ -0,0 +1,311 @@ +import type { Page } from "@playwright/test"; +import type { DataSource_Deserialize, DbSchemaSelection, DbVisibilityChange } from "../src/bindings"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const databasePanel = (page: Page) => page.locator('section[aria-label="Database"]'); + +async function persistedSources(page: Page): Promise { + return page.evaluate(() => window.__ipc.handlers.db_sources!({}) as DataSource_Deserialize[]); +} + +async function openTree(page: Page, sources: DataSource_Deserialize[]) { + await stubDesktop(page); + await page.evaluate(async (sources) => { + const storePath = "/src/features/database/store.ts"; + const contributionsPath = "/src/workbench/contributions.ts"; + const { useDatabase } = await import(storePath); + const { toolWindowService } = await import(contributionsPath); + const connected = new Set(); + Object.assign(window.__ipc.handlers, { + db_sources: () => sources, + db_connected: () => [...connected], + db_connect: ({ id }: { id: string }) => { + connected.add(id); + return null; + }, + db_disconnect: () => null, + db_databases: () => ({ names: ["reporting", "sandbox", "maintenance"], current: "reporting" }), + db_schemas: ({ id }: { id: string }) => + id === "ch" ? ["demo", "events", "warehouse"] : ["public", "app_data", "scratch"], + db_save_sources: ({ sources: next }: { sources: DataSource_Deserialize[] }) => { + sources = next; + return null; + }, + db_save_source_visibility: ({ + id, + available, + change, + }: { + id: string; + available: string[]; + change: DbVisibilityChange; + }) => { + const update = (before: string[], selection: DbSchemaSelection, exact = false) => + selection.all || (!exact && before.some((name) => /[*?]/.test(name))) + ? before + : [...before.filter((name) => !available.includes(name)), ...(selection.names ?? [])]; + sources = sources.map((source) => { + if (id !== source.id) return source; + const introspection: NonNullable = { ...source.introspection }; + const selection = change.selection; + if (change.kind === "databaseSchemas") { + const overrides: Record = { ...introspection.schemasByDatabase }; + if (!selection) delete overrides[change.database]; + else + overrides[change.database] = { + all: selection.all, + names: update(overrides[change.database]?.names ?? [], selection, true), + }; + introspection.schemasByDatabase = overrides; + } else if (change.kind === "databases") { + introspection.allDatabases = selection?.all; + if (selection) introspection.databases = update(introspection.databases ?? [], selection); + } else { + introspection.allSchemas = selection?.all; + if (selection) introspection.schemas = update(introspection.schemas ?? [], selection); + } + return { ...source, introspection }; + }); + return null; + }, + }); + useDatabase.setState({ sources, loaded: true, connected: new Set(), schemas: {}, databases: {} }); + toolWindowService().show("database", true); + }, sources); + return databasePanel(page); +} + +test("the localized chooser keeps source and database names verbatim", async ({ workbench: page }) => { + await page.evaluate(async () => { + const localePath = "/src/platform/i18n.ts"; + await (await import(/* @vite-ignore */ localePath)).setLocale("zh"); + }); + await openTree(page, [{ id: "ch", name: "Apply", driver: "clickhouse" }]); + await page.evaluate(() => { + window.__ipc.handlers.db_schemas = () => ["Retry"]; + }); + await page.getByRole("button", { name: "选择 Apply 的数据库", exact: true }).click(); + const dialog = page.getByRole("dialog", { name: "选择 Apply 的数据库", exact: true }); + await expect(dialog.getByRole("checkbox", { name: "Retry", exact: true })).toBeChecked(); + await expect(dialog.getByRole("button", { name: "应用", exact: true })).toBeVisible(); +}); + +test("a flat ClickHouse count applies a selection and cancels unsaved changes", async ({ workbench: page }, info) => { + const panel = await openTree(page, [{ id: "ch", name: "ClickHouse Demo", driver: "clickhouse" }]); + const source = panel.getByRole("treeitem").filter({ hasText: "ClickHouse Demo" }); + await source.locator("[data-tree-toggle]").click(); + await expect(panel.getByText("warehouse", { exact: true })).toBeVisible(); + await page.screenshot({ path: info.outputPath("clickhouse-tree.png"), animations: "disabled" }); + + const count = source.getByRole("button", { name: "Choose databases for ClickHouse Demo" }); + await expect(count).toHaveText("3 of 3"); + await count.focus(); + await count.press("Enter"); + const dialog = page.getByRole("dialog", { name: "Choose databases for ClickHouse Demo" }); + const search = dialog.getByRole("textbox", { name: "Filter names" }); + await expect(search).toBeFocused(); + await page.screenshot({ path: info.outputPath("clickhouse-chooser.png"), animations: "disabled" }); + await search.fill("ware"); + await expect(dialog.getByRole("checkbox", { name: "demo", exact: true })).toHaveCount(0); + await dialog.getByRole("checkbox", { name: "warehouse", exact: true }).focus(); + await page.keyboard.press("Space"); + await page.keyboard.press("Enter"); + await expect(dialog).toHaveCount(0); + await expect(count).toHaveText("2 of 3"); + await expect(panel.getByText("warehouse", { exact: true })).toHaveCount(0); + expect(await ipcCalls(page, "db_schemas")).toHaveLength(1); + expect(await persistedSources(page)).toMatchObject([ + { id: "ch", introspection: { allSchemas: false, schemas: ["demo", "events"] } }, + ]); + + await count.click(); + await search.fill(""); + await dialog.getByRole("checkbox", { name: "demo", exact: true }).uncheck(); + await count.click(); + await expect(dialog.getByRole("checkbox", { name: "demo", exact: true })).not.toBeChecked(); + await page.keyboard.press("Escape"); + await expect(dialog).toHaveCount(0); + await expect(count).toBeFocused(); + await count.click(); + await dialog.getByRole("checkbox", { name: "events", exact: true }).uncheck(); + await page.locator("body").click({ position: { x: 450, y: 425 } }); + await expect(dialog).toHaveCount(0); + await expect(count).toHaveText("1 of 3"); + expect(await ipcCalls(page, "db_save_source_visibility")).toHaveLength(2); + + await count.click(); + await dialog.getByRole("checkbox", { name: "demo", exact: true }).uncheck(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(count).toHaveText("0 of 3"); + await expect(panel.getByText("demo", { exact: true })).toHaveCount(0); +}); + +test("a PostgreSQL database picker loads that database and overrides the source defaults", async ({ + workbench: page, +}, info) => { + const panel = await openTree(page, [ + { + id: "pg", + name: "PostgreSQL Demo", + driver: "postgres", + introspection: { allSchemas: false, schemas: ["app_*"], objectFilter: "order*" }, + }, + ]); + const source = panel.getByRole("treeitem").filter({ hasText: "PostgreSQL Demo" }); + await source.locator("[data-tree-toggle]").click(); + const reporting = panel.getByRole("treeitem").filter({ hasText: "reporting" }); + await expect(reporting).toBeVisible(); + expect(await ipcCalls(page, "db_schemas")).toHaveLength(0); + const count = reporting.getByRole("button", { name: "Choose schemas for reporting" }); + await count.click(); + const dialog = page.getByRole("dialog", { name: "Choose schemas for reporting" }); + await expect(dialog.getByRole("checkbox", { name: "app_data", exact: true })).toBeChecked(); + await expect(dialog.getByRole("checkbox", { name: "public", exact: true })).not.toBeChecked(); + await page.screenshot({ path: info.outputPath("postgres-schema-chooser.png"), animations: "disabled" }); + expect(await ipcCalls(page, "db_schemas")).toMatchObject([{ id: "pg" }]); + await dialog.getByRole("checkbox", { name: "public", exact: true }).check(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(dialog).toHaveCount(0); + expect(await persistedSources(page)).toMatchObject([ + { + id: "pg", + introspection: { + allSchemas: false, + schemas: ["app_*"], + objectFilter: "order*", + schemasByDatabase: { reporting: { all: false, names: ["public", "app_data"] } }, + }, + }, + ]); + + const sandbox = panel + .getByRole("treeitem") + .filter({ hasText: "sandbox" }) + .getByRole("button", { name: "Choose schemas for sandbox" }); + await sandbox.click(); + const sibling = page.getByRole("dialog", { name: "Choose schemas for sandbox" }); + await expect(sibling.getByRole("checkbox", { name: "app_data", exact: true })).toBeChecked(); + await expect(sibling.getByRole("checkbox", { name: "public", exact: true })).not.toBeChecked(); + await sibling.getByRole("button", { name: "Cancel", exact: true }).click(); + await count.click(); + await dialog.getByRole("checkbox", { name: "Use source settings", exact: true }).check(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(dialog).toHaveCount(0); + expect(await persistedSources(page)).toMatchObject([ + { introspection: { schemas: ["app_*"], schemasByDatabase: {} } }, + ]); +}); + +test("a PostgreSQL source keeps the connected database while narrowing the catalog", async ({ workbench: page }) => { + const panel = await openTree(page, [{ id: "pg", name: "PostgreSQL Demo", driver: "postgres" }]); + const source = panel.getByRole("treeitem").filter({ hasText: "PostgreSQL Demo" }); + await source.locator("[data-tree-toggle]").click(); + const count = source.getByRole("button", { name: "Choose databases for PostgreSQL Demo" }); + await expect(count).toHaveText("3 of 3"); + await count.click(); + const dialog = page.getByRole("dialog", { name: "Choose databases for PostgreSQL Demo" }); + const current = dialog.getByRole("checkbox", { name: "reporting Current database", exact: true }); + await expect(current).toBeChecked(); + await expect(current).toBeDisabled(); + await dialog.getByRole("checkbox", { name: "All databases", exact: true }).uncheck(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(count).toHaveText("1 of 3"); + await expect(panel.getByText("reporting", { exact: true })).toBeVisible(); + await expect(panel.getByText("sandbox", { exact: true })).toHaveCount(0); + expect(await ipcCalls(page, "db_schemas")).toHaveLength(0); +}); + +test("the source picker keeps matching and currently unavailable wildcard rules", async ({ workbench: page }) => { + const schemas = ["ev*", "unavailable_?"]; + const panel = await openTree(page, [ + { id: "ch", name: "ClickHouse Demo", driver: "clickhouse", introspection: { allSchemas: false, schemas } }, + ]); + const count = panel.getByRole("button", { name: "Choose databases for ClickHouse Demo" }); + await count.click(); + const dialog = page.getByRole("dialog", { name: "Choose databases for ClickHouse Demo" }); + const events = dialog.getByRole("checkbox", { name: "events", exact: true }); + await expect(events).toBeChecked(); + await expect(events).toBeDisabled(); + await expect(dialog).toHaveAccessibleDescription("Edit name patterns in Data Source Properties."); + await dialog.getByRole("checkbox", { name: "All databases", exact: true }).check(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(count).toHaveText("3 of 3"); + expect(await persistedSources(page)).toMatchObject([{ introspection: { allSchemas: true, schemas } }]); + await count.click(); + await dialog.getByRole("checkbox", { name: "All databases", exact: true }).uncheck(); + await expect(events).toBeChecked(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(count).toHaveText("1 of 3"); + expect(await persistedSources(page)).toMatchObject([{ introspection: { allSchemas: false, schemas } }]); +}); + +test("the picker keeps explicitly chosen names absent from the catalog", async ({ workbench: page }) => { + const panel = await openTree(page, [ + { + id: "ch", + name: "ClickHouse Demo", + driver: "clickhouse", + introspection: { allSchemas: false, schemas: ["demo", "unavailable"] }, + }, + ]); + const count = panel.getByRole("button", { name: "Choose databases for ClickHouse Demo" }); + await count.click(); + const dialog = page.getByRole("dialog", { name: "Choose databases for ClickHouse Demo" }); + await dialog.getByRole("checkbox", { name: "events", exact: true }).check(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(count).toHaveText("2 of 3"); + expect(await persistedSources(page)).toMatchObject([ + { introspection: { allSchemas: false, schemas: expect.arrayContaining(["demo", "events", "unavailable"]) } }, + ]); +}); + +test("editing the Properties defaults preserves the per-database override", async ({ workbench: page }) => { + const schemasByDatabase = { reporting: { all: false, names: ["finance"] } }; + const panel = await openTree(page, [ + { + id: "pg", + name: "PostgreSQL Demo", + driver: "postgres", + host: "example.invalid", + introspection: { schemasByDatabase }, + }, + ]); + await panel.getByRole("button", { name: "Data Source Properties…" }).click(); + const dialog = page.getByRole("dialog", { name: "Data Source: PostgreSQL Demo" }); + await dialog.getByRole("tab", { name: "Schemas", exact: true }).click(); + await dialog.locator("#db-object-filter").fill("order*"); + await dialog.getByRole("button", { name: "OK", exact: true }).click(); + await expect(dialog).toHaveCount(0); + const [save] = await ipcCalls(page, "db_save_sources"); + expect(save).toMatchObject({ sources: [{ introspection: { schemasByDatabase, objectFilter: "order*" } }] }); +}); + +test("an older remote server refuses the picker save without falling back", async ({ workbench: page }) => { + const panel = await openTree(page, [{ id: "pg", name: "PostgreSQL Demo", driver: "postgres" }]); + const count = panel.getByRole("button", { name: "Choose databases for PostgreSQL Demo" }); + await count.click(); + const dialog = page.getByRole("dialog", { name: "Choose databases for PostgreSQL Demo" }); + await dialog.getByRole("checkbox", { name: "sandbox", exact: true }).uncheck(); + await page.evaluate(async () => { + const remotePath = "/src/platform/remote.ts"; + const { enableRemote } = await import(remotePath); + window.__ipc.handlers.remote_invoke = () => { + throw { kind: "protocol", message: "command db_save_source_visibility is not available remotely", data: null }; + }; + enableRemote({ + target: { kind: "ssh", config: "synthetic" }, + root: "/project", + host: "test.invalid", + os: "linux", + commands: ["db_save_source_visibility"], + }); + }); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(dialog.getByRole("alert")).toHaveText( + "Update the remote OpenIDEA server to edit visibility from the tree.", + ); + expect(await ipcCalls(page, "remote_invoke")).toMatchObject([{ cmd: "db_save_source_visibility" }]); + expect(await ipcCalls(page, "db_save_sources")).toHaveLength(0); + expect(await ipcCalls(page, "db_disconnect")).toHaveLength(0); + await expect(count).toHaveText("3 of 3"); +}); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 065a6eaa5..477fcfc03 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -124,6 +124,7 @@ db_remove_jdbc_driver trusted project_host bin db_retain_catalog trusted project_host bindings async db_run_tool trusted desktop bindings async db_save_jdbc_driver trusted project_host bindings sync +db_save_source_visibility trusted project_host bindings async db_save_sources trusted project_host bindings async db_saved_catalog trusted project_host bindings async db_schema_objects trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 0f64c75ab..0b219bfdc 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -349,6 +349,7 @@ export const commands = { */ dbRunTool: (request: RequestId, id: string, executable: string, job: DbToolJob, onOutput: Channel) => typedError(__TAURI_INVOKE("db_run_tool", { request, id, executable, job, onOutput })), dbSaveJdbcDriver: (driver: DbJdbcDriver_Deserialize) => typedError(__TAURI_INVOKE("db_save_jdbc_driver", { driver })), + dbSaveSourceVisibility: (id: string, available: string[], change: DbVisibilityChange) => typedError(__TAURI_INVOKE("db_save_source_visibility", { id, available, change })), dbSaveSources: (sources: DataSource_Deserialize[]) => typedError(__TAURI_INVOKE("db_save_sources", { sources })), dbSavedCatalog: (id: string) => typedError<{ databases?: DbCatalogDatabase[], @@ -4403,7 +4404,7 @@ export type DataSource_Deserialize = { sslCertFile?: string, sslKeyFile?: string, options?: DbOptions, - introspection?: DbIntrospection, + introspection?: DbIntrospection_Deserialize, properties?: DbProperty[], /** Snowflake settings (`None`: not a Snowflake data source, or all defaults). */ snowflake?: DbSnowflake | null, @@ -4449,7 +4450,7 @@ export type DataSource_Serialize = { sslCertFile: string, sslKeyFile: string, options: DbOptions, - introspection: DbIntrospection, + introspection: DbIntrospection_Serialize, properties: DbProperty[], /** Snowflake settings (`None`: not a Snowflake data source, or all defaults). */ snowflake: DbSnowflake | null, @@ -4609,11 +4610,16 @@ export type DbIndexInfo = { }; /** Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`. */ -export type DbIntrospection = { +export type DbIntrospection = DbIntrospection_Serialize | DbIntrospection_Deserialize; + +/** Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`. */ +export type DbIntrospection_Deserialize = { allDatabases?: boolean, databases?: string[], allSchemas?: boolean, schemas?: string[], + /** A database can replace the source's schema rules with all schemas or a list of exact names. */ + schemasByDatabase?: { [key in string]: DbSchemaSelection }, /** `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…). */ showSystem?: boolean, /** PostgreSQL template databases (`template0`, `template1`). */ @@ -4625,6 +4631,25 @@ export type DbIntrospection = { objectFilter?: string, }; +/** Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`. */ +export type DbIntrospection_Serialize = { + allDatabases: boolean, + databases: string[], + allSchemas: boolean, + schemas: string[], + /** A database can replace the source's schema rules with all schemas or a list of exact names. */ + schemasByDatabase?: { [key in string]: DbSchemaSelection }, + /** `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…). */ + showSystem: boolean, + /** PostgreSQL template databases (`template0`, `template1`). */ + showTemplates: boolean, + /** + * Object filter: the tree lists only tables, views, routines and sequences matching + * one of these patterns (`*`, `?`; separated by commas or spaces). Empty: all. + */ + objectFilter: string, +}; + export type DbJdbcDriver = DbJdbcDriver_Serialize | DbJdbcDriver_Deserialize; export type DbJdbcDriver_Deserialize = { @@ -4817,6 +4842,11 @@ export type DbSchemaObjects = { others?: DbSchemaObject[], }; +export type DbSchemaSelection = { + all?: boolean, + names?: string[], +}; + export type DbSequenceInfo = { name: string, dataType: string, @@ -4954,6 +4984,8 @@ export type DbTriggerInfo = { /** Transaction control of the data source's consoles. */ export type DbTxMode = "auto" | "manual"; +export type DbVisibilityChange = { kind: "databases"; selection: DbSchemaSelection } | { kind: "schemas"; selection: DbSchemaSelection } | { kind: "databaseSchemas"; database: string; selection: DbSchemaSelection | null }; + /** What a session's adapter supports, for enabling actions. */ export type DebugCapabilities = { restartFrame: boolean, diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 773eb21ea..3b3636837 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -229,6 +229,52 @@ border: 1px solid var(--border); border-radius: var(--radius-small); } +.introspectionTrigger { + display: inline-flex; + flex: none; +} +.introspectionCount { + display: inline-flex; + align-items: center; + padding: 0 var(--space-1); + background: transparent; + color: var(--fg-secondary); + border: 1px solid var(--border); + border-radius: var(--radius-small); + font: inherit; + font-size: var(--fs-small); + line-height: 16px; +} +.introspectionCount:hover, +.introspectionCount:focus-visible, +.introspectionCount[aria-expanded="true"] { + color: var(--fg-strong); + border-color: var(--accent); +} +.introspectionPopup { + display: flex; + flex-direction: column; + width: min(276px, calc(100vw - 24px)); + padding: var(--space-2); + gap: var(--space-2); +} +.introspectionModes, +.introspectionNames { + display: grid; + align-content: start; + gap: var(--space-1); +} +.introspectionNames { + max-height: min(220px, 40vh); + overflow: auto; + padding: var(--space-1); + border-block: 1px solid var(--border); +} +.introspectionActions { + display: flex; + justify-content: flex-end; + gap: var(--space-2); +} .textTool { flex: none; height: 20px; diff --git a/src/features/database/DatabaseView.tsx b/src/features/database/DatabaseView.tsx index a2ed72772..23390ce5d 100644 --- a/src/features/database/DatabaseView.tsx +++ b/src/features/database/DatabaseView.tsx @@ -24,6 +24,7 @@ import { T, } from "@/ui"; import { databaseKey, passesObjectFilter, shownNames, sourceIcon, splitTarget, targetOf } from "./model"; +import { IntrospectionPicker } from "./IntrospectionPicker"; import { nodeTarget, isOtherFolder, @@ -46,6 +47,7 @@ import { loadTables, openConsole, openObjectDdl, + saveSourceVisibility, tablesKey, useDatabase, type Loaded, @@ -53,7 +55,7 @@ import { import { DB_VIEW_FOCUS, databaseTree, openTableData } from "./treeActions"; import { newMenu, nodeMenu } from "./treeMenu"; import styles from "./Database.module.css"; -import { tx } from "@/platform/i18n"; +import { formatMessage, tx } from "@/platform/i18n"; import { databaseRequest } from "./requests"; const GROUP_LABELS: Record = { @@ -187,19 +189,31 @@ export function DatabaseView() { }; const sourceOf = (target: string) => st.sources.find((s) => s.id === splitTarget(target).id); - /** The Schemas tab's choice. */ - const shownSchemas = (target: string, names: string[]) => { + const schemaOverride = (target: string, database: string | null) => { + const overrides = sourceOf(target)?.introspection?.schemasByDatabase; + return database !== null && overrides && Object.hasOwn(overrides, database) ? overrides[database] : undefined; + }; + const defaultSchemas = (target: string, names: string[]) => { const i = sourceOf(target)?.introspection; return shownNames(names, i?.allSchemas, i?.schemas); }; + const exactNames = (available: string[], choice: readonly string[]) => { + const picked = new Set(choice); + return available.filter((name) => picked.has(name)); + }; + const shownSchemas = (target: string, names: string[], database: string | null) => { + const override = schemaOverride(target, database); + if (!override) return defaultSchemas(target, names); + return override.all ? names : exactNames(names, override.names ?? []); + }; const shownDatabases = (id: string, v: DbDatabases) => { const i = sourceOf(id)?.introspection; return shownNames(v.names, i?.allDatabases, i?.databases, v.current); }; - const schemasOf = (key: string, id: string) => + const schemasOf = (key: string, id: string, database: string | null) => status(key, st.schemas[id], (v) => - shownSchemas(id, v).map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node), + shownSchemas(id, v, database).map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node), ); const children = (n: Node): readonly Node[] | undefined => { @@ -216,10 +230,10 @@ export function DatabaseView() { current: name === v.current, })), ); - return schemasOf(n.key, id); + return schemasOf(n.key, id, null); } case "database": - return schemasOf(n.key, n.id); + return schemasOf(n.key, n.id, n.name); case "schema": return status(n.key, st.tables[tablesKey(n.id, n.schema)], () => folders @@ -341,6 +355,82 @@ export function DatabaseView() { else if (n.kind === "table") await loadDetails(n.id, n.schema, n.table.name); }; + const picker = (n: Node, lead: boolean) => { + if (n.kind !== "source" && n.kind !== "database") return null; + const source = n.kind === "source" ? n.source : sourceOf(n.id); + if (!source?.id || source.driver === "sqlite") return null; + 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 databases = listDatabases ? st.databases[sourceId] : undefined; + const schemas = listDatabases ? undefined : st.schemas[target]; + const intro = source.introspection; + const name = label(n); + const kind = + listDatabases || source.driver === "clickhouse" || source.vendor === "clickhouse" ? "databases" : "schemas"; + const title = kind === "databases" ? tx("Choose databases for {name}") : tx("Choose schemas for {name}"); + const override = schemaOverride(target, database); + const hasPattern = (value: string) => /[*?]/.test(value); + const protectedRules = database === null && (listDatabases ? intro?.databases : intro?.schemas)?.some(hasPattern); + const names = + databases?.status === "ok" + ? { + available: databases.value.names, + visible: shownDatabases(sourceId, databases.value), + current: databases.value.current, + restore: () => shownNames(databases.value.names, false, intro?.databases, databases.value.current), + } + : schemas?.status === "ok" + ? { + available: schemas.value, + visible: shownSchemas(target, schemas.value, database), + defaults: database === null ? undefined : defaultSchemas(target, schemas.value), + restore: () => + database === null + ? shownNames(schemas.value, false, intro?.schemas) + : override + ? exactNames(schemas.value, override.names ?? []) + : defaultSchemas(target, schemas.value), + } + : undefined; + const initial = + database !== null + ? override + ? { all: !!override.all, names: override.names ?? [] } + : null + : listDatabases + ? { all: intro?.allDatabases !== false, names: intro?.databases ?? [] } + : { all: intro?.allSchemas !== false, names: intro?.schemas ?? [] }; + const metadata = databases ?? schemas; + return ( + database !== null || (!protectedRules && !hasPattern(name))} + loadError={metadata?.status === "error" ? metadata.message : undefined} + onLoad={() => { + if (metadata?.status !== "loading") void load(n); + }} + onApply={async (selection) => { + const available = names?.available ?? []; + if (database !== null) { + await saveSourceVisibility(sourceId, available, { kind: "databaseSchemas", database, selection }); + } else if (selection) { + await saveSourceVisibility(sourceId, available, { + kind: listDatabases ? "databases" : "schemas", + selection, + }); + } + }} + /> + ); + }; + const expandable = (n: Node) => n.kind === "source" || n.kind === "database" || @@ -411,17 +501,10 @@ export function DatabaseView() { const detail = (n: Node): string | undefined => { switch (n.kind) { case "source": { + if (n.source.driver !== "sqlite") return undefined; const id = n.source.id ?? ""; - if (listsDatabases(n.source)) { - const d = st.databases[id]; - return d?.status === "ok" ? String(shownDatabases(id, d.value).length) : undefined; - } const s = st.schemas[id]; - return s?.status === "ok" ? String(shownSchemas(id, s.value).length) : undefined; - } - case "database": { - const s = st.schemas[n.id]; - return s?.status === "ok" ? String(shownSchemas(n.id, s.value).length) : undefined; + return s?.status === "ok" ? String(shownSchemas(id, s.value, null).length) : undefined; } case "folder": return String(folderSize(n.id, n.schema, n.folder)); @@ -528,7 +611,7 @@ export function DatabaseView() { renderNode={(n: Node, state) => { const i = icon(n); const d = detail(n); - const counted = n.kind === "source" || n.kind === "database" || n.kind === "folder" || n.kind === "group"; + const counted = n.kind === "source" || n.kind === "folder" || n.kind === "group"; const labelClass = n.kind === "message" && n.error ? styles.treeError @@ -554,6 +637,7 @@ export function DatabaseView() { {tx("global")} )} + {picker(n, state.lead)} {d && ( string[]; +} + +interface Props { + title: string; + kind: "databases" | "schemas"; + names: Names | undefined; + initial: Selection | null; + tabIndex: number; + protectedRules: boolean; + editableName: (name: string) => boolean; + loadError?: string; + onLoad: () => void; + onApply: (selection: Selection | null) => Promise; +} + +/** A database row can inherit its source's schema rules; source rows edit those rules directly. */ +export function IntrospectionPicker(props: Props) { + const { title, names, onLoad, loadError, tabIndex } = props; + const anchor = useRef(null); + const [open, setOpen] = useState(false); + const used = names?.visible.length ?? 0; + const total = names?.available.length ?? 0; + const close = () => setOpen(false); + return ( + e.stopPropagation()} + onDoubleClick={(e) => e.stopPropagation()} + onKeyDown={(e) => { + if (e.key !== "Escape" && e.key !== "Tab") e.stopPropagation(); + }} + > + + {open && } + + ); +} + +function PickerPopup({ + title, + kind, + names, + initial, + loadError, + onLoad, + onApply, + anchor, + onClose, + protectedRules, + editableName, +}: Props & { anchor: RefObject; onClose: () => void }) { + const [query, setQuery] = useState(""); + const [draft, setDraft] = useState(); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(); + const patternHint = useId(); + const selection = draft === undefined ? initial : draft; + const marked = new Set( + draft === undefined + ? names?.visible + : draft === null + ? names?.defaults + : draft.all + ? names?.available + : draft.names, + ); + if (names?.current) marked.add(names.current); + const filter = query.trim().toLocaleLowerCase(); + const matches = names?.available.filter((name) => name.toLocaleLowerCase().includes(filter)); + const apply = async () => { + if (saving) return; + if (draft === undefined) { + onClose(); + return; + } + try { + setSaving(true); + setSaveError(undefined); + await onApply(draft); + onClose(); + } catch (e) { + setSaveError(e instanceof Error ? e.message : String(e)); + setSaving(false); + } + }; + return ( + { + if (saving) return; + if (reason === "outside") void apply(); + else onClose(); + }} + > +
{ + if (e.key === "Enter" && e.target instanceof HTMLInputElement && !isImeKey(e.nativeEvent)) { + e.preventDefault(); + void apply(); + } + }} + > + {names ? ( + <> + setQuery(e.target.value)} + /> +
+ {names.defaults && ( + setDraft(inherit ? null : { all: false, names: [...marked] })} + /> + )} + setDraft({ all, names: all ? [] : names.restore() })} + /> +
+
+ {matches?.length ? ( + matches.map((name) => ( + + {name} + {name === names.current && ( + + {" "} + Current database + + )} + + } + checked={marked.has(name)} + disabled={saving || name === names.current || !editableName(name)} + onChange={(checked) => { + if (checked) marked.add(name); + else marked.delete(name); + setDraft({ all: false, names: names.available.filter((item) => marked.has(item)) }); + }} + /> + )) + ) : ( + + No matching names + + )} +
+ {protectedRules && ( + + Edit name patterns in Data Source Properties. + + )} + + ) : loadError ? ( +
+ {loadError} + +
+ ) : !saveError ? ( + + Loading… + + ) : null} + {saveError && {saveError}} + {names && ( + + Enter or click outside to apply + + )} +
+ + +
+
+
+ ); +} diff --git a/src/features/database/requestLifecycle.test.ts b/src/features/database/requestLifecycle.test.ts index 1a8db190b..1e93bc86c 100644 --- a/src/features/database/requestLifecycle.test.ts +++ b/src/features/database/requestLifecycle.test.ts @@ -642,6 +642,48 @@ describe("completion requests", () => { expect(backend.completion).toHaveBeenCalledTimes(2); }); + it("drops only the edited JDBC completion model when its schema rules change", async () => { + const jdbc: DataSource = { ...pg, driver: "jdbc", introspection: { allSchemas: false, schemas: ["APP_*"] } }; + savedSources = [jdbc, other]; + await loadSources(); + await loadSchemas("pg"); + await loadCompletion("pg"); + await loadCompletion("pg2"); + const schemas = useDatabase.getState().schemas; + + await saveSource({ ...jdbc, introspection: { allSchemas: false, schemas: ["REPORTS"] } }, undefined); + + const state = useDatabase.getState(); + expect(state.completion.pg).toBeUndefined(); + expect(state.completion.pg2).toEqual(completion); + expect(state.schemas).toBe(schemas); + expect(state.connected.has("pg")).toBe(true); + expect(backend.schemas).toHaveBeenCalledOnce(); + expect(backend.completion).toHaveBeenCalledTimes(2); + expect(await loadCompletion("pg")).toEqual(completion); + expect(backend.completion).toHaveBeenCalledTimes(3); + }); + + it("ignores an old JDBC completion response after its schema rules change", async () => { + const jdbc: DataSource = { ...pg, driver: "jdbc" }; + savedSources = [jdbc, other]; + await loadSources(); + const old = deferred(); + const fresh = deferred(); + backend.completion.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise); + const previous = loadCompletion("pg"); + + await saveSource({ ...jdbc, introspection: { allSchemas: false, schemas: ["APP"] } }, undefined); + const next = loadCompletion("pg"); + expect(next).not.toBe(previous); + old.resolve(ok({ ...completion, defaultSchema: "old" })); + expect(await previous).toBeNull(); + expect(useDatabase.getState().completion.pg).toBeUndefined(); + expect(loadCompletion("pg")).toBe(next); + fresh.resolve(ok(completion)); + expect(await next).toEqual(completion); + }); + it("lets completion recover after failure", async () => { backend.completion.mockRejectedValueOnce(new Error("not available")); expect(await loadCompletion("pg")).toBeNull(); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 4e84824c4..f205eb8a1 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -17,6 +17,7 @@ import { type DbCompletion, type DbDatabases, type DbDriver, + type DbIntrospection_Deserialize, type ExecutionEvent, type DbObjectKind, type DbPlanNode, @@ -25,6 +26,7 @@ import { type DbTableDetails, type DbTableInfo, type DbTableKind, + type DbVisibilityChange, type RequestId, type SqlStatement, } from "@/platform/ipc"; @@ -346,6 +348,30 @@ function sourceMutation(id: string): () => boolean { return () => project() && sourceMutations.get(id) === intent; } +/** The cached names come from the server before the visibility rules are applied. */ +function sourceMetadataKey(source: DataSource | undefined): string | undefined { + if (!source) return undefined; + const { introspection, ...connection } = source; + const metadata: DbIntrospection_Deserialize = { + ...introspection, + showSystem: !!introspection?.showSystem, + showTemplates: !!introspection?.showTemplates, + }; + delete metadata.allDatabases; + delete metadata.databases; + delete metadata.allSchemas; + delete metadata.schemas; + delete metadata.schemasByDatabase; + delete metadata.objectFilter; + return JSON.stringify([connection, metadata]); +} + +function jdbcSchemaRuleKey(source: DataSource): string | undefined { + const rules = source.introspection; + if (rules?.allSchemas !== false) return undefined; + return JSON.stringify([...new Set(rules.schemas?.map((pattern) => pattern.trim()).filter(Boolean))].sort()); +} + export async function loadSources(): Promise { // Closing the project resets `loaded` while its SQL consoles are still mounted. if (!useProject.getState().project) return; @@ -356,8 +382,20 @@ export async function loadSources(): Promise { try { const [sources, connected] = await Promise.all([call(commands.dbSources()), call(commands.dbConnected())]); if (request !== sourcesRequest || !current()) return; + const staleCompletionSources = new Set(); for (const old of useDatabase.getState().sources) { - if (JSON.stringify(old) !== JSON.stringify(sources.find((s) => s.id === old.id))) forget(old.id ?? ""); + const next = sources.find((s) => s.id === old.id); + const id = old.id ?? ""; + if (sourceMetadataKey(old) !== sourceMetadataKey(next)) forget(id); + else if (old.driver === "jdbc" && next && jdbcSchemaRuleKey(old) !== jdbcSchemaRuleKey(next)) { + staleCompletionSources.add(id); + } + } + if (staleCompletionSources.size) { + // JDBC completion uses the source's schema rules. Raw names and live sessions do not. + for (const target of completionLoads.keys()) { + if (staleCompletionSources.has(splitTarget(target).id)) completionLoads.delete(target); + } } useDatabase.setState((s) => { const server = new Set(connected); @@ -370,7 +408,12 @@ export async function loadSources(): Promise { sourceIntents.get(sourceId) !== sourceConnectionIntents.get(sourceId); return changed ? s.connected.has(target) : server.has(target); }); - return { sources, connected: new Set(live), loaded: true }; + const completion = staleCompletionSources.size + ? Object.fromEntries( + Object.entries(s.completion).filter(([target]) => !staleCompletionSources.has(splitTarget(target).id)), + ) + : s.completion; + return { sources, connected: new Set(live), completion, loaded: true }; }); } catch (e) { if (request !== sourcesRequest || !current()) return; @@ -410,11 +453,15 @@ export async function saveSource( ): Promise { const id = source.id ?? ""; const st = useDatabase.getState(); + const preserve = + password === undefined && + sshSecret === undefined && + sourceMetadataKey(st.sources.find((s) => s.id === id)) === sourceMetadataKey(source); const loaded = id in st.databases || Object.keys(st.schemas).some((t) => splitTarget(t).id === id); // Taken before anything is forgotten: what the tree had expanded under this source. - const levels = loadedLevels(id); + const levels = !preserve && loaded ? loadedLevels(id) : undefined; const connection = connectionIntents.get(id); - forget(id); + if (!preserve) forget(id); const current = sourceMutation(id); const sources = useDatabase.getState().sources; const next = sources.some((s) => s.id === source.id) @@ -431,7 +478,21 @@ export async function saveSource( // expanded nodes don't stay on Loading. await loadSources(); if (!current() || !sourceById(id)) return; - if (loaded && connectionIntents.get(id) === connection) await refresh(id, levels); + if (levels && connectionIntents.get(id) === connection) await refresh(id, levels); +} + +export async function saveSourceVisibility(id: string, available: string[], change: DbVisibilityChange): Promise { + const current = projectRequest(); + try { + await call(commands.dbSaveSourceVisibility(id, available, change)); + } catch (e) { + // This command is deliberately separate: older hosts reject it before writing or disconnecting. + if (message(e).includes("command db_save_source_visibility is not available remotely")) { + throw new Error(tx("Update the remote OpenIDEA server to edit visibility from the tree."), { cause: e }); + } + throw e; + } + if (current()) await loadSources(); } /** Copy/Paste › Duplicate: a copy of data source `id` named ` [2]` (its password is not copied). */ @@ -909,7 +970,7 @@ export function loadCompletion(id: string): Promise { const current = databaseRequest(id); const promise = call(commands.dbCompletion(id)) .then((model) => { - if (!current()) return null; + if (!current() || completionLoads.get(id)?.promise !== promise) return null; useDatabase.setState((s) => ({ completion: { ...s.completion, [id]: model } })); return model; }) diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 584cba0dc..67ddf3155 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2593,6 +2593,17 @@ "{route} in {took}": "{route} in {took}", "{program} stopped after {took}": "{program} stopped after {took}", "All databases": "All databases", + "Choose databases for {name}": "Choose databases for {name}", + "Choose schemas for {name}": "Choose schemas for {name}", + "{used} of {total}": "{used} of {total}", + "Use source settings": "Use source settings", + "Filter names": "Filter names", + "No matching names": "No matching names", + "Current database": "Current database", + "Enter or click outside to apply": "Enter or click outside to apply", + "Edit name patterns in Data Source Properties.": "Edit name patterns in Data Source Properties.", + "Update the remote OpenIDEA server to edit visibility from the tree.": "Update the remote OpenIDEA server to edit visibility from the tree.", + "Retry": "Retry", "Choose File…": "Choose File…", "Choose Directory Archive…": "Choose Directory Archive…", "This is a MySQL dump: restore it into a MySQL data source.": "This is a MySQL dump: restore it into a MySQL data source.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 0020f9f44..ba87085de 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3438,7 +3438,7 @@ "with NO BOM": "不带 BOM", "with statement": "with 语句", "{count} rows exported": "已导出 {count} 行", - "{index} of {total}": "第 {index} 个,共 {total} 个", + "{index} of {total}": "{index} / {total}", "{name} failed": "{name}失败", "{name} has unsaved changes": "{name} 有未保存的更改", "{name} installed": "{name} 已安装", @@ -4997,6 +4997,15 @@ "{label} (seconds)": "{label}(秒)", "Succeeded: {version}": "成功:{version}", "All databases": "全部数据库", + "Choose databases for {name}": "选择 {name} 的数据库", + "Choose schemas for {name}": "选择 {name} 的架构", + "Use source settings": "使用数据源设置", + "Filter names": "筛选名称", + "No matching names": "没有匹配的名称", + "Current database": "当前数据库", + "Enter or click outside to apply": "按 Enter 或点击列表外部以应用", + "Edit name patterns in Data Source Properties.": "在数据源属性中编辑名称模式。", + "Update the remote OpenIDEA server to edit visibility from the tree.": "请更新远程 OpenIDEA 服务器以在树中编辑可见范围。", "Add databases pattern": "添加数据库模式", "All schemas (databases)": "全部架构(数据库)", "All schemas": "全部架构", diff --git a/src/ui/Popup.tsx b/src/ui/Popup.tsx index e6a4d38b1..a548e175e 100644 --- a/src/ui/Popup.tsx +++ b/src/ui/Popup.tsx @@ -56,6 +56,7 @@ export interface PopupProps { style?: CSSProperties; role?: string; "aria-label"?: string; + "aria-describedby"?: string; /** Keep Tab inside the popup. */ trapFocus?: boolean; /** Focus on open: `true` = first `[data-autofocus]`/focusable/the popup itself; `false` = leave focus. */ @@ -290,6 +291,7 @@ function PopupInner({ data-popup="" role={role} aria-label={aria["aria-label"]} + aria-describedby={aria["aria-describedby"]} tabIndex={-1} className={clsx(styles.popup, centered && styles.centered, !unstyled && styles.surface, className)} data-positioned={centered || isPositioned || undefined}