diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index c7c3adda5f..fa072581f4 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -1775,9 +1775,24 @@ impl DbManager { schema: Option<&str>, console: Option>, ) -> IdeResult> { - let driver = self.pool(id).await?.driver(); - if driver == DbDriver::Jdbc { - return Err(IdeError::invalid("Custom JDBC execution plans are unsupported")); + let pool = self.pool(id).await?; + let driver = pool.driver(); + if let Pool::Jdbc(jdbc) = &*pool { + if self.source(id)?.vendor != "duckdb" || !jdbc.version.starts_with("DuckDB ") { + return Err(IdeError::invalid("Custom JDBC execution plans are unsupported")); + } + let sql = statement.trim().trim_end_matches(';'); + if sql.contains(';') { + // The driver can execute a whole script. Have DuckDB count its statements before prefixing EXPLAIN. + let literal = sql::quote_literal(driver, sql); + let check = format!("SELECT json_array_length(json_serialize_plan({literal}), '$.plans')"); + let result = self.run(id, &check, 0, 1, cancel, schema, console).await?; + if result.rows.first().and_then(|r| r.first()).and_then(Option::as_deref) != Some("1") { + return Err(IdeError::invalid("Choose one statement to explain")); + } + } + let result = self.run(id, &format!("EXPLAIN (FORMAT JSON) {sql}"), 0, 3, cancel, schema, console).await?; + return plan::duckdb(&result); } if driver == DbDriver::Oracle { // EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately. diff --git a/crates/ide-db/src/plan.rs b/crates/ide-db/src/plan.rs index f1560145f4..c41d474c72 100644 --- a/crates/ide-db/src/plan.rs +++ b/crates/ide-db/src/plan.rs @@ -90,6 +90,54 @@ fn prop(name: &str, value: impl Into) -> PlanProperty { PlanProperty { name: name.to_owned(), value: value.into() } } +fn json_property(name: &str, value: &Value) -> PlanProperty { + let as_text = |v: &Value| v.as_str().map_or_else(|| v.to_string(), str::to_owned); + let text = match value { + Value::Array(items) => items.iter().map(as_text).collect::>().join(", "), + other => as_text(other), + }; + prop(name, text) +} + +/// DuckDB's explain_output may request the physical plan, the optimized logical plan, or all three. +pub(crate) fn duckdb(result: &QueryResult) -> IdeResult> { + #[derive(Deserialize)] + struct Operator { + name: String, + #[serde(default)] + children: Vec, + #[serde(default)] + extra_info: serde_json::Map, + } + + fn append(node: Operator, parent: Option, out: &mut Vec) { + let index = out.len() as u32; + let properties = node.extra_info.iter().map(|(k, v)| json_property(k, v)).collect(); + let params = ["Table", "Conditions", "Filters", "Projections"] + .iter() + .find_map(|key| node.extra_info.get(*key).map(|v| json_property(key, v).value)) + .unwrap_or_default(); + out.push(PlanNode { parent, operation: node.name.trim().to_owned(), params, properties }); + for child in node.children { + append(child, Some(index), out); + } + } + + let json = ["physical_plan", "logical_opt", "logical_plan"] + .iter() + .find_map(|kind| { + result.rows.iter().find(|r| r.first().and_then(Option::as_deref) == Some(*kind))?.get(1)?.as_deref() + }) + .ok_or_else(|| IdeError::invalid("DuckDB returned no execution plan"))?; + let roots: Vec = + serde_json::from_str(json).map_err(|e| IdeError::invalid(format!("DuckDB plan: {e}")))?; + let mut out = Vec::new(); + for root in roots { + append(root, None, &mut out); + } + Ok(out) +} + /// SQLite rows: `id, parent, notused, detail` (`SCAN o`, `SEARCH c USING INTEGER PRIMARY KEY (rowid=?)`). fn sqlite(rows: &[Vec>]) -> Vec { let mut ids: Vec = Vec::new(); @@ -149,18 +197,7 @@ fn postgres(node: &Value, parent: Option, out: &mut Vec) { .into_iter() .flatten() .filter(|(k, _)| k.as_str() != "Plans") - .map(|(k, v)| { - let value = match v { - Value::String(s) => s.clone(), - Value::Array(a) => a - .iter() - .map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned)) - .collect::>() - .join(", "), - other => other.to_string(), - }; - prop(k, value) - }) + .map(|(k, v)| json_property(k, v)) .collect(); let me = out.len() as u32; out.push(PlanNode { parent, operation, params: params.join(" "), properties }); @@ -287,6 +324,25 @@ mod tests { } } + #[test] + fn duckdb_prefers_the_physical_plan_and_preserves_operator_details() { + let physical = r#"[{"name":"PROJECTION","extra_info":{"Projections":["a","b"]},"children":[{"name":"SEQ_SCAN ","extra_info":{"Table":"items"}}]}]"#; + let rows = result( + &["explain_key", "explain_value"], + vec![vec![Some("logical_opt"), Some("[]")], vec![Some("physical_plan"), Some(physical)]], + ); + let nodes = duckdb(&rows).unwrap(); + assert_eq!(nodes.len(), 2); + assert_eq!((nodes[0].parent, nodes[0].params.as_str()), (None, "a, b")); + assert_eq!( + (nodes[1].parent, nodes[1].operation.as_str(), nodes[1].params.as_str()), + (Some(0), "SEQ_SCAN", "items") + ); + assert_eq!(nodes[1].properties, [prop("Table", "items")]); + assert!(duckdb(&result(&[], vec![])).is_err()); + assert!(duckdb(&result(&[], vec![vec![Some("physical_plan"), Some("invalid")]])).is_err()); + } + #[test] fn explains_per_dialect() { assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 1"); diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs index 46c296f694..e0a7a52535 100644 --- a/crates/ide-db/tests/jdbc.rs +++ b/crates/ide-db/tests/jdbc.rs @@ -248,6 +248,21 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> { db.save_sources(vec![source.clone()]).await?; db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?; assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]); + let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id"; + let nodes = db.explain("test", join, &cancel, None).await?; + let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join"); + assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2); + assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id"))); + let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err(); + assert!(batch.message.contains("one statement")); + assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty()); + db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?; + assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty()); + db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?; + assert_eq!( + db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows, + [vec![Some("1".into())]] + ); db.disconnect("test").await; assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items")); db.disconnect("test").await; diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index b40181002c..282719832d 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -38,7 +38,7 @@ Add a named profile with the vendor's driver JAR, any dependency JARs, the fully When switching to JDBC, configure TLS and driver-specific settings in the JDBC URL or **Advanced** properties. If the built-in source used an SSH tunnel, configure an equivalent route for the JDBC connection. JDBC uses auto-commit. Review the built-in startup script, default schema, and time zone, and configure equivalent settings supported by your JDBC driver or database. For enforced read-only access, use a database account with read-only privileges. Enter a separate JDBC password when converting a Snowflake source that used key pair, token, or browser authentication and your JDBC driver needs a password. -Select the profile, enter the vendor's JDBC URL, and use the **User**, **Password**, and **Advanced** fields for credentials and driver properties. The URL and Advanced properties are stored in the data source configuration. Put credentials in the password field to use the existing OS credential store. On Linux, saving a password requires a running Secret Service. You can also enter the password for the current session. The **Read-only** option asks the JDBC driver for a read-only connection. Use a database account with read-only privileges to enforce it. Cancelling a query keeps the session and its temporary tables when the driver stops the statement. If the driver does not respond within three seconds, OpenIDEA closes the session. A submitted statement can still finish on the server. **Test Connection** reports the database product and version. Schema, table and column browsing use JDBC metadata; the SQL console supports auto-commit queries and updates. Vendor-specific DDL, execution plans and table-grid writes are unavailable for custom drivers. +Select the profile, enter the vendor's JDBC URL, and use the **User**, **Password**, and **Advanced** fields for credentials and driver properties. The URL and Advanced properties are stored in the data source configuration. Put credentials in the password field to use the existing OS credential store. On Linux, saving a password requires a running Secret Service. You can also enter the password for the current session. The **Read-only** option asks the JDBC driver for a read-only connection. Use a database account with read-only privileges to enforce it. Cancelling a query keeps the session and its temporary tables when the driver stops the statement. If the driver does not respond within three seconds, OpenIDEA closes the session. A submitted statement can still finish on the server. **Test Connection** reports the database product and version. Schema, table and column browsing use JDBC metadata; the SQL console supports auto-commit queries and updates. Generic JDBC sources do not offer vendor-specific DDL, execution plans or table-grid writes. The DuckDB preset also supports **Explain Plan**. Each SQL console uses its own JDBC connection. Use the same console for statements that need its temporary tables or session settings. Other consoles can run queries while it is busy. OpenIDEA keeps the connection until you close the console and its result tabs. @@ -139,7 +139,7 @@ Each data source has a query console, a `.sql` file kept under `consoles/db` in The console toolbar has: - **Execute** (`⌘Enter` / `Ctrl+Enter`): runs the selected statements, or the statement at the caret. -- **Explain Plan**: shows the plan in a **Query Plan** tab. +- **Explain Plan**: shows the plan in a **Query Plan** tab. For a named DuckDB source, the tab shows DuckDB's operators, their inputs, and estimated row counts on the current connection. - **Cancel Running Statement**. Cancelling inside a manual transaction rolls it back. - **Browse Query History**: the last 500 statements per data source, with search and **Paste**. - A row limit (100 to 50,000; default 500). diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index 6361917dbe..dd099bb84f 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -38,7 +38,7 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行 切换到 JDBC 时,请在 JDBC URL 或 **高级** 属性中配置 TLS 和驱动专用设置。如果内置数据源使用了 SSH 隧道,请为 JDBC 连接配置等效的网络路径。JDBC 使用自动提交。请检查内置驱动的启动脚本、默认模式和时区,并通过 JDBC 驱动或数据库配置相应的设置。要强制限制为只读访问,请使用具备只读权限的数据库账号。如果原 Snowflake 数据源使用密钥对、令牌或浏览器认证,且 JDBC 驱动需要密码,请单独设置 JDBC 密码。 -选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。自定义驱动不支持厂商特有的 DDL、执行计划或表格编辑。 +选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。通用 JDBC 数据源不支持厂商特有的 DDL、执行计划或表格编辑。DuckDB 预设还支持**解释计划**。 每个 SQL 控制台使用独立的 JDBC 连接。依赖临时表或会话设置的语句应在同一控制台中执行,其他控制台可以同时运行查询。关闭控制台及其结果标签页后,OpenIDEA 会释放连接。 @@ -139,7 +139,7 @@ DuckDB 的各个控制台共享同一个数据库,包括内存数据库。SQLi 控制台工具栏: - **执行**(`⌘Enter` / `Ctrl+Enter`):执行选中的语句,没有选区时执行光标处的语句。 -- **解释计划**:在 **Query Plan** 标签页中显示执行计划。 +- **解释计划**:在 **Query Plan** 标签页中显示执行计划。对于 DuckDB 数据源,此标签页显示当前连接的运算符、输入和估计行数。 - **取消正在运行的语句**。在手动事务中取消会回滚该事务。 - **浏览查询历史记录**:每个数据源最近 500 条语句,可搜索并粘贴回控制台。 - 行数上限(100 到 50,000,默认 500)。 diff --git a/e2e/duckdbExplain.spec.ts b/e2e/duckdbExplain.spec.ts new file mode 100644 index 0000000000..b4b0473b0c --- /dev/null +++ b/e2e/duckdbExplain.spec.ts @@ -0,0 +1,50 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("opens a named DuckDB query plan without executing the statement", async ({ workbench: page }, info) => { + await stubDesktop(page); + await page.evaluate(async () => { + const database = "/src/features/database/store.ts"; + const workbench = "/src/workbench/contributions.ts"; + const { useDatabase, bindConsole } = await import(database); + const { editorService } = await import(workbench); + const path = "/dev/acme-api/orders.sql"; + useDatabase.setState({ + loaded: true, + sources: [{ id: "shop", name: "Shop · DuckDB", driver: "jdbc", vendor: "duckdb" }], + completion: { shop: { defaultSchema: "main", tables: [], foreignKeys: [] } }, + }); + bindConsole(path, "shop"); + Object.assign(window.__ipc.handlers, { + db_statements: ({ text }: { text: string }) => [{ text, from: 0, to: text.length }], + db_connected: () => ["shop"], + db_explain: () => [ + { + parent: null, + operation: "HASH_JOIN", + params: "customer_id = id", + properties: [{ name: "Join Type", value: "INNER" }], + }, + { parent: 0, operation: "SEQ_SCAN", params: "orders", properties: [{ name: "Table", value: "orders" }] }, + { parent: 0, operation: "SEQ_SCAN", params: "customers", properties: [{ name: "Table", value: "customers" }] }, + ], + }); + await editorService().openFile(path, { focus: true }); + }); + const editor = page.locator(".cm-editor:visible .cm-content[contenteditable=true]"); + await editor.click(); + await editor.press("Meta+A"); + await page.keyboard.insertText( + "SELECT orders.id, customers.name\nFROM orders\nJOIN customers ON orders.customer_id = customers.id;", + ); + const toolbar = page.getByRole("toolbar", { name: "Query Console" }); + await toolbar.getByRole("button", { name: "Explain Plan" }).click(); + const tree = page.getByRole("tree", { name: "Query plan" }); + await expect(tree).toContainText("HASH_JOIN"); + await tree.getByText("HASH_JOIN", { exact: true }).click(); + await expect(page.getByRole("table", { name: "Plan node properties" })).toContainText("INNER"); + await expect(tree).toContainText("customers"); + expect(await ipcCalls(page, "db_explain")).toHaveLength(1); + expect(await ipcCalls(page, "db_execute")).toHaveLength(0); + expect(await ipcCalls(page, "db_execute_stream")).toHaveLength(0); + await page.screenshot({ path: info.outputPath("duckdb-explain.png"), animations: "disabled" }); +}); diff --git a/src/features/database/console.tsx b/src/features/database/console.tsx index bdb58c87fb..beae3ccc13 100644 --- a/src/features/database/console.tsx +++ b/src/features/database/console.tsx @@ -67,6 +67,7 @@ import { schemaTreeRows, schemaTreeValue, sourceIcon, + supportsExplain, sourceLabel, splitTarget, targetOf, @@ -880,7 +881,9 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) { // SQL resolution scopes in the settings can move the console to another data source. useProject((s) => s.settings); const boundId = bound ? splitTarget(bound).id : null; - const driver = sources.find((s) => s.id === boundId)?.driver; + const source = sources.find((s) => s.id === boundId); + const canExplain = supportsExplain(source); + const driver = source?.driver; const jdbc = driver === "jdbc"; const supportsTransactions = driver !== "clickhouse" && !jdbc; const switchable = schemaSwitchable(driver); @@ -950,7 +953,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) { /> openHistory(path)} /> - {!jdbc && ( + {canExplain && ( void { icon: "db-plan", keywords: ["query plan", "explain", "sql"], when: `editorTextFocus && editorLangId == ${SQL_LANGUAGE}`, - enabled: () => sourceById(consoleSource(activeEditor()?.ctx.path ?? ""))?.driver !== "jdbc", + enabled: () => supportsExplain(sourceById(consoleSource(activeEditor()?.ctx.path ?? ""))), run: async () => { const current = projectRequest(); const e = activeEditor(); diff --git a/src/features/database/model.ts b/src/features/database/model.ts index 6ef0611030..2aed387ac3 100644 --- a/src/features/database/model.ts +++ b/src/features/database/model.ts @@ -180,6 +180,10 @@ export function fileSourceName(file: string): string { return base.replace(/\.[^.]+$/, "") || base; } +export function supportsExplain(source?: Pick | null): boolean { + return source?.driver !== "jdbc" || source.vendor === "duckdb"; +} + /** The tree / menu icon of a data source (IDEA shows the vendor's mark). */ export function sourceIcon(s: Pick): string { return vendorOf(s).icon; diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx index 3045a8c43b..9fddc30dc8 100644 --- a/src/features/database/results-view.test.tsx +++ b/src/features/database/results-view.test.tsx @@ -1353,6 +1353,18 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab } }); + it.each([ + ["duckdb", 1], + ["mysql", 0], + ["", 0], + ] as const)("requests a plan for JDBC vendor %s only when supported", async (vendor, calls) => { + useDatabase.setState({ sources: [{ id: "pg", name: "Local", driver: "jdbc", vendor }] }); + backend.explain.mockResolvedValue({ status: "ok", data: [] }); + await explainConsole("a.sql", "SELECT 1", 0, 0); + expect(backend.explain.mock.calls.map((call) => call[4])).toEqual(calls ? ["a.sql"] : []); + expect(useDatabase.getState().results).toHaveLength(calls); + }); + it("never replaces the Query Plan from a run, and appends a new plan beside a pinned one", async () => { backend.explain.mockResolvedValue({ status: "ok", data: [] }); await explainConsole("a.sql", "SELECT 1", 0, 0); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 334878a026..538b775107 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -55,6 +55,7 @@ import { idleTargets, newSourceId, sourceIcon, + supportsExplain, splitTarget, targetOf, } from "./model"; @@ -2204,7 +2205,7 @@ async function explain( /** Explain Plan: the plan of the statement at `from` (the first selected one) of console `path`. */ export async function explainConsole(path: string, text: string, from: number, to: number): Promise { const id = consoleSource(path); - if (!id || sourceById(id)?.driver === "jdbc") return; + if (!id || !supportsExplain(sourceById(id))) return; try { const [statement] = await consoleStatements(id, text, from, to); if (!statement) return;