mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-16 17:54:53 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85ab17b710 |
No files matched your search
@@ -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::<String>("id")?) });
|
||||
d.add("db_consoles", |c| async move { consoles(&c.host, &c.arg::<String>("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<IpcPath> {
|
||||
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<Vec<IpcPath>> {
|
||||
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<IpcPath> = Vec::new();
|
||||
if default.exists() {
|
||||
out.push(default.into());
|
||||
}
|
||||
out.extend(numbered.into_iter().map(|(_, p)| p.into()));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
|
||||
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
|
||||
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: `<id>` for the default one, `<id>.<database>` 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<IpcPath> {
|
||||
};
|
||||
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)
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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<ide_core::IpcPath>| -> Vec<String> {
|
||||
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());
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -362,3 +362,10 @@ pub async fn db_apply_edits(
|
||||
pub fn db_console_path(state: State<'_, AppState>, id: String) -> IdeResult<IpcPath> {
|
||||
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<Vec<IpcPath>> {
|
||||
ide_host::ops::db::consoles(&state.host, &id, create)
|
||||
}
|
||||
@@ -747,5 +747,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
db::db_table_page,
|
||||
db::db_apply_edits,
|
||||
db::db_console_path,
|
||||
db::db_consoles,
|
||||
])
|
||||
}
|
||||
@@ -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<DbTablePage, IdeError>(__TAURI_INVOKE("db_table_page", { request, id, schema, table, filter, sort, offset, limit })),
|
||||
dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError<number | null, IdeError>(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })),
|
||||
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__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<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
|
||||
};
|
||||
|
||||
/* Types */
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -906,6 +906,29 @@ export async function openConsole(id: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** The query console files of data source `id`: `console.sql`, then `console_1.sql`, `console_2.sql`… */
|
||||
export function consoleFiles(id: string): Promise<string[]> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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;
|
||||
|
||||
@@ -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<void> {
|
||||
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)]!);
|
||||
}
|
||||
@@ -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))) });
|
||||
|
||||
@@ -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 和依赖树",
|
||||
|
||||
Reference in new issue
Block a user