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++

feat: Clickhouse

Tobifebee96c04f6
diff --git a/CLAUDE.md b/CLAUDE.md
index 4ae01b9..daced9b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,41 +1,65 @@
-# Gridex — AI-Native Database IDE for macOS
-
-## Project Overview
-Native macOS app (Swift, AppKit) combining a powerful database GUI with built-in AI chat.
-
-## Architecture
-Clean Architecture with 5 layers:
-- **Core**: Protocols, Models, Enums, Errors, Extensions — zero dependencies
-- **Domain**: Use Cases, Repository protocols — depends only on Core
-- **Data**: Database adapters (SQLite, PostgreSQL, MySQL, Redis), SwiftData persistence, Keychain — implements Domain
-- **Services**: Query Engine, AI (Anthropic/OpenAI/Ollama), SSH Tunnel, Import/Export
-- **Presentation**: AppKit views (NSTableView, NSOutlineView, NSSplitView), SwiftUI settings, ViewModels, Coordinators
-
-## Tech Stack
-- **Language**: Swift 5.10+
-- **UI**: AppKit (primary) + SwiftUI (settings, forms)
-- **Persistence**: SwiftData
-- **Credentials**: macOS Keychain
-- **DB Drivers**: PostgresNIO, MySQLNIO, SQLite3, RediStack
-- **SSH**: swift-nio-ssh
-- **AI**: Direct API calls to Anthropic/OpenAI, local Ollama
-
-## Key Conventions
-- All database adapters conform to `DatabaseAdapter` protocol
-- All LLM providers conform to `LLMService` protocol
-- Use `actor` for thread-safe services (ConnectionManager, QueryEngine)
-- SwiftData `@Model` entities live in Data/Persistence/Models
-- Domain models are plain structs (Codable, Sendable)
-- Dependency injection via `DependencyContainer`
-- Errors centralized in `GridexError` enum
-
-## Folder Structure
-- `macos/` — macOS app source code
-- `window/` — Windows app (future)
-- `Package.swift` — SPM manifest
-
-## Build & Run
-```bash
-swift build
-.build/debug/Gridex
+# CLAUDE.md
+
+Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
+
+**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
+
+## 1. Think Before Coding
+
+**Don't assume. Don't hide confusion. Surface tradeoffs.**
+
+Before implementing:
+- State your assumptions explicitly. If uncertain, ask.
+- If multiple interpretations exist, present them - don't pick silently.
+- If a simpler approach exists, say so. Push back when warranted.
+- If something is unclear, stop. Name what's confusing. Ask.
+
+## 2. Simplicity First
+
+**Minimum code that solves the problem. Nothing speculative.**
+
+- No features beyond what was asked.
+- No abstractions for single-use code.
+- No "flexibility" or "configurability" that wasn't requested.
+- No error handling for impossible scenarios.
+- If you write 200 lines and it could be 50, rewrite it.
+
+Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
+
+## 3. Surgical Changes
+
+**Touch only what you must. Clean up only your own mess.**
+
+When editing existing code:
+- Don't "improve" adjacent code, comments, or formatting.
+- Don't refactor things that aren't broken.
+- Match existing style, even if you'd do it differently.
+- If you notice unrelated dead code, mention it - don't delete it.
+
+When your changes create orphans:
+- Remove imports/variables/functions that YOUR changes made unused.
+- Don't remove pre-existing dead code unless asked.
+
+The test: Every changed line should trace directly to the user's request.
+
+## 4. Goal-Driven Execution
+
+**Define success criteria. Loop until verified.**
+
+Transform tasks into verifiable goals:
+- "Add validation" → "Write tests for invalid inputs, then make them pass"
+- "Fix the bug" → "Write a test that reproduces it, then make it pass"
+- "Refactor X" → "Ensure tests pass before and after"
+
+For multi-step tasks, state a brief plan:
+```
+1. [Step] → verify: [check]
+2. [Step] → verify: [check]
+3. [Step] → verify: [check]
```
+
+Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
+
+---
+
+**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
diff --git a/macos/App/State/AppState.swift b/macos/App/State/AppState.swift
index c2c381d..507d5a1 100644
--- a/macos/App/State/AppState.swift
+++ b/macos/App/State/AppState.swift
@@ -727,6 +727,19 @@ final class AppState: ObservableObject {
Task { await loadSidebar(config: config, adapter: adapter) }
}
+ /// Re-fetch the database list from the active adapter and publish it.
+ /// Call after CREATE DATABASE / DROP DATABASE so pickers and switchers update
+ /// without waiting for the user to reconnect.
+ func refreshAvailableDatabases() async {
+ guard let adapter = activeAdapter else { return }
+ do {
+ let databases = try await adapter.listDatabases()
+ availableDatabases = databases
+ } catch {
+ print("refreshAvailableDatabases failed: \(error)")
+ }
+ }
+
func loadSavedConnections() async {
do {
savedConnections = try await container.connectionRepository.fetchAll()
diff --git a/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift b/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift
index 06e0060..9fc8c33 100644
--- a/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift
+++ b/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift
@@ -465,21 +465,71 @@ final class ClickHouseAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Se
}
func updateRow(table: String, schema: String?, set: [String: RowValue], where whereClause: [String: RowValue]) async throws -> QueryResult {
- // ClickHouse uses ALTER TABLE ... UPDATE (async mutation).
+ // ClickHouse uses ALTER TABLE ... UPDATE (async mutation). Only MergeTree-family
+ // engines support mutations — fail fast with a clear message for others.
let d = SQLDialect.clickhouse
let db = try resolveDB(schema)
+ try await ensureMutable(db: db, table: table, operation: "UPDATE")
let qualified = qualifiedName(db: db, table: table, dialect: d)
let setClauses = set.map { "\(d.quoteIdentifier($0.key)) = \(inlineValue($0.value))" }.joined(separator: ", ")
let whereClauses = whereClause.map { "\(d.quoteIdentifier($0.key)) = \(inlineValue($0.value))" }.joined(separator: " AND ")
- return try await executeRaw(sql: "ALTER TABLE \(qualified) UPDATE \(setClauses) WHERE \(whereClauses)")
+ return try await executeMutationWithFriendlyError(
+ sql: "ALTER TABLE \(qualified) UPDATE \(setClauses) WHERE \(whereClauses)",
+ operation: "UPDATE"
+ )
}
func deleteRow(table: String, schema: String?, where whereClause: [String: RowValue]) async throws -> QueryResult {
let d = SQLDialect.clickhouse
let db = try resolveDB(schema)
+ try await ensureMutable(db: db, table: table, operation: "DELETE")
let qualified = qualifiedName(db: db, table: table, dialect: d)
let clauses = whereClause.map { "\(d.quoteIdentifier($0.key)) = \(inlineValue($0.value))" }.joined(separator: " AND ")
- return try await executeRaw(sql: "ALTER TABLE \(qualified) DELETE WHERE \(clauses)")
+ return try await executeMutationWithFriendlyError(
+ sql: "ALTER TABLE \(qualified) DELETE WHERE \(clauses)",
+ operation: "DELETE"
+ )
+ }
+
+ /// Pre-check the table engine: only MergeTree-family engines support ALTER ... UPDATE/DELETE.
+ /// Views, Dictionaries, and *Log engines raise CH error code 48 ("NOT_IMPLEMENTED") mid-flight;
+ /// catching it here lets us explain the *why* instead of surfacing the raw server message.
+ private func ensureMutable(db: String, table: String, operation: String) async throws {
+ let r = try? await executeRaw(sql: """
+ SELECT engine FROM system.tables
+ WHERE database = '\(escape(db))' AND name = '\(escape(table))'
+ """)
+ let engine = r?.rows.first?.first?.stringValue ?? ""
+ guard !engine.isEmpty else { return } // table unknown — let the server decide
+ if engine.contains("MergeTree") { return } // MergeTree family supports mutations
+ throw GridexError.queryExecutionFailed(
+ "ClickHouse: cannot \(operation) rows in `\(db)`.`\(table)` — engine `\(engine)` does not support row mutations. "
+ + "Only MergeTree-family engines accept ALTER TABLE ... \(operation). "
+ + "For Dictionary/View tables, update the underlying source instead."
+ )
+ }
+
+ /// Wrap mutation execution so CH server errors about non-mutable engines surface with a
+ /// friendlier explanation even when our pre-check is bypassed (e.g. race with schema change).
+ private func executeMutationWithFriendlyError(sql: String, operation: String) async throws -> QueryResult {
+ do {
+ return try await executeRaw(sql: sql)
+ } catch let err as GridexError {
+ if case .queryExecutionFailed(let msg) = err {
+ let lower = msg.lowercased()
+ if lower.contains("lightweight updates are not supported")
+ || lower.contains("not_implemented")
+ || lower.contains("read-only")
+ || lower.contains("mutations are not supported") {
+ throw GridexError.queryExecutionFailed(
+ "ClickHouse: \(operation) failed — this table's engine does not support row mutations. "
+ + "Only MergeTree-family engines accept ALTER TABLE ... \(operation). "
+ + "Server message: \(msg)"
+ )
+ }
+ }
+ throw err
+ }
}
// MARK: - Transactions (no-op — ClickHouse has no traditional transactions)
diff --git a/macos/Presentation/Views/Main/MainView.swift b/macos/Presentation/Views/Main/MainView.swift
index 5417581..b000188 100644
--- a/macos/Presentation/Views/Main/MainView.swift
+++ b/macos/Presentation/Views/Main/MainView.swift
@@ -1575,10 +1575,7 @@ struct DatabaseSwitcherDialog: View {
guard let name = selected, let adapter = appState.activeAdapter else { return }
do {
try await adapter.dropDatabase(name: name)
- // Refresh database list
- if let databases = try? await adapter.listDatabases() {
- appState.availableDatabases = databases
- }
+ await appState.refreshAvailableDatabases()
selected = appState.currentDatabaseName ?? filteredDatabases.first
} catch {
deleteError = error.localizedDescription
@@ -1801,10 +1798,8 @@ struct NewDatabaseSheet: View {
return
}
- // Refresh database list and switch
- if let databases = try? await adapter.listDatabases() {
- appState.availableDatabases = databases
- }
+ // Refresh database list before dismissing so the picker/switcher updates immediately
+ await appState.refreshAvailableDatabases()
dismiss()
onCreated(dbName)
}
diff --git a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
index d5605c9..1718e54 100644
--- a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
+++ b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
@@ -285,9 +285,7 @@ struct QueryEditorView: View {
appState.currentDatabaseName = newDB
}
// Refresh the available databases list (picker shows new/removed DBs)
- if let databases = try? await adapter.listDatabases() {
- appState.availableDatabases = databases
- }
+ await appState.refreshAvailableDatabases()
}
// Script may have created/altered/dropped tables — refresh the sidebar