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): add ClickHouse adapter via HTTP interface

Tobi81e98cad3047
diff --git a/macos/App/State/AppState.swift b/macos/App/State/AppState.swift
index 2bf6736..c2c381d 100644
--- a/macos/App/State/AppState.swift
+++ b/macos/App/State/AppState.swift
@@ -609,6 +609,11 @@ final class AppState: ObservableObject {
_ = try await adapter.executeRaw(sql: "USE [\(databaseName.replacingOccurrences(of: "]", with: "]]"))]")
currentDatabaseName = databaseName
+ case .clickhouse:
+ // ClickHouse HTTP is stateless — adapter intercepts USE and updates its default DB.
+ _ = try await adapter.executeRaw(sql: "USE `\(databaseName.replacingOccurrences(of: "`", with: "``"))`")
+ currentDatabaseName = databaseName
+
case .postgresql:
// PostgreSQL: each connection is tied to one database — must reconnect
try await adapter.disconnect()
diff --git a/macos/Core/Enums/DatabaseType.swift b/macos/Core/Enums/DatabaseType.swift
index bd140c2..d247f51 100644
--- a/macos/Core/Enums/DatabaseType.swift
+++ b/macos/Core/Enums/DatabaseType.swift
@@ -10,6 +10,7 @@ enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {
case redis = "redis"
case mongodb = "mongodb"
case mssql = "mssql"
+ case clickhouse = "clickhouse"
var id: String { rawValue }
@@ -21,6 +22,7 @@ enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {
case .redis: return "Redis"
case .mongodb: return "MongoDB"
case .mssql: return "SQL Server"
+ case .clickhouse: return "ClickHouse"
}
}
@@ -32,6 +34,7 @@ enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {
case .redis: return 6379
case .mongodb: return 27017
case .mssql: return 1433
+ case .clickhouse: return 8123
}
}
@@ -43,6 +46,7 @@ enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {
case .redis: return "key.fill"
case .mongodb: return "leaf.fill"
case .mssql: return "cylinder.split.1x2.fill"
+ case .clickhouse: return "bolt.horizontal.circle.fill"
}
}
@@ -54,13 +58,14 @@ enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {
case .redis: return .redis
case .mongodb: return .mongodb
case .mssql: return .mssql
+ case .clickhouse: return .clickhouse
}
}
/// Whether this database type uses SQL as its query language.
var isSQL: Bool {
switch self {
- case .postgresql, .mysql, .sqlite, .mssql: return true
+ case .postgresql, .mysql, .sqlite, .mssql, .clickhouse: return true
case .redis, .mongodb: return false
}
}
@@ -68,7 +73,7 @@ enum DatabaseType: String, Codable, Sendable, CaseIterable, Identifiable {
var supportsSchemas: Bool {
switch self {
case .postgresql, .mssql: return true
- case .mysql, .sqlite, .redis, .mongodb: return false
+ case .mysql, .sqlite, .redis, .mongodb, .clickhouse: return false
}
}
}
diff --git a/macos/Core/Enums/SQLDialect.swift b/macos/Core/Enums/SQLDialect.swift
index 0a2224e..1935648 100644
--- a/macos/Core/Enums/SQLDialect.swift
+++ b/macos/Core/Enums/SQLDialect.swift
@@ -10,12 +10,13 @@ enum SQLDialect: Sendable {
case redis
case mongodb
case mssql
+ case clickhouse
func quoteIdentifier(_ identifier: String) -> String {
switch self {
case .postgresql, .sqlite:
return "\"\(identifier.replacingOccurrences(of: "\"", with: "\"\""))\""
- case .mysql:
+ case .mysql, .clickhouse:
return "`\(identifier.replacingOccurrences(of: "`", with: "``"))`"
case .mssql:
return "[\(identifier.replacingOccurrences(of: "]", with: "]]"))]"
@@ -43,7 +44,7 @@ enum SQLDialect: Sendable {
return { "$\($0)" }
case .mssql:
return { "@p\($0)" }
- case .mysql, .sqlite, .redis, .mongodb:
+ case .mysql, .sqlite, .redis, .mongodb, .clickhouse:
return { _ in "?" }
}
}
diff --git a/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift b/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift
new file mode 100644
index 0000000..06e0060
--- /dev/null
+++ b/macos/Data/Adapters/ClickHouse/ClickHouseAdapter.swift
@@ -0,0 +1,707 @@
+// ClickHouseAdapter.swift
+// Gridex
+//
+// ClickHouse adapter using the HTTP interface (ports 8123/8443). Speaks
+// JSONCompact for SELECTs and plain statements for DDL/DML. No native TCP.
+
+import Foundation
+
+final class ClickHouseAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Sendable {
+
+ let databaseType: DatabaseType = .clickhouse
+ private(set) var isConnected: Bool = false
+
+ private let stateLock = NSLock()
+ private var client: ClickHouseHTTPClient?
+ private var storedConfig: ConnectionConfig?
+ private var storedPassword: String?
+ private var currentDB: String?
+ private var serverVersionCache: String?
+
+ // MARK: - Connection lifecycle
+
+ func connect(config: ConnectionConfig, password: String?) async throws {
+ let host = config.host ?? "localhost"
+ let port = config.port ?? (config.sslEnabled ? 8443 : 8123)
+ let username = config.username ?? "default"
+ let database = config.database
+
+ let newClient = ClickHouseHTTPClient(
+ host: host,
+ port: port,
+ username: username,
+ password: password ?? "",
+ defaultDatabase: database,
+ useTLS: config.sslEnabled,
+ sslCACertPath: config.sslCACertPath,
+ sslClientBundlePath: config.sslCertPath
+ )
+
+ do {
+ _ = try await newClient.send(sql: "SELECT 1 FORMAT JSONCompact", readOnly: true)
+ } catch {
+ if case GridexError.connectionFailed = error { throw error }
+ throw GridexError.connectionFailed(underlying: error)
+ }
+
+ stateLock.lock()
+ self.client = newClient
+ self.storedConfig = config
+ self.storedPassword = password
+ self.currentDB = (database?.isEmpty == false) ? database : nil
+ self.isConnected = true
+ stateLock.unlock()
+
+ // Cache server version for introspection fallbacks (21.3+ has is_in_primary_key).
+ self.serverVersionCache = try? await fetchServerVersion()
+ }
+
+ func disconnect() async throws {
+ stateLock.lock()
+ client = nil
+ storedConfig = nil
+ storedPassword = nil
+ currentDB = nil
+ serverVersionCache = nil
+ isConnected = false
+ stateLock.unlock()
+ }
+
+ func testConnection(config: ConnectionConfig, password: String?) async throws -> Bool {
+ let adapter = ClickHouseAdapter()
+ do {
+ try await adapter.connect(config: config, password: password)
+ _ = try? await adapter.serverVersion()
+ try await adapter.disconnect()
+ return true
+ } catch {
+ try? await adapter.disconnect()
+ throw error
+ }
+ }
+
+ private func requireClient() throws -> ClickHouseHTTPClient {
+ stateLock.lock()
+ defer { stateLock.unlock() }
+ guard let client else {
+ throw GridexError.queryExecutionFailed("Not connected to ClickHouse")
+ }
+ return client
+ }
+
+ // MARK: - Query Execution
+
+ func execute(query: String, parameters: [QueryParameter]?) async throws -> QueryResult {
+ try await executeRaw(sql: query)
+ }
+
+ func executeRaw(sql: String) async throws -> QueryResult {
+ let start = CFAbsoluteTimeGetCurrent()
+ let trimmed = sql.trimmingCharacters(in: .whitespacesAndNewlines)
+ let upper = trimmed.uppercased()
+
+ // ClickHouse HTTP is stateless — intercept USE to update in-memory default DB.
+ if upper.hasPrefix("USE ") {
+ let name = parseUseStatement(trimmed)
+ if !name.isEmpty {
+ stateLock.lock()
+ currentDB = name
+ // Rebuild client so future requests include the new default database.
+ if let cfg = storedConfig {
+ let host = cfg.host ?? "localhost"
+ let port = cfg.port ?? (cfg.sslEnabled ? 8443 : 8123)
+ let username = cfg.username ?? "default"
+ client = ClickHouseHTTPClient(
+ host: host,
+ port: port,
+ username: username,
+ password: storedPassword ?? "",
+ defaultDatabase: name,
+ useTLS: cfg.sslEnabled,
+ sslCACertPath: cfg.sslCACertPath,
+ sslClientBundlePath: cfg.sslCertPath
+ )
+ }
+ stateLock.unlock()
+ }
+ let elapsed = CFAbsoluteTimeGetCurrent() - start
+ return QueryResult(columns: [], rows: [], rowsAffected: 0, executionTime: elapsed, queryType: .other)
+ }
+
+ let qType = detectQueryType(upper)
+ let isSelectShaped = qType == .select
+ || upper.hasPrefix("EXPLAIN")
+ || upper.hasPrefix("WITH")
+ || upper.hasPrefix("SHOW")
+ || upper.hasPrefix("DESCRIBE")
+ || upper.hasPrefix("DESC ")
+
+ let client = try requireClient()
+
+ if isSelectShaped {
+ let wireSQL = trimmed + " FORMAT JSONCompact"
+ let response = try await client.send(sql: wireSQL, readOnly: false)
+ let elapsed = CFAbsoluteTimeGetCurrent() - start
+ return try parseJSONCompact(data: response.body, elapsed: elapsed)
+ } else {
+ let response = try await client.send(sql: trimmed, readOnly: false)
+ let elapsed = CFAbsoluteTimeGetCurrent() - start
+ return QueryResult(columns: [], rows: [], rowsAffected: response.writtenRows, executionTime: elapsed, queryType: qType)
+ }
+ }
+
+ // MARK: - JSONCompact parsing
+
+ private func parseJSONCompact(data: Data, elapsed: TimeInterval) throws -> QueryResult {
+ guard !data.isEmpty else {
+ return QueryResult(columns: [], rows: [], rowsAffected: 0, executionTime: elapsed, queryType: .select)
+ }
+
+ let root: Any
+ do {
+ root = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
+ } catch {
+ let snippet = String(data: data.prefix(400), encoding: .utf8) ?? ""
+ throw GridexError.queryExecutionFailed("Unexpected ClickHouse response: \(snippet)")
+ }
+ guard let dict = root as? [String: Any],
+ let metaArr = dict["meta"] as? [[String: Any]],
+ let dataArr = dict["data"] as? [[Any]]
+ else {
+ return QueryResult(columns: [], rows: [], rowsAffected: 0, executionTime: elapsed, queryType: .select)
+ }
+
+ struct Meta { let name: String; let type: String }
+ let meta: [Meta] = metaArr.compactMap { entry in
+ guard let name = entry["name"] as? String,
+ let type = entry["type"] as? String else { return nil }
+ return Meta(name: name, type: type)
+ }
+ let columns = meta.map {
+ ColumnHeader(name: $0.name, dataType: $0.type, isNullable: $0.type.hasPrefix("Nullable"))
+ }
+ let rows: [[RowValue]] = dataArr.map { row in
+ row.enumerated().map { idx, raw in
+ let type = idx < meta.count ? meta[idx].type : "String"
+ return decodeRow(raw, chType: type)
+ }
+ }
+ return QueryResult(columns: columns, rows: rows, rowsAffected: 0, executionTime: elapsed, queryType: .select)
+ }
+
+ private func decodeRow(_ raw: Any, chType: String) -> RowValue {
+ // Strip Nullable(T) wrapping
+ let unwrapped: String = {
+ if chType.hasPrefix("Nullable(") && chType.hasSuffix(")") {
+ return String(chType.dropFirst("Nullable(".count).dropLast())
+ }
+ return chType
+ }()
+
+ if raw is NSNull { return .null }
+
+ if unwrapped.hasPrefix("Array(") {
+ if let items = raw as? [Any] {
+ let inner = String(unwrapped.dropFirst("Array(".count).dropLast())
+ return .array(items.map { decodeRow($0, chType: inner) })
+ }
+ return .null
+ }
+
+ if unwrapped == "Boolean" || unwrapped == "Bool" {
+ if let b = raw as? Bool { return .boolean(b) }
+ if let n = raw as? NSNumber { return .boolean(n.intValue != 0) }
+ if let s = raw as? String { return .boolean(s == "true" || s == "1") }
+ return .null
+ }
+
+ if unwrapped.hasPrefix("UInt") || unwrapped.hasPrefix("Int") {
+ if let s = raw as? String {
+ if let i = Int64(s) { return .integer(i) }
+ if let u = UInt64(s) { return .integer(Int64(bitPattern: u)) }
+ return .string(s)
+ }
+ if let n = raw as? NSNumber { return .integer(n.int64Value) }
+ return .null
+ }
+
+ if unwrapped.hasPrefix("Float") {
+ if let n = raw as? NSNumber { return .double(n.doubleValue) }
+ if let s = raw as? String, let d = Double(s) { return .double(d) }
+ return .null
+ }
+
+ if unwrapped.hasPrefix("Decimal") {
+ if let s = raw as? String { return .string(s) }
+ if let n = raw as? NSNumber { return .string(n.stringValue) }
+ return .null
+ }
+
+ if unwrapped == "UUID" {
+ if let s = raw as? String, let uuid = UUID(uuidString: s) { return .uuid(uuid) }
+ if let s = raw as? String { return .string(s) }
+ return .null
+ }
+
+ if unwrapped.hasPrefix("Date") {
+ if let s = raw as? String {
+ let fmts = ["yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"]
+ let fmt = DateFormatter()
+ fmt.timeZone = TimeZone(identifier: "UTC")
+ for pattern in fmts {
+ fmt.dateFormat = pattern
+ if let d = fmt.date(from: s) { return .date(d) }
+ }
+ return .string(s)
+ }
+ return .null
+ }
+
+ if unwrapped.hasPrefix("Map(") || unwrapped.hasPrefix("Tuple(") || unwrapped == "JSON" || unwrapped == "Object('json')" {
+ if let s = raw as? String { return .json(s) }
+ if let data = try? JSONSerialization.data(withJSONObject: raw),
+ let text = String(data: data, encoding: .utf8) {
+ return .json(text)
+ }
+ return .null
+ }
+
+ // String / FixedString / IPv4 / IPv6 / Enum* / fallback
+ if let s = raw as? String { return .string(s) }
+ if let n = raw as? NSNumber { return .integer(n.int64Value) }
+ if let b = raw as? Bool { return .boolean(b) }
+ return .null
+ }
+
+ // MARK: - Schema Inspection
+
+ func listDatabases() async throws -> [String] {
+ let r = try await executeRaw(sql: "SELECT name FROM system.databases ORDER BY name")
+ return r.rows.compactMap { $0.first?.stringValue }
+ }
+
+ func listSchemas(database: String?) async throws -> [String] {
+ // ClickHouse is flat — databases are the schema boundary.
+ []
+ }
+
+ func listTables(schema: String?) async throws -> [TableInfo] {
+ let db = try resolveDB(schema)
+ let sql = """
+ SELECT name, total_rows FROM system.tables
+ WHERE database = '\(escape(db))' AND engine NOT LIKE '%View'
+ ORDER BY name
+ """
+ let r = try await executeRaw(sql: sql)
+ return r.rows.compactMap { row -> TableInfo? in
+ guard let name = row.first?.stringValue else { return nil }
+ let count = row.count > 1 ? row[1].intValue : nil
+ return TableInfo(name: name, schema: db, type: .table, estimatedRowCount: count)
+ }
+ }
+
+ func listViews(schema: String?) async throws -> [ViewInfo] {
+ let db = try resolveDB(schema)
+ let sql = """
+ SELECT name, as_select, engine FROM system.tables
+ WHERE database = '\(escape(db))' AND engine LIKE '%View'
+ ORDER BY name
+ """
+ let r = try await executeRaw(sql: sql)
+ return r.rows.compactMap { row -> ViewInfo? in
+ guard let name = row.first?.stringValue else { return nil }
+ let def = row.count > 1 ? row[1].stringValue : nil
+ let engine = row.count > 2 ? (row[2].stringValue ?? "") : ""
+ return ViewInfo(name: name, schema: db, definition: def, isMaterialized: engine == "MaterializedView")
+ }
+ }
+
+ func describeTable(name: String, schema: String?) async throws -> TableDescription {
+ let db = try resolveDB(schema)
+ let columns = try await describeColumns(table: name, schema: db)
+ let indexes = try await listIndexes(table: name, schema: db)
+
+ // Row count + comment from system.tables
+ let meta = try? await executeRaw(sql: """
+ SELECT total_rows, comment FROM system.tables
+ WHERE database = '\(escape(db))' AND name = '\(escape(name))'
+ """)
+ let estRows = meta?.rows.first?[0].intValue
+ let comment = meta?.rows.first?[1].stringValue
+
+ return TableDescription(
+ name: name,
+ schema: db,
+ columns: columns,
+ indexes: indexes,
+ foreignKeys: [], // ClickHouse has no foreign keys
+ constraints: [],
+ comment: (comment?.isEmpty == true) ? nil : comment,
+ estimatedRowCount: estRows
+ )
+ }
+
+ private func describeColumns(table: String, schema db: String) async throws -> [ColumnInfo] {
+ let hasPKFlag = supportsIsInPrimaryKey()
+
+ let selectList = hasPKFlag
+ ? "name, type, default_kind, default_expression, comment, is_in_primary_key, position"
+ : "name, type, default_kind, default_expression, comment, 0 AS is_in_primary_key, position"
+
+ let r = try await executeRaw(sql: """
+ SELECT \(selectList) FROM system.columns
+ WHERE database = '\(escape(db))' AND table = '\(escape(table))'
+ ORDER BY position
+ """)
+
+ // Fallback PK set from system.tables.primary_key when is_in_primary_key is unavailable.
+ var pkSet: Set<String> = []
+ if !hasPKFlag {
+ let pkResult = try? await executeRaw(sql: """
+ SELECT primary_key FROM system.tables
+ WHERE database = '\(escape(db))' AND name = '\(escape(table))'
+ """)
+ if let raw = pkResult?.rows.first?.first?.stringValue {
+ pkSet = Set(raw.split(separator: ",").map {
+ $0.trimmingCharacters(in: .whitespaces)
+ })
+ }
+ }
+
+ return r.rows.enumerated().compactMap { idx, row -> ColumnInfo? in
+ guard let colName = row[0].stringValue,
+ let dataType = row[1].stringValue else { return nil }
+ let defKind = row[2].stringValue ?? ""
+ let defExpr = row[3].stringValue ?? ""
+ let comment = row[4].stringValue
+ let isPK = hasPKFlag ? (row[5].intValue == 1) : pkSet.contains(colName)
+
+ let isNullable = dataType.hasPrefix("Nullable(")
+ let defaultValue: String?
+ if defExpr.isEmpty {
+ defaultValue = nil
+ } else if defKind.isEmpty {
+ defaultValue = defExpr
+ } else {
+ defaultValue = "\(defKind) \(defExpr)"
+ }
+
+ return ColumnInfo(
+ name: colName,
+ dataType: dataType,
+ isNullable: isNullable,
+ defaultValue: defaultValue,
+ isPrimaryKey: isPK,
+ isAutoIncrement: false,
+ comment: (comment?.isEmpty == true) ? nil : comment,
+ ordinalPosition: idx + 1,
+ characterMaxLength: nil
+ )
+ }
+ }
+
+ /// `is_in_primary_key` was added in 21.3. Cache the check based on serverVersionCache.
+ private func supportsIsInPrimaryKey() -> Bool {
+ guard let v = serverVersionCache else { return true } // optimistic for unknown
+ let parts = v.split(separator: ".").prefix(2).compactMap { Int($0) }
+ guard parts.count == 2 else { return true }
+ let (major, minor) = (parts[0], parts[1])
+ if major > 21 { return true }
+ if major == 21 && minor >= 3 { return true }
+ return false
+ }
+
+ func listIndexes(table: String, schema: String?) async throws -> [IndexInfo] {
+ let db = try resolveDB(schema)
+ let r = try? await executeRaw(sql: """
+ SELECT name, expr, type FROM system.data_skipping_indices
+ WHERE database = '\(escape(db))' AND table = '\(escape(table))'
+ ORDER BY name
+ """)
+ return (r?.rows ?? []).compactMap { row -> IndexInfo? in
+ guard let name = row[0].stringValue else { return nil }
+ let expr = row.count > 1 ? (row[1].stringValue ?? "") : ""
+ let type = row.count > 2 ? row[2].stringValue : nil
+ return IndexInfo(
+ name: name,
+ columns: [expr],
+ isUnique: false,
+ type: type,
+ tableName: table
+ )
+ }
+ }
+
+ func listForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo] {
+ [] // ClickHouse has no foreign keys.
+ }
+
+ func listFunctions(schema: String?) async throws -> [String] {
+ let r = try? await executeRaw(sql: """
+ SELECT name FROM system.functions
+ WHERE is_aggregate = 0 AND origin = 'SQLUserDefined'
+ ORDER BY name
+ """)
+ return (r?.rows ?? []).compactMap { $0.first?.stringValue }
+ }
+
+ func getFunctionSource(name: String, schema: String?) async throws -> String {
+ let r = try await executeRaw(sql: """
+ SELECT create_query FROM system.functions WHERE name = '\(escape(name))'
+ """)
+ return r.rows.first?.first?.stringValue ?? ""
+ }
+
+ // MARK: - Data Manipulation
+
+ func insertRow(table: String, schema: String?, values: [String: RowValue]) async throws -> QueryResult {
+ let d = SQLDialect.clickhouse
+ let db = try resolveDB(schema)
+ let qualified = qualifiedName(db: db, table: table, dialect: d)
+ let keys = values.keys.sorted()
+ let cols = keys.map { d.quoteIdentifier($0) }.joined(separator: ", ")
+ let vals = keys.map { inlineValue(values[$0] ?? .null) }.joined(separator: ", ")
+ return try await executeRaw(sql: "INSERT INTO \(qualified) (\(cols)) VALUES (\(vals))")
+ }
+
+ func updateRow(table: String, schema: String?, set: [String: RowValue], where whereClause: [String: RowValue]) async throws -> QueryResult {
+ // ClickHouse uses ALTER TABLE ... UPDATE (async mutation).
+ let d = SQLDialect.clickhouse
+ let db = try resolveDB(schema)
+ 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)")
+ }
+
+ func deleteRow(table: String, schema: String?, where whereClause: [String: RowValue]) async throws -> QueryResult {
+ let d = SQLDialect.clickhouse
+ let db = try resolveDB(schema)
+ 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)")
+ }
+
+ // MARK: - Transactions (no-op — ClickHouse has no traditional transactions)
+
+ func beginTransaction() async throws {}
+ func commitTransaction() async throws {}
+ func rollbackTransaction() async throws {}
+
+ // MARK: - Pagination
+
+ func fetchRows(
+ table: String,
+ schema: String?,
+ columns: [String]?,
+ where filter: FilterExpression?,
+ orderBy: [QuerySortDescriptor]?,
+ limit: Int,
+ offset: Int
+ ) async throws -> QueryResult {
+ let d = SQLDialect.clickhouse
+ let db = try resolveDB(schema)
+ let qualified = qualifiedName(db: db, table: table, dialect: d)
+ let colList = columns?.map { d.quoteIdentifier($0) }.joined(separator: ", ") ?? "*"
+
+ var sql = "SELECT \(colList) FROM \(qualified)"
+ if let filter, !filter.conditions.isEmpty {
+ sql += " WHERE \(filter.toSQL(dialect: d))"
+ }
+ if let orderBy, !orderBy.isEmpty {
+ sql += " ORDER BY " + orderBy.map { $0.toSQL(dialect: d) }.joined(separator: ", ")
+ }
+ sql += " LIMIT \(limit) OFFSET \(offset)"
+ return try await executeRaw(sql: sql)
+ }
+
+ // MARK: - Database management
+
+ func createDatabase(name: String) async throws {
+ let quoted = SQLDialect.clickhouse.quoteIdentifier(name)
+ _ = try await executeRaw(sql: "CREATE DATABASE IF NOT EXISTS \(quoted)")
+ }
+
+ func dropDatabase(name: String) async throws {
+ let quoted = SQLDialect.clickhouse.quoteIdentifier(name)
+ _ = try await executeRaw(sql: "DROP DATABASE \(quoted)")
+ }
+
+ // MARK: - Info
+
+ func serverVersion() async throws -> String {
+ if let cached = serverVersionCache { return cached }
+ return try await fetchServerVersion()
+ }
+
+ func currentDatabase() async throws -> String? {
+ stateLock.lock()
+ let cached = currentDB
+ stateLock.unlock()
+ if let cached, !cached.isEmpty { return cached }
+ let r = try await executeRaw(sql: "SELECT currentDatabase()")
+ let name = r.rows.first?.first?.stringValue
+ if let name, !name.isEmpty {
+ stateLock.lock()
+ currentDB = name
+ stateLock.unlock()
+ }
+ return name
+ }
+
+ private func fetchServerVersion() async throws -> String {
+ let r = try await executeRaw(sql: "SELECT version()")
+ let v = r.rows.first?.first?.stringValue ?? "ClickHouse"
+ serverVersionCache = v
+ return v
+ }
+
+ // MARK: - SchemaInspectable
+
+ func fullSchemaSnapshot(database: String?) async throws -> SchemaSnapshot {
+ let db: String
+ if let explicit = database, !explicit.isEmpty {
+ db = explicit
+ } else {
+ db = (try await currentDatabase()) ?? "default"
+ }
+ let tables = try await listTables(schema: db)
+ let descs: [TableDescription] = try await withThrowingTaskGroup(of: TableDescription.self) { group in
+ for t in tables {
+ let name = t.name
+ group.addTask { try await self.describeTable(name: name, schema: db) }
+ }
+ var results: [TableDescription] = []
+ for try await desc in group { results.append(desc) }
+ return results
+ }
+ let views = try await listViews(schema: db)
+ let schemaInfo = SchemaInfo(name: db, tables: descs, views: views, functions: [], enums: [])
+ return SchemaSnapshot(databaseName: db, databaseType: .clickhouse, schemas: [schemaInfo], capturedAt: Date())
+ }
+
+ func columnStatistics(table: String, schema: String?, sampleSize: Int) async throws -> [ColumnStatistics] {
+ let db = try resolveDB(schema)
+ let cols = try await describeColumns(table: table, schema: db)
+ let d = SQLDialect.clickhouse
+ let qualified = qualifiedName(db: db, table: table, dialect: d)
+ var stats: [ColumnStatistics] = []
+ for col in cols {
+ let q = d.quoteIdentifier(col.name)
+ let r = try? await executeRaw(sql: """
+ SELECT count(DISTINCT \(q)),
+ countIf(\(q) IS NULL) / greatest(count(), 1),
+ toString(min(\(q))),
+ toString(max(\(q)))
+ FROM (SELECT \(q) FROM \(qualified) LIMIT \(sampleSize)) AS sample
+ """)
+ if let row = r?.rows.first {
+ stats.append(ColumnStatistics(
+ columnName: col.name,
+ distinctCount: row[0].intValue,
+ nullRatio: row[1].doubleValue,
+ topValues: nil,
+ minValue: row[2].stringValue,
+ maxValue: row[3].stringValue
+ ))
+ }
+ }
+ return stats
+ }
+
+ func tableRowCount(table: String, schema: String?) async throws -> Int {
+ let db = try resolveDB(schema)
+ let r = try await executeRaw(sql: """
+ SELECT total_rows FROM system.tables
+ WHERE database = '\(escape(db))' AND name = '\(escape(table))'
+ """)
+ return r.rows.first?.first?.intValue ?? 0
+ }
+
+ func tableSizeBytes(table: String, schema: String?) async throws -> Int64? {
+ let db = try resolveDB(schema)
+ let r = try await executeRaw(sql: """
+ SELECT total_bytes FROM system.tables
+ WHERE database = '\(escape(db))' AND name = '\(escape(table))'
+ """)
+ if let v = r.rows.first?.first?.intValue { return Int64(v) }
+ return nil
+ }
+
+ func queryStatistics() async throws -> [QueryStatisticsEntry] { [] }
+
+ func primaryKeyColumns(table: String, schema: String?) async throws -> [String] {
+ let db = try resolveDB(schema)
+ if supportsIsInPrimaryKey() {
+ let r = try await executeRaw(sql: """
+ SELECT name FROM system.columns
+ WHERE database = '\(escape(db))' AND table = '\(escape(table))' AND is_in_primary_key = 1
+ ORDER BY position
+ """)
+ return r.rows.compactMap { $0.first?.stringValue }
+ } else {
+ let r = try await executeRaw(sql: """
+ SELECT primary_key FROM system.tables
+ WHERE database = '\(escape(db))' AND name = '\(escape(table))'
+ """)
+ guard let raw = r.rows.first?.first?.stringValue, !raw.isEmpty else { return [] }
+ return raw.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }
+ }
+ }
+
+ // MARK: - Helpers
+
+ private func resolveDB(_ schema: String?) throws -> String {
+ if let schema, !schema.isEmpty { return schema }
+ stateLock.lock()
+ let cur = currentDB
+ stateLock.unlock()
+ return cur ?? "default"
+ }
+
+ private func qualifiedName(db: String, table: String, dialect: SQLDialect) -> String {
+ "\(dialect.quoteIdentifier(db)).\(dialect.quoteIdentifier(table))"
+ }
+
+ private func parseUseStatement(_ sql: String) -> String {
+ // Handles: USE dbname, USE `dbname`, USE "dbname"; optional trailing ';'
+ let after = sql.dropFirst(4).trimmingCharacters(in: .whitespacesAndNewlines)
+ let stripped = after.trimmingCharacters(in: CharacterSet(charactersIn: "`\"'; "))
+ return stripped
+ }
+
+ private func detectQueryType(_ upper: String) -> QueryType {
+ if upper.hasPrefix("SELECT") || upper.hasPrefix("WITH") || upper.hasPrefix("EXPLAIN") || upper.hasPrefix("SHOW") || upper.hasPrefix("DESCRIBE") || upper.hasPrefix("DESC ") { return .select }
+ if upper.hasPrefix("INSERT") { return .insert }
+ if upper.hasPrefix("UPDATE") || upper.hasPrefix("ALTER TABLE") && upper.contains(" UPDATE ") { return .update }
+ if upper.hasPrefix("DELETE") || upper.hasPrefix("ALTER TABLE") && upper.contains(" DELETE ") { return .delete }
+ if upper.hasPrefix("CREATE") || upper.hasPrefix("ALTER") || upper.hasPrefix("DROP") || upper.hasPrefix("TRUNCATE") || upper.hasPrefix("RENAME") { return .ddl }
+ return .other
+ }
+
+ private func escape(_ s: String) -> String {
+ s.replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "'", with: "\\'")
+ }
+
+ private func inlineValue(_ value: RowValue) -> String {
+ switch value {
+ case .null: return "NULL"
+ case .string(let v): return "'\(escape(v))'"
+ case .integer(let v): return "\(v)"
+ case .double(let v): return "\(v)"
+ case .boolean(let v): return v ? "1" : "0"
+ case .date(let v):
+ let fmt = DateFormatter()
+ fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
+ fmt.timeZone = TimeZone(identifier: "UTC")
+ return "'\(fmt.string(from: v))'"
+ case .uuid(let v): return "'\(v.uuidString)'"
+ case .json(let v): return "'\(escape(v))'"
+ case .data: return "NULL"
+ case .array(let items):
+ let parts = items.map { inlineValue($0) }.joined(separator: ", ")
+ return "[\(parts)]"
+ }
+ }
+}
diff --git a/macos/Data/Adapters/ClickHouse/ClickHouseHTTPClient.swift b/macos/Data/Adapters/ClickHouse/ClickHouseHTTPClient.swift
new file mode 100644
index 0000000..02d3573
--- /dev/null
+++ b/macos/Data/Adapters/ClickHouse/ClickHouseHTTPClient.swift
@@ -0,0 +1,236 @@
+// ClickHouseHTTPClient.swift
+// Gridex
+//
+// HTTP client for ClickHouse. Speaks the ClickHouse HTTP interface
+// (ports 8123/8443) using URLSession. Supports plain HTTP, HTTPS with a
+// pinned CA, trust-on-first-use, and mutual TLS via a PKCS#12 bundle.
+
+import Foundation
+
+struct ClickHouseHTTPClient: Sendable {
+ let scheme: String // "http" or "https"
+ let host: String
+ let port: Int
+ let username: String
+ let password: String
+ let defaultDatabase: String?
+ private let session: URLSession
+
+ init(
+ host: String,
+ port: Int,
+ username: String,
+ password: String,
+ defaultDatabase: String?,
+ useTLS: Bool,
+ sslCACertPath: String?,
+ sslClientBundlePath: String?
+ ) {
+ self.scheme = useTLS ? "https" : "http"
+ self.host = host
+ self.port = port
+ self.username = username
+ self.password = password
+ self.defaultDatabase = defaultDatabase
+
+ let cfg = URLSessionConfiguration.ephemeral
+ cfg.timeoutIntervalForRequest = 60
+ cfg.timeoutIntervalForResource = 600
+ cfg.httpShouldUsePipelining = false
+ cfg.waitsForConnectivity = false
+ cfg.httpAdditionalHeaders = ["Accept": "application/json"]
+
+ let delegate = ClickHouseTLSDelegate(
+ useTLS: useTLS,
+ caCertPath: sslCACertPath,
+ clientBundlePath: sslClientBundlePath
+ )
+ self.session = URLSession(configuration: cfg, delegate: delegate, delegateQueue: nil)
+ }
+
+ /// Issue a ClickHouse query. `sql` is appended verbatim to the request body.
+ /// `database` overrides the default database for this request.
+ /// `queryId` is sent via `X-ClickHouse-Query-Id` to enable `KILL QUERY`.
+ func send(
+ sql: String,
+ database: String? = nil,
+ queryId: String? = nil,
+ readOnly: Bool = false
+ ) async throws -> ClickHouseHTTPResponse {
+ var components = URLComponents()
+ components.scheme = scheme
+ components.host = host
+ components.port = port
+ components.path = "/"
+ var items: [URLQueryItem] = []
+ if let db = database ?? defaultDatabase, !db.isEmpty {
+ items.append(URLQueryItem(name: "database", value: db))
+ }
+ if readOnly {
+ // readonly=2 allows SETTINGS, readonly=1 is strict. Use 2 for SELECT introspection.
+ items.append(URLQueryItem(name: "readonly", value: "2"))
+ }
+ // Ask the server for row-count summary in headers so non-SELECT statements
+ // can report `rowsAffected` even with FORMAT Null.
+ items.append(URLQueryItem(name: "send_progress_in_http_headers", value: "0"))
+ components.queryItems = items.isEmpty ? nil : items
+
+ guard let url = components.url else {
+ throw GridexError.queryExecutionFailed("Invalid ClickHouse URL")
+ }
+
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.httpBody = sql.data(using: .utf8)
+ request.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
+ if !username.isEmpty {
+ request.setValue(username, forHTTPHeaderField: "X-ClickHouse-User")
+ }
+ if !password.isEmpty {
+ request.setValue(password, forHTTPHeaderField: "X-ClickHouse-Key")
+ }
+ if let queryId, !queryId.isEmpty {
+ request.setValue(queryId, forHTTPHeaderField: "X-ClickHouse-Query-Id")
+ }
+
+ let (data, response): (Data, URLResponse)
+ do {
+ (data, response) = try await session.data(for: request)
+ } catch {
+ throw GridexError.connectionFailed(underlying: error)
+ }
+
+ guard let http = response as? HTTPURLResponse else {
+ throw GridexError.queryExecutionFailed("ClickHouse returned a non-HTTP response")
+ }
+
+ if http.statusCode >= 400 {
+ let body = String(data: data, encoding: .utf8) ?? "HTTP \(http.statusCode)"
+ throw GridexError.queryExecutionFailed(body.trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+
+ return ClickHouseHTTPResponse(status: http.statusCode, body: data, headers: http.allHeaderFields)
+ }
+}
+
+struct ClickHouseHTTPResponse: Sendable {
+ let status: Int
+ let body: Data
+ let headers: [AnyHashable: Any]
+
+ /// ClickHouse writes progress as JSON in this response header on mutating statements.
+ var summary: [String: String]? {
+ guard let raw = headers["X-ClickHouse-Summary"] as? String,
+ let data = raw.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: String]
+ else { return nil }
+ return json
+ }
+
+ var writtenRows: Int {
+ Int(summary?["written_rows"] ?? "0") ?? 0
+ }
+}
+
+// MARK: - TLS delegate
+
+/// URLSessionDelegate that pins a custom CA and/or presents a client identity.
+/// Gracefully falls back to the system trust store if no CA is provided.
+final class ClickHouseTLSDelegate: NSObject, URLSessionDelegate, Sendable {
+ private let useTLS: Bool
+ private let caCertificates: [SecCertificate]
+ private let clientIdentity: SecIdentity?
+
+ init(useTLS: Bool, caCertPath: String?, clientBundlePath: String?) {
+ self.useTLS = useTLS
+ self.caCertificates = Self.loadCACertificates(path: caCertPath)
+ self.clientIdentity = Self.loadClientIdentity(path: clientBundlePath)
+ super.init()
+ }
+
+ func urlSession(
+ _ session: URLSession,
+ didReceive challenge: URLAuthenticationChallenge,
+ completionHandler: @Sendable @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
+ ) {
+ let method = challenge.protectionSpace.authenticationMethod
+
+ if method == NSURLAuthenticationMethodServerTrust {
+ guard let serverTrust = challenge.protectionSpace.serverTrust else {
+ completionHandler(.performDefaultHandling, nil)
+ return
+ }
+ if !caCertificates.isEmpty {
+ SecTrustSetAnchorCertificates(serverTrust, caCertificates as CFArray)
+ SecTrustSetAnchorCertificatesOnly(serverTrust, true)
+ var error: CFError?
+ let ok = SecTrustEvaluateWithError(serverTrust, &error)
+ if ok {
+ completionHandler(.useCredential, URLCredential(trust: serverTrust))
+ } else {
+ completionHandler(.cancelAuthenticationChallenge, nil)
+ }
+ } else {
+ completionHandler(.performDefaultHandling, nil)
+ }
+ return
+ }
+
+ if method == NSURLAuthenticationMethodClientCertificate, let identity = clientIdentity {
+ let credential = URLCredential(identity: identity, certificates: nil, persistence: .forSession)
+ completionHandler(.useCredential, credential)
+ return
+ }
+
+ completionHandler(.performDefaultHandling, nil)
+ }
+
+ // MARK: - Loading
+
+ private static func loadCACertificates(path: String?) -> [SecCertificate] {
+ guard let path, !path.isEmpty,
+ let data = try? Data(contentsOf: URL(fileURLWithPath: path))
+ else { return [] }
+
+ // Try DER first
+ if let cert = SecCertificateCreateWithData(nil, data as CFData) {
+ return [cert]
+ }
+
+ // Fall back to PEM — may contain one or more BEGIN CERTIFICATE blocks.
+ guard let text = String(data: data, encoding: .utf8) else { return [] }
+ var certs: [SecCertificate] = []
+ let blocks = text.components(separatedBy: "-----BEGIN CERTIFICATE-----")
+ for block in blocks.dropFirst() {
+ guard let endRange = block.range(of: "-----END CERTIFICATE-----") else { continue }
+ let base64 = block[..<endRange.lowerBound]
+ .replacingOccurrences(of: "\n", with: "")
+ .replacingOccurrences(of: "\r", with: "")
+ .replacingOccurrences(of: " ", with: "")
+ if let der = Data(base64Encoded: base64),
+ let cert = SecCertificateCreateWithData(nil, der as CFData) {
+ certs.append(cert)
+ }
+ }
+ return certs
+ }
+
+ /// Load a PKCS#12 bundle (.p12/.pfx) containing the client certificate + private key.
+ /// The bundle must be exported with an empty passphrase — separate PEM files are not
+ /// supported by URLSession's client-identity API on macOS without keychain staging.
+ private static func loadClientIdentity(path: String?) -> SecIdentity? {
+ guard let path, !path.isEmpty,
+ let data = try? Data(contentsOf: URL(fileURLWithPath: path))
+ else { return nil }
+
+ let options: [String: Any] = [kSecImportExportPassphrase as String: ""]
+ var rawItems: CFArray?
+ let status = SecPKCS12Import(data as CFData, options as CFDictionary, &rawItems)
+ guard status == errSecSuccess,
+ let items = rawItems as? [[String: Any]],
+ let first = items.first,
+ let identity = first[kSecImportItemIdentity as String]
+ else { return nil }
+ return (identity as! SecIdentity)
+ }
+}
diff --git a/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swift b/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swift
index 0d0baab..5d399de 100644
--- a/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swift
+++ b/macos/Presentation/Views/ConnectionForm/ConnectionFormPanel.swift
@@ -149,6 +149,7 @@ final class ConnectionFormPanel {
case .redis: RedisAdapter()
case .mongodb: MongoDBAdapter()
case .mssql: MSSQLAdapter()
+ case .clickhouse: ClickHouseAdapter()
}
let sshService = appState.container.sshTunnelService
diff --git a/macos/Presentation/Views/DataGrid/CreateTableView.swift b/macos/Presentation/Views/DataGrid/CreateTableView.swift
index a4c6cf5..e62c47e 100644
--- a/macos/Presentation/Views/DataGrid/CreateTableView.swift
+++ b/macos/Presentation/Views/DataGrid/CreateTableView.swift
@@ -49,6 +49,7 @@ struct CreateTableView: View {
private var defaultSchema: String {
switch appState.activeAdapter?.databaseType {
case .mssql: return "dbo"
+ case .clickhouse: return appState.currentDatabaseName ?? "default"
default: return "public"
}
}
@@ -77,6 +78,7 @@ struct CreateTableView: View {
case .mysql: idType = "int"
case .sqlite: idType = "INTEGER"
case .mssql: idType = "INT"
+ case .clickhouse: idType = "UInt64"
default: idType = "int"
}
if columns.count == 1 && columns[0].dataType == "int4" {
@@ -840,6 +842,7 @@ struct CreateTableView: View {
case .mysql: return "varchar(255)"
case .sqlite: return "TEXT"
case .mssql: return "NVARCHAR(255)"
+ case .clickhouse: return "String"
case .redis: return "string"
case .mongodb: return "string"
}
@@ -855,11 +858,32 @@ struct CreateTableView: View {
case .mysql: cachedDataTypes = mysqlDataTypes
case .sqlite: cachedDataTypes = sqliteDataTypes
case .mssql: cachedDataTypes = mssqlDataTypes
+ case .clickhouse: cachedDataTypes = clickhouseDataTypes
case .redis: cachedDataTypes = ["string", "list", "set", "zset", "hash", "stream"]
case .mongodb: cachedDataTypes = ["string", "integer", "double", "boolean", "date", "objectId", "document", "array"]
}
}
+ /// ClickHouse data types grouped by family. Nullable/Array wrappers are applied
+ /// per-column by the user (the form doesn't try to auto-wrap).
+ private var clickhouseDataTypes: [String] {
+ [
+ // Integers
+ "UInt8", "UInt16", "UInt32", "UInt64", "UInt128", "UInt256",
+ "Int8", "Int16", "Int32", "Int64", "Int128", "Int256",
+ // Floats + decimals
+ "Float32", "Float64", "Decimal(18, 4)", "Decimal(38, 4)", "Decimal(76, 4)",
+ // Strings
+ "String", "FixedString(32)", "UUID",
+ // Date/time
+ "Date", "Date32", "DateTime", "DateTime64(3)", "DateTime64(6)",
+ // Other
+ "Boolean", "IPv4", "IPv6", "JSON",
+ // Common wrappers (users can edit the inner type)
+ "Nullable(String)", "Array(String)", "Array(UInt64)", "Map(String, String)",
+ ]
+ }
+
/// SQL Server data types ordered by category (exact numerics → approximate
/// numerics → date/time → char strings → unicode strings → binary → other).
/// Modern variants (VARCHAR(MAX), NVARCHAR(MAX), VARBINARY(MAX)) replace
diff --git a/macos/Presentation/Views/DataGrid/DataGridView.swift b/macos/Presentation/Views/DataGrid/DataGridView.swift
index b484439..d8b9708 100644
--- a/macos/Presentation/Views/DataGrid/DataGridView.swift
+++ b/macos/Presentation/Views/DataGrid/DataGridView.swift
@@ -2733,6 +2733,15 @@ struct InlineStructureView: View {
"UNIQUEIDENTIFIER", "XML", "JSON", "ROWVERSION", "HIERARCHYID",
"GEOGRAPHY", "GEOMETRY", "SQL_VARIANT",
]
+ case .clickhouse: base = [
+ "UInt8", "UInt16", "UInt32", "UInt64", "UInt128", "UInt256",
+ "Int8", "Int16", "Int32", "Int64", "Int128", "Int256",
+ "Float32", "Float64", "Decimal(18, 4)", "Decimal(38, 4)", "Decimal(76, 4)",
+ "String", "FixedString(32)", "UUID",
+ "Date", "Date32", "DateTime", "DateTime64(3)", "DateTime64(6)",
+ "Boolean", "IPv4", "IPv6", "JSON",
+ "Nullable(String)", "Array(String)", "Array(UInt64)", "Map(String, String)",
+ ]
case .redis: base = ["string", "list", "set", "zset", "hash", "stream"]
case .mongodb: base = ["string", "integer", "double", "boolean", "date", "objectId", "document", "array"]
}
diff --git a/macos/Presentation/Views/ERDiagram/ERDiagramView.swift b/macos/Presentation/Views/ERDiagram/ERDiagramView.swift
index 26a86a3..4e2c9b2 100644
--- a/macos/Presentation/Views/ERDiagram/ERDiagramView.swift
+++ b/macos/Presentation/Views/ERDiagram/ERDiagramView.swift
@@ -46,6 +46,24 @@ struct ERDiagramView: View {
}
.padding(12)
}
+
+ // ClickHouse has no foreign keys — flag the diagram so users don't
+ // mistake the missing relations for a bug.
+ if appState.activeAdapter?.databaseType == .clickhouse && !viewModel.isLoading && !viewModel.tables.isEmpty {
+ VStack {
+ Spacer()
+ HStack(spacing: 6) {
+ Image(systemName: "info.circle.fill")
+ Text("ClickHouse has no foreign keys — showing tables only.")
+ .font(.system(size: 11))
+ }
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8))
+ .padding(12)
+ }
+ }
}
.background(Color(nsColor: .controlBackgroundColor))
.task {
diff --git a/macos/Presentation/Views/Main/MainView.swift b/macos/Presentation/Views/Main/MainView.swift
index 170973b..5417581 100644
--- a/macos/Presentation/Views/Main/MainView.swift
+++ b/macos/Presentation/Views/Main/MainView.swift
@@ -842,6 +842,8 @@ struct DatabaseTypeIcon: View {
return LinearGradient(colors: [Color(red: 0.30, green: 0.65, blue: 0.35), Color(red: 0.20, green: 0.50, blue: 0.25)], startPoint: .top, endPoint: .bottom)
case .mssql:
return LinearGradient(colors: [Color(red: 0.80, green: 0.20, blue: 0.40), Color(red: 0.65, green: 0.10, blue: 0.30)], startPoint: .top, endPoint: .bottom)
+ case .clickhouse:
+ return LinearGradient(colors: [Color(red: 1.00, green: 0.85, blue: 0.00), Color(red: 0.85, green: 0.65, blue: 0.00)], startPoint: .top, endPoint: .bottom)
}
}
@@ -853,6 +855,7 @@ struct DatabaseTypeIcon: View {
case .redis: return "Rd"
case .mongodb: return "Mg"
case .mssql: return "MS"
+ case .clickhouse: return "CH"
}
}
}
@@ -1678,7 +1681,7 @@ struct NewDatabaseSheet: View {
switch adapter.databaseType {
case .postgresql: return ["Default", "UTF8", "LATIN1", "SQL_ASCII"]
case .mysql: return ["Default", "utf8mb4", "utf8", "latin1"]
- case .sqlite, .redis, .mongodb, .mssql: return ["Default"]
+ case .sqlite, .redis, .mongodb, .mssql, .clickhouse: return ["Default"]
}
}
@@ -1687,7 +1690,7 @@ struct NewDatabaseSheet: View {
switch adapter.databaseType {
case .postgresql: return ["Default", "C", "POSIX", "en_US.UTF-8"]
case .mysql: return ["Default", "utf8mb4_unicode_ci", "utf8mb4_general_ci", "utf8_general_ci"]
- case .sqlite, .redis, .mongodb, .mssql: return ["Default"]
+ case .sqlite, .redis, .mongodb, .mssql, .clickhouse: return ["Default"]
}
}
@@ -1776,6 +1779,8 @@ struct NewDatabaseSheet: View {
break // SQLite/Redis don't support CREATE DATABASE
case .mssql:
break // SQL Server: use plain CREATE DATABASE without options for MVP
+ case .clickhouse:
+ break // ClickHouse: use plain CREATE DATABASE (options go via SETTINGS)
case .mongodb:
// MongoDB: use the adapter's createDatabase method
skipExecuteRaw = true
diff --git a/macos/Presentation/Views/Sidebar/BackupRestorePanel.swift b/macos/Presentation/Views/Sidebar/BackupRestorePanel.swift
index ede9b3b..2c9972f 100644
--- a/macos/Presentation/Views/Sidebar/BackupRestorePanel.swift
+++ b/macos/Presentation/Views/Sidebar/BackupRestorePanel.swift
@@ -631,6 +631,7 @@ struct BackupRestoreView: View {
case .redis: return .red
case .mongodb: return .green
case .mssql: return Color(red: 0.8, green: 0.2, blue: 0.4)
+ case .clickhouse: return Color(red: 1.0, green: 0.85, blue: 0.0)
}
}
@@ -642,6 +643,7 @@ struct BackupRestoreView: View {
case .redis: return "Rd"
case .mongodb: return "Mg"
case .mssql: return "MS"
+ case .clickhouse: return "CH"
}
}
@@ -673,6 +675,7 @@ struct BackupRestoreView: View {
case .redis: RedisAdapter()
case .mongodb: MongoDBAdapter()
case .mssql: MSSQLAdapter()
+ case .clickhouse: ClickHouseAdapter()
}
do {
diff --git a/macos/Presentation/Views/Sidebar/SidebarView.swift b/macos/Presentation/Views/Sidebar/SidebarView.swift
index 962eca1..0b09990 100644
--- a/macos/Presentation/Views/Sidebar/SidebarView.swift
+++ b/macos/Presentation/Views/Sidebar/SidebarView.swift
@@ -891,6 +891,7 @@ struct NewTableSheet: View {
case .mysql: idType = "int AUTO_INCREMENT PRIMARY KEY"
case .sqlite: idType = "INTEGER PRIMARY KEY AUTOINCREMENT"
case .mssql: idType = "INT IDENTITY(1,1) PRIMARY KEY"
+ case .clickhouse: idType = "UInt64) ENGINE = MergeTree ORDER BY (id" // NB: no FK/IDENTITY — MergeTree requires an ORDER BY
case .redis, .mongodb: return // Non-SQL databases don't support CREATE TABLE
}
diff --git a/macos/Presentation/Views/TableList/TableListView.swift b/macos/Presentation/Views/TableList/TableListView.swift
index 8ee041c..5556753 100644
--- a/macos/Presentation/Views/TableList/TableListView.swift
+++ b/macos/Presentation/Views/TableList/TableListView.swift
@@ -191,6 +191,20 @@ final class TableListViewModel: ObservableObject {
WHERE TABLE_SCHEMA = '\(schema ?? "dbo")' AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME
""")
+ case .clickhouse:
+ let db: String
+ if let schema, !schema.isEmpty {
+ db = schema
+ } else {
+ db = (try? await adapter.currentDatabase()) ?? "default"
+ }
+ let safe = db.replacingOccurrences(of: "'", with: "\\'")
+ result = try await adapter.executeRaw(sql: """
+ SELECT name, total_rows, total_bytes, engine
+ FROM system.tables
+ WHERE database = '\(safe)' AND engine NOT LIKE '%View'
+ ORDER BY name
+ """)
}
columns = result.columns.map(\.name)
diff --git a/macos/Services/Export/BackupService.swift b/macos/Services/Export/BackupService.swift
index bdb122a..448b04c 100644
--- a/macos/Services/Export/BackupService.swift
+++ b/macos/Services/Export/BackupService.swift
@@ -50,6 +50,7 @@ enum BackupFormat: String, CaseIterable, Sendable {
case .mssql: return [.bak]
case .mongodb: return [.ndjson]
case .redis: return [.redisJSON]
+ case .clickhouse: return [.sql]
}
}
}
@@ -108,6 +109,11 @@ actor BackupService {
return BackupResult(success: false, outputPath: nil, errorMessage: "SQL Server adapter required for backup", duration: 0, fileSize: nil)
}
return await mssqlBackup(adapter: mssql, database: database, to: outputURL, start: start)
+ case .clickhouse:
+ guard let ch = adapter as? ClickHouseAdapter else {
+ return BackupResult(success: false, outputPath: nil, errorMessage: "ClickHouse adapter required for backup", duration: 0, fileSize: nil)
+ }
+ return await clickhouseBackup(adapter: ch, database: database, to: outputURL, start: start)
}
}
@@ -146,6 +152,11 @@ actor BackupService {
return BackupResult(success: false, outputPath: nil, errorMessage: "SQL Server adapter required for restore", duration: 0, fileSize: nil)
}
return await mssqlRestore(adapter: mssql, database: database, from: inputURL, start: start)
+ case .clickhouse:
+ guard let ch = adapter as? ClickHouseAdapter else {
+ return BackupResult(success: false, outputPath: nil, errorMessage: "ClickHouse adapter required for restore", duration: 0, fileSize: nil)
+ }
+ return await clickhouseRestore(adapter: ch, database: database, from: inputURL, start: start)
}
}
@@ -825,4 +836,112 @@ actor BackupService {
}
}
}
+
+ // MARK: - ClickHouse (pure Swift SQL dump via HTTP)
+
+ /// ClickHouse backup: emit `CREATE TABLE` + row-level `INSERT ... FORMAT Values`
+ /// statements for each table in the database. Views are skipped — they're
+ /// derived from their sources and will be recreated when the source tables exist.
+ private func clickhouseBackup(
+ adapter: ClickHouseAdapter,
+ database: String,
+ to outputURL: URL,
+ start: CFAbsoluteTime
+ ) async -> BackupResult {
+ do {
+ FileManager.default.createFile(atPath: outputURL.path, contents: nil)
+ guard let handle = try? FileHandle(forWritingTo: outputURL) else {
+ return BackupResult(success: false, outputPath: nil,
+ errorMessage: "Cannot create output file at \(outputURL.path)",
+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)
+ }
+ defer { try? handle.close() }
+
+ let header = "-- ClickHouse dump for database `\(database)` at \(ISO8601DateFormatter().string(from: Date()))\n\n"
+ if let data = header.data(using: .utf8) { try handle.write(contentsOf: data) }
+
+ let tables = try await adapter.listTables(schema: database)
+ for t in tables {
+ let ddlResult = try await adapter.executeRaw(
+ sql: "SHOW CREATE TABLE `\(database)`.`\(t.name)`"
+ )
+ let ddl = ddlResult.rows.first?.first?.stringValue ?? ""
+ if !ddl.isEmpty {
+ let block = "\(ddl);\n\n"
+ if let data = block.data(using: .utf8) { try handle.write(contentsOf: data) }
+ }
+
+ // Row data via `FORMAT Values` → `(v1, v2), (v3, v4)...` for direct INSERT.
+ // Loads the whole result into memory — acceptable for v1.
+ let rowDump = try await adapter.executeRaw(
+ sql: "SELECT * FROM `\(database)`.`\(t.name)` FORMAT Values"
+ )
+ if let body = rowDump.rows.first?.first?.stringValue, !body.isEmpty {
+ let stmt = "INSERT INTO `\(database)`.`\(t.name)` VALUES \(body);\n\n"
+ if let data = stmt.data(using: .utf8) { try handle.write(contentsOf: data) }
+ }
+ }
+
+ let size = try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64
+ return BackupResult(
+ success: true, outputPath: outputURL.path, errorMessage: nil,
+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: size
+ )
+ } catch {
+ return BackupResult(
+ success: false, outputPath: nil,
+ errorMessage: "ClickHouse backup failed: \(error.localizedDescription)",
+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil
+ )
+ }
+ }
+
+ /// ClickHouse restore: split the dump on `;` and execute each statement.
+ /// Targets the selected database via `USE` first so unqualified identifiers work.
+ private func clickhouseRestore(
+ adapter: ClickHouseAdapter,
+ database: String,
+ from inputURL: URL,
+ start: CFAbsoluteTime
+ ) async -> BackupResult {
+ do {
+ let data = try Data(contentsOf: inputURL)
+ guard let content = String(data: data, encoding: .utf8) else {
+ return BackupResult(success: false, outputPath: nil,
+ errorMessage: "Invalid UTF-8 in backup file",
+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil)
+ }
+ _ = try await adapter.executeRaw(sql: "USE `\(database.replacingOccurrences(of: "`", with: "``"))`")
+
+ // Statement splitter: naive — splits on `;` at line ends, skipping lines that
+ // start with `--`. ClickHouse's VALUES bodies are emitted on a single line so
+ // a trailing `;` is always statement-terminating in the output of this dumper.
+ var statement = ""
+ for rawLine in content.components(separatedBy: "\n") {
+ let line = rawLine.trimmingCharacters(in: .whitespaces)
+ if line.hasPrefix("--") || line.isEmpty { continue }
+ statement += rawLine + "\n"
+ if line.hasSuffix(";") {
+ let trimmed = statement.trimmingCharacters(in: .whitespacesAndNewlines)
+ let sql = trimmed.hasSuffix(";") ? String(trimmed.dropLast()) : trimmed
+ if !sql.isEmpty {
+ _ = try await adapter.executeRaw(sql: sql)
+ }
+ statement = ""
+ }
+ }
+
+ let size = try? FileManager.default.attributesOfItem(atPath: inputURL.path)[.size] as? Int64
+ return BackupResult(
+ success: true, outputPath: nil, errorMessage: nil,
+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: size
+ )
+ } catch {
+ return BackupResult(
+ success: false, outputPath: nil,
+ errorMessage: "ClickHouse restore failed: \(error.localizedDescription)",
+ duration: CFAbsoluteTimeGetCurrent() - start, fileSize: nil
+ )
+ }
+ }
}
diff --git a/macos/Services/Import/DBeaverImporter.swift b/macos/Services/Import/DBeaverImporter.swift
index a5146a4..cde9b0a 100644
--- a/macos/Services/Import/DBeaverImporter.swift
+++ b/macos/Services/Import/DBeaverImporter.swift
@@ -126,6 +126,7 @@ struct DBeaverImporter {
if lower.contains("redis") { return .redis }
if lower.contains("mongo") { return .mongodb }
if lower.contains("sqlserver") || lower.contains("mssql") { return .mssql }
+ if lower.contains("clickhouse") { return .clickhouse }
return .postgresql
}
diff --git a/macos/Services/Import/DataGripImporter.swift b/macos/Services/Import/DataGripImporter.swift
index 4b40cfb..37d6a9c 100644
--- a/macos/Services/Import/DataGripImporter.swift
+++ b/macos/Services/Import/DataGripImporter.swift
@@ -169,6 +169,7 @@ private class DataGripXMLParser: NSObject, XMLParserDelegate {
if combined.contains("redis") { return .redis }
if combined.contains("mongo") { return .mongodb }
if combined.contains("sqlserver") || combined.contains("mssql") { return .mssql }
+ if combined.contains("clickhouse") { return .clickhouse }
return .postgresql
}
diff --git a/macos/Services/Import/NavicatImporter.swift b/macos/Services/Import/NavicatImporter.swift
index 7089a67..aab2462 100644
--- a/macos/Services/Import/NavicatImporter.swift
+++ b/macos/Services/Import/NavicatImporter.swift
@@ -205,6 +205,7 @@ private class NavicatNCXParser: NSObject, XMLParserDelegate {
if lower.contains("redis") { return .redis }
if lower.contains("mongo") { return .mongodb }
if lower.contains("sqlserver") || lower.contains("mssql") { return .mssql }
+ if lower.contains("clickhouse") { return .clickhouse }
if lower == "1" { return .mysql }
if lower == "2" { return .postgresql }
if lower == "3" { return .sqlite }
diff --git a/macos/Services/Import/TablePlusImporter.swift b/macos/Services/Import/TablePlusImporter.swift
index 97c6054..03d65f9 100644
--- a/macos/Services/Import/TablePlusImporter.swift
+++ b/macos/Services/Import/TablePlusImporter.swift
@@ -188,6 +188,7 @@ struct TablePlusImporter {
if lower.contains("redis") { return .redis }
if lower.contains("mongo") { return .mongodb }
if lower.contains("mssql") || lower.contains("sqlserver") { return .mssql }
+ if lower.contains("clickhouse") { return .clickhouse }
return .postgresql
}
}
diff --git a/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift b/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
index 0499315..c10cf77 100644
--- a/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
+++ b/macos/Services/MCP/Tools/Tier2/ExplainQueryTool.swift
@@ -51,6 +51,8 @@ struct ExplainQueryTool: MCPTool {
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:
return MCPToolResult(text: "EXPLAIN is not supported for \(config.databaseType.displayName) connections.", isError: true)
}
diff --git a/macos/Services/QueryEngine/ConnectionManager.swift b/macos/Services/QueryEngine/ConnectionManager.swift
index 4311a5d..5c02ed1 100644
--- a/macos/Services/QueryEngine/ConnectionManager.swift
+++ b/macos/Services/QueryEngine/ConnectionManager.swift
@@ -78,6 +78,7 @@ actor ConnectionManager {
case .redis: return RedisAdapter()
case .mongodb: return MongoDBAdapter()
case .mssql: return MSSQLAdapter()
+ case .clickhouse: return ClickHouseAdapter()
}
}
}