diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index 6d352f917..f09388430 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -12,6 +12,7 @@ use ide_db::{ }; use serde::{Deserialize, Serialize}; use specta::Type; +use std::path::PathBuf; /// One statement of a console run. #[derive(Clone, Serialize, Deserialize, Type)] @@ -179,6 +180,7 @@ pub(crate) fn register(d: &mut Dispatcher) { apply_edits(&c.host, &c.window, &id, &schema, &table, edits).await }); d.add("db_console_path", |c| async move { console_path(&c.host, &c.arg::("id")?) }); + d.add("db_consoles", |c| async move { consoles(&c.host, &c.arg::("id")?, c.arg("create")?) }); } /// The data sources configured for the project (the tree's roots). @@ -472,11 +474,52 @@ pub async fn apply_edits( /// created on first use. Consoles are files of the project, so a remote /// window resolves it on the host the project runs on. pub fn console_path(host: &Host, id: &str) -> IdeResult { + let file = console_dir(host, id)?.join("console.sql"); + if !file.exists() { + std::fs::write(&file, "")?; + } + Ok(file.into()) +} + +/// The query consoles of data source `id`: the default `console.sql`, then +/// `console_1.sql`, `console_2.sql`… in order. `create` adds the next one first +/// (DataGrip's New › Query Console). +pub fn consoles(host: &Host, id: &str, create: bool) -> IdeResult> { + let dir = console_dir(host, id)?; + let default = dir.join("console.sql"); + let mut numbered: Vec<(u32, PathBuf)> = std::fs::read_dir(&dir)? + .filter_map(|e| { + let path = e.ok()?.path(); + let n = path.file_name()?.to_str()?.strip_prefix("console_")?.strip_suffix(".sql")?.parse().ok()?; + Some((n, path)) + }) + .collect(); + numbered.sort(); + if create { + // The default console comes first; once it exists, the next number. + if !default.exists() { + std::fs::write(&default, "")?; + } else { + let n = numbered.last().map_or(1, |(n, _)| n + 1); + let file = dir.join(format!("console_{n}.sql")); + std::fs::write(&file, "")?; + numbered.push((n, file)); + } + } + let mut out: Vec = Vec::new(); + if default.exists() { + out.push(default.into()); + } + out.extend(numbered.into_iter().map(|(_, p)| p.into())); + Ok(out) +} + +/// `/consoles/db/`: `` for the default database, `.` for the others. +fn console_dir(host: &Host, id: &str) -> IdeResult { let (source, database) = ide_db::split_target(id); if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { return Err(IdeError::invalid("invalid data source id")); } - // One console per database: `` for the default one, `.` for the others. let name = match database { Some(db) => { let safe: String = @@ -487,9 +530,5 @@ pub fn console_path(host: &Host, id: &str) -> IdeResult { }; let dir = host.data_dir.join("consoles").join("db").join(&name); std::fs::create_dir_all(&dir)?; - let file = dir.join("console.sql"); - if !file.exists() { - std::fs::write(&file, "")?; - } - Ok(file.into()) + Ok(dir) } diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index 309d72672..10ab2fbac 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -357,6 +357,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool { | "docker_set_registry_password" | "docker_run_env" | "db_console_path" + | "db_consoles" | "db_export_file" | "vcs_write_patch" | "app_metrics" diff --git a/crates/ide-host/tests/db_consoles.rs b/crates/ide-host/tests/db_consoles.rs new file mode 100644 index 000000000..e718d5a58 --- /dev/null +++ b/crates/ide-host/tests/db_consoles.rs @@ -0,0 +1,37 @@ +use ide_core::NullSink; +use ide_host::ops::db; +use ide_host::{Host, HostConfig}; +use std::sync::Arc; + +#[tokio::test] +async fn new_query_consoles_are_numbered_after_the_default_one() { + let tmp = tempfile::tempdir().unwrap(); + let base = tmp.path(); + let host = Arc::new(Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + let names = |paths: Vec| -> Vec { + paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect() + }; + assert!(db::consoles(&host, "pg", false).unwrap().is_empty()); + // The first new console is the default one, then console_1, console_2… + assert_eq!(names(db::consoles(&host, "pg", true).unwrap()), ["console.sql"]); + assert_eq!(names(db::consoles(&host, "pg", true).unwrap()), ["console.sql", "console_1.sql"]); + let all = db::consoles(&host, "pg", true).unwrap(); + assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]); + // Numbers sort numerically, and the default console path is the first one. + std::fs::write(all[0].0.with_file_name("console_10.sql"), "").unwrap(); + assert_eq!(names(db::consoles(&host, "pg", false).unwrap())[3], "console_10.sql"); + assert_eq!(db::console_path(&host, "pg").unwrap().0, all[0].0); + // Each database of a source has its own consoles. + assert!(db::consoles(&host, "pg:other", false).unwrap().is_empty()); + assert!(db::consoles(&host, "../x", true).is_err()); +} diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/rpc.rs index 989266844..c5ffc2e11 100644 --- a/crates/ide-host/tests/rpc.rs +++ b/crates/ide-host/tests/rpc.rs @@ -365,6 +365,7 @@ async fn local_deployment_runs_on_the_project_host() { "db_table_page", "db_apply_edits", "db_console_path", + "db_consoles", "ssh_test", "ssh_set_secret", "ssh_password_saved", diff --git a/crates/ide-host/tests/trust.rs b/crates/ide-host/tests/trust.rs index 087ccc903..bd8478c67 100644 --- a/crates/ide-host/tests/trust.rs +++ b/crates/ide-host/tests/trust.rs @@ -66,6 +66,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project( "docker_set_registry_password", "docker_run_env", "db_console_path", + "db_consoles", "db_export_file", "vcs_write_patch", "remote_bootstrap_list", diff --git a/src-tauri/src/commands/db.rs b/src-tauri/src/commands/db.rs index 563a38232..b499b7358 100644 --- a/src-tauri/src/commands/db.rs +++ b/src-tauri/src/commands/db.rs @@ -362,3 +362,10 @@ pub async fn db_apply_edits( pub fn db_console_path(state: State<'_, AppState>, id: String) -> IdeResult { ide_host::ops::db::console_path(&state.host, &id) } + +/// The query consoles of data source `id`; `create` adds the next one first. +#[tauri::command] +#[specta::specta] +pub fn db_consoles(state: State<'_, AppState>, id: String, create: bool) -> IdeResult> { + ide_host::ops::db::consoles(&state.host, &id, create) +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 7c5297e38..1fd5d7650 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -747,5 +747,6 @@ pub fn builder() -> tauri_specta::Builder { db::db_table_page, db::db_apply_edits, db::db_console_path, + db::db_consoles, ]) } diff --git a/src/bindings.ts b/src/bindings.ts index 602159c61..ba6bd0645 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1731,6 +1731,8 @@ export const commands = { dbTablePage: (request: RequestId, id: string, schema: string, table: string, filter: string | null, sort: DbSortKey[], offset: number, limit: number) => typedError(__TAURI_INVOKE("db_table_page", { request, id, schema, table, filter, sort, offset, limit })), dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })), dbConsolePath: (id: string) => typedError(__TAURI_INVOKE("db_console_path", { id })), + /** The query consoles of data source `id`; `create` adds the next one first. */ + dbConsoles: (id: string, create: boolean) => typedError(__TAURI_INVOKE("db_consoles", { id, create })), }; /* Types */ diff --git a/src/features/database/index.ts b/src/features/database/index.ts index 3c9833a6c..b7061bc47 100644 --- a/src/features/database/index.ts +++ b/src/features/database/index.ts @@ -38,6 +38,7 @@ import { loadDatabases, listsDatabases, sourceById, + newConsole, openConsole, openHistory, openSourceDialog, @@ -198,6 +199,24 @@ export function activate(): () => void { else toolWindowService().show(DB_TOOL_WINDOW, true); }, }, + { + id: "db.newConsole", + title: "New Query Console", + category: "Tools", + icon: "db-console", + keywords: ["database", "sql console"], + when: "projectOpen", + run: async ({ arg }) => { + const current = projectRequest(); + if (!useDatabase.getState().loaded) await loadSources(); + if (!current()) return; + const { sources, selectedSource } = useDatabase.getState(); + const node = arg && typeof arg === "object" && "kind" in arg ? nodeTarget(arg as DbNode) : null; + const id = node ?? selectedSource ?? (sources.length === 1 ? sources[0]!.id : null); + if (id) await newConsole(id); + else toolWindowService().show(DB_TOOL_WINDOW, true); + }, + }, { id: "db.execute", title: "Execute SQL Statement", diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 56a76b46e..3f77f627a 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -906,6 +906,29 @@ export async function openConsole(id: string): Promise { } } +/** The query console files of data source `id`: `console.sql`, then `console_1.sql`, `console_2.sql`… */ +export function consoleFiles(id: string): Promise { + return call(commands.dbConsoles(id, false)); +} + +/** Opens one of the query consoles of data source `id`. */ +export async function openConsoleFile(id: string, path: string): Promise { + bindConsole(path, id); + await editorService().openFile(path, { focus: true }); +} + +/** Creates and opens another query console of data source `id` (DataGrip's New › Query Console). */ +export async function newConsole(id: string): Promise { + try { + const before = new Set(await consoleFiles(id)); + const after = await call(commands.dbConsoles(id, true)); + const path = after.find((p) => !before.has(p)) ?? after[after.length - 1]; + if (path) await openConsoleFile(id, path); + } catch (e) { + notifications().notify({ level: "error", title: "Cannot open the query console", body: message(e) }); + } +} + let nextTab = 1; let nextRun = 1; let nextLine = 1; diff --git a/src/features/database/treeActions.ts b/src/features/database/treeActions.ts index 1ea39248c..57d750279 100644 --- a/src/features/database/treeActions.ts +++ b/src/features/database/treeActions.ts @@ -22,7 +22,10 @@ import { loadSchemas, loadSources, loadTables, + consoleFiles, + newConsole, openConsole, + openConsoleFile, openConsoleWith, openDdl, openObjectDdl, @@ -42,6 +45,7 @@ import { } from "./store"; import { tableInput } from "./tableInput"; import { tx } from "@/platform/i18n"; +import { chooseItem } from "@/workbench/inputDialogs"; import { databaseRequest } from "./requests"; /** Context key: the Database tree has focus. */ @@ -279,7 +283,7 @@ export function registerDatabaseTreeActions(): () => void { const id = n ? nodeTarget(n) : null; const { sources } = useDatabase.getState(); const target = id ?? (sources.length === 1 ? (sources[0]!.id ?? null) : null); - if (target) void openConsole(target); + if (target) void jumpToConsole(target); else toolWindowService().show(DB_TOOL_WINDOW, true); }, }), @@ -524,3 +528,14 @@ export function registerDatabaseTreeActions(): () => void { }), ]); } + +/** One console opens directly; with several, DataGrip's list of them plus New Query Console. */ +async function jumpToConsole(id: string): Promise { + const files = await consoleFiles(id).catch(() => []); + if (files.length <= 1) return openConsole(id); + const names = files.map((f) => (f.split(/[\\/]/).pop() ?? f).replace(/\.sql$/, "")); + const create = tx("New Query Console"); + const picked = await chooseItem({ title: "Query Consoles", items: [...names, create] }); + if (picked === create) await newConsole(id); + else if (picked) await openConsoleFile(id, files[names.indexOf(picked)]!); +} diff --git a/src/features/database/treeMenu.ts b/src/features/database/treeMenu.ts index 0a7ac9dd9..60de96297 100644 --- a/src/features/database/treeMenu.ts +++ b/src/features/database/treeMenu.ts @@ -66,7 +66,7 @@ async function sourceFromClipboard() { /** The toolbar's "+" menu (IDEA: New). */ export function newMenu(): MenuItem[] { - return [{ kind: "action", action: "db.openConsole", label: "Query Console" }, sep, ...dataSourceItems()]; + return [{ kind: "action", action: "db.newConsole", label: "Query Console" }, sep, ...dataSourceItems()]; } function sqlScripts(n: DbNode, table: boolean): MenuItem { @@ -88,7 +88,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] { const driver = sourceById(id)?.driver ?? "sqlite"; const o = objectOf(n); const t = tableOf(n); - const newConsole = act("db.openConsole", n, { label: "Query Console", icon: "db-console" }); + const newConsole = act("db.newConsole", n, { label: "Query Console", icon: "db-console" }); const refresh = act("db.refresh", n); const quickDoc = act("db.quickDoc", n); const rename = act("db.rename", n, { disabled: !(n.kind === "source" || (o && canRename(driver, o))) }); diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 37963974b..97a3b91d5 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2181,6 +2181,8 @@ "Python interpreter": "Python 解释器", "Python: only your code (justMyCode). JavaScript: skips node_modules and Node.js internals.": "Python:仅您的代码 (justMyCode)。JavaScript:跳过 node_modules 和 Node.js 内部代码。", "Query Console": "查询控制台", + "New Query Console": "新建查询控制台", + "Query Consoles": "查询控制台", "Quick Documentation": "快速文档", "Re-check installed tools": "重新检查已安装的工具", "Re-reads the effective POMs and dependency trees with Maven": "使用 Maven 重新读取有效 POM 和依赖树",