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++
feat(query): pgAdmin4-style EXPLAIN options dropdown
Tobif253a52d659e
diff --git a/macos/Core/Extensions/DatabaseType+Explain.swift b/macos/Core/Extensions/DatabaseType+Explain.swiftindex af658df..49b26d6 100644--- a/macos/Core/Extensions/DatabaseType+Explain.swift+++ b/macos/Core/Extensions/DatabaseType+Explain.swift@@ -11,14 +11,21 @@ import Foundationextension 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? {+ ///+ /// `options` shapes the PG `EXPLAIN (...)` option list. Other engines have+ /// no per-option syntax, so the flags are ignored and we return their+ /// plain `EXPLAIN` form.+ ///+ /// The default value preserves the previous hardcoded behaviour+ /// (`EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) ...`), so legacy+ /// call sites stay byte-compatible.+ func explainSQL(for sql: String, options: ExplainOptions = .default) -> 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)"+ return Self.buildPostgresExplain(sql: trimmed, options: options.sanitized())case .mysql:return "EXPLAIN \(trimmed)"case .sqlite:@@ -32,4 +39,36 @@ extension DatabaseType {return nil}}++ // MARK: - Postgres option-list builder++ /// Produce `EXPLAIN (FOO true, BAR false, FORMAT JSON, ...) <sql>`.+ /// ANALYZE / COSTS / FORMAT are always emitted (matches the legacy default+ /// + makes the planner output reproducible regardless of server-side+ /// defaults). Boolean toggles only appear when on. SERIALIZE only appears+ /// when not `.off`.+ private static func buildPostgresExplain(sql: String, options: ExplainOptions) -> String {+ var parts: [String] = [+ "ANALYZE \(options.analyze)",+ "COSTS \(options.costs)",+ ]++ if options.buffers { parts.append("BUFFERS true") }+ if options.genericPlan { parts.append("GENERIC_PLAN true") }+ if options.memory { parts.append("MEMORY true") }+ if options.settings { parts.append("SETTINGS true") }+ if options.summary { parts.append("SUMMARY true") }+ if options.timing { parts.append("TIMING true") }+ if options.verbose { parts.append("VERBOSE true") }+ if options.wal { parts.append("WAL true") }++ if options.serialize != .off {+ parts.append("SERIALIZE \(options.serialize.rawValue)")+ }++ // FORMAT always last per PG convention (purely cosmetic; server doesn't care).+ parts.append("FORMAT \(options.format.rawValue)")++ return "EXPLAIN (\(parts.joined(separator: ", "))) \(sql)"+ }}diff --git a/macos/Core/Models/Query/ExplainOptions.swift b/macos/Core/Models/Query/ExplainOptions.swiftnew file mode 100644index 0000000..f75d31f--- /dev/null+++ b/macos/Core/Models/Query/ExplainOptions.swift@@ -0,0 +1,179 @@+// ExplainOptions.swift+// Gridex+//+// User-toggleable EXPLAIN options. Currently shaped for PostgreSQL — the only+// engine with a rich option list (`EXPLAIN (FOO true, BAR false, ...)`).+// MySQL / SQL Server / SQLite / ClickHouse have no per-option syntax, so the+// builder ignores the flags for those engines and returns the engine's plain+// `EXPLAIN` form.+//+// Cross-disable rules and version gating live here so the UI and the SQL+// builder share a single source of truth — a future toolbar that doesn't+// honour the rules can't accidentally produce a server-rejected query.++import Foundation++struct ExplainOptions: Equatable, Codable, Sendable {++ // MARK: - PG flag toggles++ /// Execute the query (modifies data!) and report actual times.+ /// Off → planner output only, no side effects.+ var analyze: Bool = false++ /// Buffer-pool usage statistics.+ /// PG 9.0+, before PG 13 only meaningful with ANALYZE.+ var buffers: Bool = false++ /// Show estimated planner costs. Default ON in PG.+ var costs: Bool = true++ /// Show plan for a prepared statement with generic parameter values.+ /// PG 16+.+ var genericPlan: Bool = false++ /// Per-node memory usage during planning.+ /// PG 17+.+ var memory: Bool = false++ /// Modified non-default GUC settings used to plan the query.+ /// PG 12+.+ var settings: Bool = false++ /// Summary information (planning + execution time).+ /// Default ON when ANALYZE is set.+ var summary: Bool = false++ /// Per-node actual time output.+ /// Requires ANALYZE.+ var timing: Bool = false++ /// More-detailed per-node output (output columns, schema-qualified names).+ var verbose: Bool = false++ /// Per-node WAL usage.+ /// PG 13+, requires ANALYZE.+ var wal: Bool = false++ // MARK: - Multi-value enums++ enum Format: String, Codable, Sendable, CaseIterable, Identifiable {+ case text = "TEXT"+ case json = "JSON"+ case yaml = "YAML"+ case xml = "XML"++ var id: String { rawValue }+ var displayName: String { rawValue.capitalized }+ }++ enum Serialize: String, Codable, Sendable, CaseIterable, Identifiable {+ case off = "OFF" // do not include SERIALIZE in the option list+ case none = "NONE"+ case text = "TEXT"+ case binary = "BINARY"++ var id: String { rawValue }+ var displayName: String {+ self == .off ? "Off" : rawValue.capitalized+ }+ }++ /// Output format. PG default is TEXT.+ var format: Format = .text++ /// SERIALIZE option (PG 17+, requires ANALYZE).+ /// `.off` means don't include the option at all.+ var serialize: Serialize = .off++ // MARK: - Defaults++ /// Matches the legacy hard-coded `EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT)`+ /// — used when callers don't pass options.+ static let `default` = ExplainOptions()+}++// MARK: - Cross-disable rules++extension ExplainOptions {+ /// PG enforces these constraints server-side; surfacing them in the model+ /// lets the UI grey out impossible combinations before sending the query.++ /// Options that are valid only when `analyze == true`.+ /// Server rejects them with `EXPLAIN option X requires ANALYZE` otherwise.+ enum AnalyzeDependency: CaseIterable {+ case timing, wal, serialize+ }++ /// True when the toggle for `dep` should be enabled in the UI given the+ /// current `analyze` setting.+ func canEnable(_ dep: AnalyzeDependency) -> Bool {+ analyze+ }++ /// Apply cross-disable rules — call before sending. Force-clears any+ /// option that is invalid given the current settings.+ func sanitized() -> ExplainOptions {+ var copy = self+ if !copy.analyze {+ copy.timing = false+ copy.wal = false+ copy.serialize = .off+ }+ return copy+ }+}++// MARK: - Version gating++extension ExplainOptions {+ /// Each option is keyed to the minimum PG major version on which it+ /// becomes available. Older servers reject the option as a syntax error.+ enum VersionGated: Hashable, CaseIterable {+ case settings // PG 12++ case wal // PG 13++ case genericPlan // PG 16++ case memory // PG 17++ case serialize // PG 17+++ var minPostgresMajor: Int {+ switch self {+ case .settings: return 12+ case .wal: return 13+ case .genericPlan: return 16+ case .memory: return 17+ case .serialize: return 17+ }+ }++ var displayName: String {+ switch self {+ case .settings: return "Settings"+ case .wal: return "WAL"+ case .genericPlan: return "Generic Plan"+ case .memory: return "Memory"+ case .serialize: return "Serialize"+ }+ }+ }++ /// True when option is supported on a PG server reporting major version+ /// `serverMajor`. Pass nil when the version is unknown — we permit the+ /// option in that case and let the server tell the user (consistent with+ /// the rest of the codebase, which doesn't pre-detect server features).+ static func isAvailable(_ option: VersionGated, on serverMajor: Int?) -> Bool {+ guard let v = serverMajor else { return true }+ return v >= option.minPostgresMajor+ }+}++// MARK: - Persistence keying++extension ExplainOptions {+ /// UserDefaults key for storing the last-used options per connection.+ /// Connection-scoped so a user's PG 17 server can keep Memory enabled+ /// without polluting a sibling PG 12 connection.+ static func userDefaultsKey(connectionId: UUID) -> String {+ "explainOptions.\(connectionId.uuidString)"+ }+}diff --git a/macos/Presentation/Views/QueryEditor/Explain/ExplainOptionsMenu.swift b/macos/Presentation/Views/QueryEditor/Explain/ExplainOptionsMenu.swiftnew file mode 100644index 0000000..9f6e996--- /dev/null+++ b/macos/Presentation/Views/QueryEditor/Explain/ExplainOptionsMenu.swift@@ -0,0 +1,100 @@+// ExplainOptionsMenu.swift+// Gridex+//+// pgAdmin4-style dropdown attached to the Explain button. Surfaces every PG+// EXPLAIN option as a toggle, with cross-disable + version gating already+// enforced in the model (`ExplainOptions.canEnable` / `isAvailable`).+//+// Visible only for PostgreSQL connections — the other engines have no+// option list. The dropdown vanishes for them; the plain Explain button+// remains.++import SwiftUI++struct ExplainOptionsMenu: View {+ @Binding var options: ExplainOptions++ /// PG server major version, when known (`SHOW server_version_num` / 10000).+ /// Pass nil to permit every option (server will reject if it can't handle).+ let serverMajorVersion: Int?++ var body: some View {+ Menu {+ // ANALYZE — toggle prominently at the top. It's the load-bearing+ // setting (off = plan only / safe; on = execute query / measure).+ Toggle("Analyze (execute query)", isOn: $options.analyze)++ Divider()++ // Plain bool options, alphabetised after Analyze for predictability.+ Toggle("Buffers", isOn: $options.buffers)+ Toggle("Costs", isOn: $options.costs)+ versionGatedToggle("Generic Plan", $options.genericPlan, gate: .genericPlan)+ versionGatedToggle("Memory", $options.memory, gate: .memory)+ Toggle("Settings", isOn: $options.settings)+ .disabled(!ExplainOptions.isAvailable(.settings, on: serverMajorVersion))+ Toggle("Summary", isOn: $options.summary)+ Toggle("Timing", isOn: $options.timing)+ .disabled(!options.canEnable(.timing))+ Toggle("Verbose", isOn: $options.verbose)+ Toggle("WAL", isOn: $options.wal)+ .disabled(!options.canEnable(.wal) || !ExplainOptions.isAvailable(.wal, on: serverMajorVersion))++ Divider()++ // Serialize — submenu like pgAdmin4. Off-state renders as a plain+ // disabled item; the values appear when ANALYZE is on.+ Menu("Serialize") {+ ForEach(ExplainOptions.Serialize.allCases) { value in+ Button {+ options.serialize = value+ } label: {+ if options.serialize == value {+ Label(value.displayName, systemImage: "checkmark")+ } else {+ Text(value.displayName)+ }+ }+ }+ }+ .disabled(!options.canEnable(.serialize) || !ExplainOptions.isAvailable(.serialize, on: serverMajorVersion))++ // Format — submenu. JSON unlocks visual-tree rendering downstream.+ Menu("Format") {+ ForEach(ExplainOptions.Format.allCases) { value in+ Button {+ options.format = value+ } label: {+ if options.format == value {+ Label(value.displayName, systemImage: "checkmark")+ } else {+ Text(value.displayName)+ }+ }+ }+ }+ } label: {+ // Just a chevron next to the Explain button — caller draws the+ // primary "Explain" button itself, this is the disclosure.+ Image(systemName: "chevron.down")+ .font(.system(size: 9, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .controlSize(.small)+ .fixedSize()+ .help("EXPLAIN options")+ }++ @ViewBuilder+ private func versionGatedToggle(+ _ title: String,+ _ binding: Binding<Bool>,+ gate: ExplainOptions.VersionGated+ ) -> some View {+ let available = ExplainOptions.isAvailable(gate, on: serverMajorVersion)+ Toggle(available ? title : "\(title) (PG \(gate.minPostgresMajor)+)", isOn: binding)+ .disabled(!available)+ }+}diff --git a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift b/macos/Presentation/Views/QueryEditor/QueryEditorView.swiftindex 2c7b961..beae27f 100644--- a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift+++ b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift@@ -19,7 +19,17 @@ struct QueryEditorView: View {@State private var isExecuting = false@State private var splitRatio: CGFloat = 0.5+ /// EXPLAIN options surfaced in the dropdown next to the Explain button.+ /// Persisted per-connection via UserDefaults so a fix applied in one+ /// session sticks across restarts.+ @State private var explainOptions: ExplainOptions = .default++ /// PG server major version (`SHOW server_version_num` / 10000), used to+ /// grey out options the server doesn't support (Memory needs PG 17+, etc.)+ @State private var pgServerMajorVersion: Int?+private var isRedis: Bool { appState.activeConfig?.databaseType == .redis }+ private var isPostgres: Bool { appState.activeConfig?.databaseType == .postgresql }var body: some View {VSplitView {@@ -69,14 +79,28 @@ struct QueryEditorView: View {.help(isRedis ? "Run Redis command (⌘R)" : "Run statement at cursor (⌘R)")if !isRedis {- Button(action: explainQuery) {- HStack(spacing: 4) {- Image(systemName: "lightbulb")- Text("Explain")+ // Split: primary button runs EXPLAIN with the current+ // options; the chevron beside opens the toggle menu.+ // For non-PG engines the menu is hidden — they have+ // no per-option syntax to surface.+ HStack(spacing: 0) {+ Button(action: explainQuery) {+ HStack(spacing: 4) {+ Image(systemName: "lightbulb")+ Text("Explain")+ }+ }+ .controlSize(.small)+ .pointerCursor()++ if isPostgres {+ ExplainOptionsMenu(+ options: $explainOptions,+ serverMajorVersion: pgServerMajorVersion+ )+ .padding(.leading, 2)}}- .controlSize(.small)- .pointerCursor()}}.padding(.horizontal, 8)@@ -155,11 +179,15 @@ struct QueryEditorView: View {if let saved = appState.queryEditorText[tabId] {sqlText = saved}+ loadExplainOptionsForActiveConnection()}.onChange(of: sqlText) { _, newValue in// Persist so tab switches don't lose the queryappState.queryEditorText[tabId] = newValue}+ .onChange(of: appState.activeConnectionId) { _, _ in+ loadExplainOptionsForActiveConnection()+ }.onReceive(NotificationCenter.default.publisher(for: .init("pasteQueryToEditor"))) { notif in// Only the currently active query editor tab handles the pasteguard appState.activeTabId == tabId,@@ -374,11 +402,19 @@ struct QueryEditorView: View {isExecuting = trueerrorMessage = nil- guard let explainSQL = adapter.databaseType.explainSQL(for: sql) else {+ // Options apply only to PG (other engines ignore the param).+ let optsForBuild = isPostgres ? explainOptions : .default+ guard let explainSQL = adapter.databaseType.explainSQL(for: sql, options: optsForBuild) else {errorMessage = "EXPLAIN is not supported for \(adapter.databaseType.displayName) connections."isExecuting = falsereturn}++ // Persist whatever the user just used so the next session restores it.+ if isPostgres, let connId = appState.activeConnectionId {+ persistExplainOptions(explainOptions, for: connId)+ }+Task {let start = Date()do {@@ -397,6 +433,53 @@ struct QueryEditorView: View {}}+ // MARK: - EXPLAIN options persistence + version detection++ /// Load saved options for the active connection (and probe server version+ /// for PG, so the menu can grey-out unavailable options).+ private func loadExplainOptionsForActiveConnection() {+ guard let connId = appState.activeConnectionId else {+ explainOptions = .default+ pgServerMajorVersion = nil+ return+ }+ let key = ExplainOptions.userDefaultsKey(connectionId: connId)+ if let data = UserDefaults.standard.data(forKey: key),+ let saved = try? JSONDecoder().decode(ExplainOptions.self, from: data) {+ explainOptions = saved+ } else {+ explainOptions = .default+ }++ guard isPostgres, let adapter = appState.activeAdapter else {+ pgServerMajorVersion = nil+ return+ }+ Task {+ // `serverVersion()` returns the long banner; extract the major.+ // Failure → leave nil → menu permits everything (server enforces).+ let version = (try? await adapter.serverVersion()) ?? ""+ await MainActor.run {+ pgServerMajorVersion = Self.parsePostgresMajor(from: version)+ }+ }+ }++ private func persistExplainOptions(_ opts: ExplainOptions, for connId: UUID) {+ guard let data = try? JSONEncoder().encode(opts) else { return }+ UserDefaults.standard.set(data, forKey: ExplainOptions.userDefaultsKey(connectionId: connId))+ }++ /// Pull the major from the `version()` banner.+ /// Examples: "PostgreSQL 16.2 on …" → 16; "PostgreSQL 9.6.24 …" → 9.+ static func parsePostgresMajor(from banner: String) -> Int? {+ // Look for the first integer after "PostgreSQL ".+ guard let range = banner.range(of: "PostgreSQL ") else { return nil }+ let tail = banner[range.upperBound...]+ let digits = tail.prefix { $0.isNumber }+ return Int(digits)+ }+/// Populate the DataGridViewState with query results so AppKitDataGrid can render them/// with the same look & feel as the table data view.private func applyResult(_ result: QueryResult) {diff --git a/macos/Tests/GridexTests/ExplainOptionsTests.swift b/macos/Tests/GridexTests/ExplainOptionsTests.swiftnew file mode 100644index 0000000..8233fe1--- /dev/null+++ b/macos/Tests/GridexTests/ExplainOptionsTests.swift@@ -0,0 +1,213 @@+// ExplainOptionsTests.swift+// Pure-logic tests for the new ExplainOptions struct + the PG `EXPLAIN (...)`+// option-list builder it powers. No infra needed.++import XCTest+@testable import Gridex++final class ExplainOptionsTests: XCTestCase {++ private let sql = "SELECT * FROM profile"++ // MARK: - Default value pins legacy behaviour++ func test_default_buildsLegacyShape() {+ // The previous hardcoded query was+ // "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) <sql>"+ // The default value of ExplainOptions must reproduce it exactly so+ // every existing call site stays byte-compatible.+ let out = DatabaseType.postgresql.explainSQL(for: sql)+ XCTAssertEqual(out, "EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) \(sql)")+ }++ // MARK: - Always-emitted vs opt-in toggles++ func test_costsCanBeTurnedOff() {+ var opts = ExplainOptions.default+ opts.costs = false+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)+ XCTAssertEqual(out, "EXPLAIN (ANALYZE false, COSTS false, FORMAT TEXT) \(sql)")+ }++ func test_offToggles_doNotAppearInOutput() {+ // Buffers / Memory / Settings / Summary / Verbose / WAL all default+ // false, must not bloat the option list.+ let out = DatabaseType.postgresql.explainSQL(for: sql)!+ XCTAssertFalse(out.contains("BUFFERS"))+ XCTAssertFalse(out.contains("MEMORY"))+ XCTAssertFalse(out.contains("SETTINGS"))+ XCTAssertFalse(out.contains("SUMMARY"))+ XCTAssertFalse(out.contains("VERBOSE"))+ XCTAssertFalse(out.contains("WAL"))+ XCTAssertFalse(out.contains("GENERIC_PLAN"))+ XCTAssertFalse(out.contains("SERIALIZE"))+ }++ func test_onToggles_appearWithTrue() {+ var opts = ExplainOptions.default+ opts.buffers = true+ opts.memory = true+ opts.settings = true+ opts.summary = true+ opts.verbose = true+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)!+ for piece in ["BUFFERS true", "MEMORY true", "SETTINGS true",+ "SUMMARY true", "VERBOSE true"] {+ XCTAssertTrue(out.contains(piece), "missing '\(piece)' in: \(out)")+ }+ }++ // MARK: - Cross-disable: ANALYZE-dependent options++ func test_timing_requiresAnalyze_sanitizedOut() {+ // User toggles Timing on without enabling Analyze. PG would 400 with+ // "EXPLAIN option TIMING requires ANALYZE". `sanitized()` (called+ // inside the builder) drops the offending flag pre-flight.+ var opts = ExplainOptions.default+ opts.analyze = false+ opts.timing = true+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)!+ XCTAssertFalse(out.contains("TIMING"), "TIMING must be stripped when ANALYZE is off")+ }++ func test_wal_requiresAnalyze_sanitizedOut() {+ var opts = ExplainOptions.default+ opts.wal = true+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)!+ XCTAssertFalse(out.contains("WAL"))+ }++ func test_serialize_requiresAnalyze_sanitizedOut() {+ var opts = ExplainOptions.default+ opts.serialize = .text+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)!+ XCTAssertFalse(out.contains("SERIALIZE"))+ }++ func test_canEnable_returnsFalse_whenAnalyzeOff() {+ var opts = ExplainOptions.default+ opts.analyze = false+ for dep in ExplainOptions.AnalyzeDependency.allCases {+ XCTAssertFalse(opts.canEnable(dep), "\(dep) must be disabled when analyze=false")+ }+ }++ func test_canEnable_returnsTrue_whenAnalyzeOn() {+ var opts = ExplainOptions.default+ opts.analyze = true+ for dep in ExplainOptions.AnalyzeDependency.allCases {+ XCTAssertTrue(opts.canEnable(dep), "\(dep) must be enabled when analyze=true")+ }+ }++ func test_analyzeOn_keepsDependentOptions() {+ var opts = ExplainOptions.default+ opts.analyze = true+ opts.timing = true+ opts.wal = true+ opts.serialize = .binary+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)!+ XCTAssertTrue(out.contains("ANALYZE true"))+ XCTAssertTrue(out.contains("TIMING true"))+ XCTAssertTrue(out.contains("WAL true"))+ XCTAssertTrue(out.contains("SERIALIZE BINARY"))+ }++ // MARK: - Format submenu++ func test_format_changesOutputClause() {+ for fmt in ExplainOptions.Format.allCases {+ var opts = ExplainOptions.default+ opts.format = fmt+ let out = DatabaseType.postgresql.explainSQL(for: sql, options: opts)!+ XCTAssertTrue(out.contains("FORMAT \(fmt.rawValue)"),+ "missing 'FORMAT \(fmt.rawValue)' in: \(out)")+ }+ }++ // MARK: - Version gating++ func test_versionGating_minMajor() {+ XCTAssertEqual(ExplainOptions.VersionGated.settings.minPostgresMajor, 12)+ XCTAssertEqual(ExplainOptions.VersionGated.wal.minPostgresMajor, 13)+ XCTAssertEqual(ExplainOptions.VersionGated.genericPlan.minPostgresMajor, 16)+ XCTAssertEqual(ExplainOptions.VersionGated.memory.minPostgresMajor, 17)+ XCTAssertEqual(ExplainOptions.VersionGated.serialize.minPostgresMajor, 17)+ }++ func test_isAvailable_respectsServerVersion() {+ // PG 12 server: settings yes, wal/generic/memory/serialize no.+ XCTAssertTrue(ExplainOptions.isAvailable(.settings, on: 12))+ XCTAssertFalse(ExplainOptions.isAvailable(.wal, on: 12))+ XCTAssertFalse(ExplainOptions.isAvailable(.memory, on: 12))++ // PG 17 server: every gated option allowed.+ for opt in ExplainOptions.VersionGated.allCases {+ XCTAssertTrue(ExplainOptions.isAvailable(opt, on: 17),+ "\(opt) must be available on PG 17")+ }+ }++ func test_isAvailable_nilVersion_permitsEverything() {+ // When server version is unknown, we default to permissive — let the+ // server tell the user. Matches the rest of the codebase, which doesn't+ // pre-detect server features.+ for opt in ExplainOptions.VersionGated.allCases {+ XCTAssertTrue(ExplainOptions.isAvailable(opt, on: nil))+ }+ }++ // MARK: - Other engines unchanged by options++ func test_otherEngines_ignoreOptions() {+ var opts = ExplainOptions.default+ opts.analyze = true+ opts.buffers = true+ opts.format = .json+ // MySQL / SQLite / MSSQL / ClickHouse have no per-option syntax.+ XCTAssertEqual(DatabaseType.mysql.explainSQL(for: sql, options: opts),+ "EXPLAIN \(sql)")+ XCTAssertEqual(DatabaseType.sqlite.explainSQL(for: sql, options: opts),+ "EXPLAIN QUERY PLAN \(sql)")+ XCTAssertEqual(DatabaseType.mssql.explainSQL(for: sql, options: opts),+ "SET SHOWPLAN_TEXT ON; \(sql); SET SHOWPLAN_TEXT OFF")+ XCTAssertEqual(DatabaseType.clickhouse.explainSQL(for: sql, options: opts),+ "EXPLAIN \(sql)")+ XCTAssertNil(DatabaseType.mongodb.explainSQL(for: sql, options: opts))+ XCTAssertNil(DatabaseType.redis.explainSQL(for: sql, options: opts))+ }++ // MARK: - Codable persistence++ func test_codable_roundTripsAllFields() throws {+ var opts = ExplainOptions.default+ opts.analyze = true+ opts.buffers = true+ opts.genericPlan = true+ opts.memory = true+ opts.settings = true+ opts.summary = true+ opts.timing = true+ opts.verbose = true+ opts.wal = true+ opts.serialize = .binary+ opts.format = .json++ let data = try JSONEncoder().encode(opts)+ let restored = try JSONDecoder().decode(ExplainOptions.self, from: data)+ XCTAssertEqual(restored, opts)+ }++ // MARK: - PG version banner parsing++ func test_parsePostgresMajor_examples() {+ XCTAssertEqual(QueryEditorView.parsePostgresMajor(from:+ "PostgreSQL 16.2 on aarch64-apple-darwin"), 16)+ XCTAssertEqual(QueryEditorView.parsePostgresMajor(from:+ "PostgreSQL 9.6.24 on x86_64-pc-linux-gnu"), 9)+ XCTAssertEqual(QueryEditorView.parsePostgresMajor(from:+ "PostgreSQL 17rc1"), 17)+ XCTAssertNil(QueryEditorView.parsePostgresMajor(from: "garbage"))+ XCTAssertNil(QueryEditorView.parsePostgresMajor(from: ""))+ }+}diff --git a/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift b/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swiftindex 2a665bb..e2a92bd 100644--- a/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift+++ b/macos/Tests/GridexTests/PostgreSQLAdapterIntegrationTests.swift@@ -346,4 +346,62 @@ final class PostgreSQLAdapterIntegrationTests: XCTestCase {_ = try? await adapter.executeRaw(sql: "DROP TABLE IF EXISTS \(table)")try await adapter.disconnect()}++ // MARK: - ExplainOptions — server accepts the option lists we build++ /// Sanity check that `EXPLAIN (BUFFERS true, COSTS true, FORMAT JSON, ...)`+ /// — the shape produced when a user toggles options in the new dropdown —+ /// is something a real PG server actually parses. The pure-logic+ /// ExplainOptionsTests cover SQL shape; this one covers wire compatibility.+ func test_explainOptions_pgAcceptsBuiltOptionLists() 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)++ let table = "gridex_explain_opts_\(UUID().uuidString.prefix(8).lowercased())"+ do {+ _ = try await adapter.executeRaw(sql: "CREATE TABLE \(table) (id int)")+ _ = try await adapter.executeRaw(sql: "INSERT INTO \(table) VALUES (1), (2), (3)")++ // Plan-only with extra detail — should never modify data.+ var planOnly = ExplainOptions.default+ planOnly.buffers = true+ planOnly.verbose = true+ planOnly.summary = true+ planOnly.format = .json+ let planSQL = DatabaseType.postgresql.explainSQL(+ for: "SELECT * FROM \(table)",+ options: planOnly+ )!+ let planRes = try await adapter.executeRaw(sql: planSQL)+ XCTAssertFalse(planRes.rows.isEmpty,+ "EXPLAIN with bool toggles + JSON format must return plan rows")++ // Actual execution with timing — should run the SELECT, not modify+ // the table. Asserts the cross-disable rules in `sanitized()` don't+ // strip Timing when ANALYZE is on.+ var withAnalyze = ExplainOptions.default+ withAnalyze.analyze = true+ withAnalyze.timing = true+ withAnalyze.buffers = true+ let analyzeSQL = DatabaseType.postgresql.explainSQL(+ for: "SELECT count(*) FROM \(table)",+ options: withAnalyze+ )!+ XCTAssertTrue(analyzeSQL.contains("TIMING true"),+ "Timing must survive sanitize when Analyze is on")+ let analyzeRes = try await adapter.executeRaw(sql: analyzeSQL)+ XCTAssertFalse(analyzeRes.rows.isEmpty,+ "EXPLAIN ANALYZE must return plan rows including actual times")+ } 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()+ }}