Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

fix(query): per-engine EXPLAIN syntax, fixes #49

Tobi4489e96616d1
diff --git a/macos/Core/Extensions/DatabaseType+Explain.swift b/macos/Core/Extensions/DatabaseType+Explain.swift
new file mode 100644
index 0000000..af658df
--- /dev/null
+++ b/macos/Core/Extensions/DatabaseType+Explain.swift
@@ -0,0 +1,35 @@
+// DatabaseType+Explain.swift
+// Gridex
+//
+// Per-engine EXPLAIN syntax. PostgreSQL/MySQL/SQLite/MSSQL/ClickHouse all
+// disagree on the keyword and the option-list shape; MongoDB and Redis don't
+// have a SQL EXPLAIN at all. Centralising here so the query editor button,
+// the MCP `explain_query` tool, and any future caller don't drift apart.
+
+import Foundation
+
+extension DatabaseType {
+ /// Build the database-specific EXPLAIN SQL for `sql`. Returns nil when the
+ /// engine has no SQL EXPLAIN (Mongo, Redis) or when `sql` is blank.
+ func explainSQL(for sql: String) -> String? {
+ let trimmed = sql.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+
+ switch self {
+ case .postgresql:
+ // ANALYZE=false → planner output without executing the query.
+ return "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) \(trimmed)"
+ case .mysql:
+ return "EXPLAIN \(trimmed)"
+ case .sqlite:
+ return "EXPLAIN QUERY PLAN \(trimmed)"
+ case .mssql:
+ // SET-toggled showplan; statements between the toggles return plan rows.
+ return "SET SHOWPLAN_TEXT ON; \(trimmed); SET SHOWPLAN_TEXT OFF"
+ case .clickhouse:
+ return "EXPLAIN \(trimmed)"
+ case .mongodb, .redis:
+ return nil
+ }
+ }
+}
diff --git a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
index 1718e54..2c7b961 100644
--- a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
+++ b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
@@ -374,7 +374,11 @@ struct QueryEditorView: View {
isExecuting = true
errorMessage = nil
- let explainSQL = "EXPLAIN QUERY PLAN \(sql)"
+ guard let explainSQL = adapter.databaseType.explainSQL(for: sql) else {
+ errorMessage = "EXPLAIN is not supported for \(adapter.databaseType.displayName) connections."
+ isExecuting = false
+ return
+ }
Task {
let start = Date()
do {
diff --git a/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift b/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
index c10cf77..cd120e0 100644
--- a/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
+++ b/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
@@ -39,21 +39,7 @@ struct ExplainQueryTool: MCPTool {
let (adapter, config) = try await context.getAdapter(for: connectionId)
- // Build EXPLAIN query based on database type
- let explainSQL: String
- switch config.databaseType {
- case .postgresql:
- explainSQL = "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) \(sql)"
- case .mysql:
- explainSQL = "EXPLAIN \(sql)"
- case .sqlite:
- explainSQL = "EXPLAIN QUERY PLAN \(sql)"
- case .mssql:
- // SQL Server uses SET SHOWPLAN_TEXT or estimated plan
- explainSQL = "SET SHOWPLAN_TEXT ON; \(sql); SET SHOWPLAN_TEXT OFF"
- case .clickhouse:
- explainSQL = "EXPLAIN \(sql)"
- case .mongodb, .redis:
+ guard let explainSQL = config.databaseType.explainSQL(for: sql) else {
return MCPToolResult(text: "EXPLAIN is not supported for \(config.databaseType.displayName) connections.", isError: true)
}
diff --git a/macos/Tests/GridexTests/DatabaseTypeExplainTests.swift b/macos/Tests/GridexTests/DatabaseTypeExplainTests.swift
new file mode 100644
index 0000000..1f1a2f8
--- /dev/null
+++ b/macos/Tests/GridexTests/DatabaseTypeExplainTests.swift
@@ -0,0 +1,72 @@
+// DatabaseTypeExplainTests.swift — pure-logic checks for DatabaseType.explainSQL.
+// No infra needed. Locks the per-engine SQL shape so the QueryEditor button
+// and the MCP explain_query tool can't drift from each other again
+// (regression for issue #49: hardcoded "EXPLAIN QUERY PLAN" on Postgres).
+
+import XCTest
+@testable import Gridex
+
+final class DatabaseTypeExplainTests: XCTestCase {
+
+ private let sql = "SELECT * FROM profile"
+
+ func test_postgres_uses_optionListExplain_notQueryPlan() {
+ let out = DatabaseType.postgresql.explainSQL(for: sql)
+ XCTAssertEqual(out, "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) \(sql)")
+ // Issue #49 receipt: PG must NEVER receive SQLite-style "EXPLAIN QUERY PLAN".
+ XCTAssertFalse(out?.uppercased().contains("QUERY PLAN") ?? true,
+ "PG EXPLAIN must not contain 'QUERY PLAN' (SQLite-only syntax)")
+ }
+
+ func test_mysql_usesPlainExplain() {
+ XCTAssertEqual(DatabaseType.mysql.explainSQL(for: sql), "EXPLAIN \(sql)")
+ }
+
+ func test_sqlite_usesQueryPlan() {
+ XCTAssertEqual(DatabaseType.sqlite.explainSQL(for: sql), "EXPLAIN QUERY PLAN \(sql)")
+ }
+
+ func test_mssql_usesShowplanToggle() {
+ XCTAssertEqual(DatabaseType.mssql.explainSQL(for: sql),
+ "SET SHOWPLAN_TEXT ON; \(sql); SET SHOWPLAN_TEXT OFF")
+ }
+
+ func test_clickhouse_usesPlainExplain() {
+ XCTAssertEqual(DatabaseType.clickhouse.explainSQL(for: sql), "EXPLAIN \(sql)")
+ }
+
+ func test_mongo_returnsNil() {
+ XCTAssertNil(DatabaseType.mongodb.explainSQL(for: sql),
+ "Mongo has no SQL EXPLAIN; must return nil so callers show the right error")
+ }
+
+ func test_redis_returnsNil() {
+ XCTAssertNil(DatabaseType.redis.explainSQL(for: sql))
+ }
+
+ func test_blankSQL_returnsNil_acrossAllEngines() {
+ for engine in DatabaseType.allCases {
+ XCTAssertNil(engine.explainSQL(for: ""), "\(engine): empty input")
+ XCTAssertNil(engine.explainSQL(for: " \n\t "), "\(engine): whitespace-only input")
+ }
+ }
+
+ func test_trimsLeadingTrailingWhitespace() {
+ let padded = " \n SELECT 1 \n "
+ XCTAssertEqual(DatabaseType.postgresql.explainSQL(for: padded),
+ "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) SELECT 1")
+ }
+
+ func test_allEnginesHandled_noUnknownCase() {
+ // Belt-and-braces: if a future engine is added to DatabaseType, this loop
+ // forces a decision (return SQL or return nil with a comment).
+ for engine in DatabaseType.allCases {
+ switch engine {
+ case .mongodb, .redis:
+ XCTAssertNil(engine.explainSQL(for: sql))
+ case .postgresql, .mysql, .sqlite, .mssql, .clickhouse:
+ XCTAssertNotNil(engine.explainSQL(for: sql))
+ }
+ }
+ }
+}
diff --git a/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift b/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift
index 9284ce0..2a665bb 100644
--- a/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift
+++ b/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift
@@ -306,4 +306,44 @@ final class PostgreSQLAdapterIntegrationTests: XCTestCase {
_ = try? await adapter.executeRaw(sql: "DROP TABLE IF EXISTS \(plain)")
try await adapter.disconnect()
}
+
+ // MARK: - Issue #49 — Explain button server-side regression
+
+ // The query editor button used to send "EXPLAIN QUERY PLAN <sql>" to every
+ // engine — that's SQLite syntax, Postgres rejects it with SQLSTATE 42601
+ // ("syntax error at or near \"QUERY\""). After the fix, the editor goes
+ // through DatabaseType.explainSQL(for:) which emits the engine-correct form.
+ // This test asserts the PG-specific shape actually parses and executes.
+ func test_explainSQL_postgresShape_runsWithoutSyntaxError() async throws {
+ try skipIfNoServer(port: 55434)
+
+ let cfg = makeBaseConfig(host: "127.0.0.1", port: 55434, sslMode: .disabled)
+ let adapter = PostgreSQLAdapter()
+ try await adapter.connect(config: cfg, password: nil)
+
+ // Make sure there's something to plan against.
+ let table = "gridex_explain_test_\(UUID().uuidString.prefix(8).lowercased())"
+ do {
+ _ = try await adapter.executeRaw(sql: "CREATE TABLE \(table) (id int)")
+
+ guard let explainSQL = DatabaseType.postgresql.explainSQL(for: "SELECT * FROM \(table)") else {
+ XCTFail("PG must produce a non-nil EXPLAIN string")
+ return
+ }
+ // The literal regression: the SQL we send must NOT be the SQLite
+ // form. (Belt-and-braces against a future contributor accidentally
+ // re-introducing the same hardcode.)
+ XCTAssertFalse(explainSQL.uppercased().contains("QUERY PLAN"))
+
+ let result = try await adapter.executeRaw(sql: explainSQL)
+ XCTAssertFalse(result.rows.isEmpty, "EXPLAIN must return at least one plan row")
+ } catch {
+ _ = try? await adapter.executeRaw(sql: "DROP TABLE IF EXISTS \(table)")
+ try? await adapter.disconnect()
+ throw error
+ }
+
+ _ = try? await adapter.executeRaw(sql: "DROP TABLE IF EXISTS \(table)")
+ try await adapter.disconnect()
+ }
}