-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathClickHousePlugin.swift
More file actions
892 lines (770 loc) · 32.7 KB
/
ClickHousePlugin.swift
File metadata and controls
892 lines (770 loc) · 32.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//
// ClickHousePlugin.swift
// TablePro
//
import Foundation
import os
import TableProPluginKit
final class ClickHousePlugin: NSObject, TableProPlugin, DriverPlugin {
static let pluginName = "ClickHouse Driver"
static let pluginVersion = "1.0.0"
static let pluginDescription = "ClickHouse database support via HTTP interface"
static let capabilities: [PluginCapability] = [.databaseDriver]
static let databaseTypeId = "ClickHouse"
static let databaseDisplayName = "ClickHouse"
static let iconName = "bolt.fill"
static let defaultPort = 8123
// MARK: - UI/Capability Metadata
static let brandColorHex = "#FFD100"
static let supportsForeignKeys = false
static let systemDatabaseNames: [String] = ["information_schema", "INFORMATION_SCHEMA", "system"]
static let columnTypesByCategory: [String: [String]] = [
"Integer": [
"UInt8", "UInt16", "UInt32", "UInt64", "UInt128", "UInt256",
"Int8", "Int16", "Int32", "Int64", "Int128", "Int256"
],
"Float": ["Float32", "Float64", "Decimal", "Decimal32", "Decimal64", "Decimal128", "Decimal256"],
"String": ["String", "FixedString", "Enum8", "Enum16"],
"Date": ["Date", "Date32", "DateTime", "DateTime64"],
"Binary": [],
"Boolean": ["Bool"],
"JSON": ["JSON"],
"UUID": ["UUID"],
"Array": ["Array"],
"Map": ["Map"],
"Tuple": ["Tuple"],
"IP": ["IPv4", "IPv6"],
"Geo": ["Point", "Ring", "Polygon", "MultiPolygon"]
]
func createDriver(config: DriverConnectionConfig) -> any PluginDatabaseDriver {
ClickHousePluginDriver(config: config)
}
}
// MARK: - Error Types
private struct ClickHouseError: Error, PluginDriverError {
let message: String
var pluginErrorMessage: String { message }
static let notConnected = ClickHouseError(message: String(localized: "Not connected to database"))
static let connectionFailed = ClickHouseError(message: String(localized: "Failed to establish connection"))
}
// MARK: - Internal Query Result
private struct CHQueryResult {
let columns: [String]
let columnTypeNames: [String]
let rows: [[String?]]
let affectedRows: Int
let isTruncated: Bool
}
// MARK: - Plugin Driver
final class ClickHousePluginDriver: PluginDatabaseDriver, @unchecked Sendable {
private let config: DriverConnectionConfig
private var _serverVersion: String?
private let lock = NSLock()
private var session: URLSession?
private var currentTask: URLSessionDataTask?
private var _currentDatabase: String
private var _lastQueryId: String?
private static let logger = Logger(subsystem: "com.TablePro", category: "ClickHousePluginDriver")
private static let selectPrefixes: Set<String> = [
"SELECT", "SHOW", "DESCRIBE", "DESC", "EXISTS", "EXPLAIN", "WITH"
]
var serverVersion: String? { _serverVersion }
var supportsSchemas: Bool { false }
var supportsTransactions: Bool { false }
func beginTransaction() async throws {}
func commitTransaction() async throws {}
func rollbackTransaction() async throws {}
var currentSchema: String? { nil }
init(config: DriverConnectionConfig) {
self.config = config
self._currentDatabase = config.database
}
// MARK: - Connection
func connect() async throws {
let useTLS = config.additionalFields["sslMode"] != nil
&& config.additionalFields["sslMode"] != "Disabled"
let skipVerification = config.additionalFields["sslMode"] == "Required"
let urlConfig = URLSessionConfiguration.default
urlConfig.timeoutIntervalForRequest = 30
urlConfig.timeoutIntervalForResource = 300
lock.lock()
if skipVerification {
session = URLSession(configuration: urlConfig, delegate: InsecureTLSDelegate(), delegateQueue: nil)
} else {
session = URLSession(configuration: urlConfig)
}
lock.unlock()
do {
_ = try await executeRaw("SELECT 1")
} catch {
lock.lock()
session?.invalidateAndCancel()
session = nil
lock.unlock()
Self.logger.error("Connection test failed: \(error.localizedDescription)")
throw ClickHouseError.connectionFailed
}
if let result = try? await executeRaw("SELECT version()"),
let versionStr = result.rows.first?.first ?? nil {
_serverVersion = versionStr
}
Self.logger.debug("Connected to ClickHouse at \(self.config.host):\(self.config.port)")
}
func disconnect() {
lock.lock()
currentTask?.cancel()
currentTask = nil
session?.invalidateAndCancel()
session = nil
lock.unlock()
}
func ping() async throws {
_ = try await execute(query: "SELECT 1")
}
// MARK: - Query Execution
func execute(query: String) async throws -> PluginQueryResult {
let startTime = Date()
let queryId = UUID().uuidString
let result = try await executeRaw(query, queryId: queryId)
let executionTime = Date().timeIntervalSince(startTime)
return PluginQueryResult(
columns: result.columns,
columnTypeNames: result.columnTypeNames,
rows: result.rows,
rowsAffected: result.affectedRows,
executionTime: executionTime,
isTruncated: result.isTruncated
)
}
func executeParameterized(query: String, parameters: [String?]) async throws -> PluginQueryResult {
guard !parameters.isEmpty else {
return try await execute(query: query)
}
let startTime = Date()
let queryId = UUID().uuidString
let (convertedQuery, paramMap) = Self.buildClickHouseParams(query: query, parameters: parameters)
let result = try await executeRawWithParams(convertedQuery, params: paramMap, queryId: queryId)
let executionTime = Date().timeIntervalSince(startTime)
return PluginQueryResult(
columns: result.columns,
columnTypeNames: result.columnTypeNames,
rows: result.rows,
rowsAffected: result.affectedRows,
executionTime: executionTime,
isTruncated: result.isTruncated
)
}
func fetchRowCount(query: String) async throws -> Int {
let countQuery = "SELECT count() FROM (\(query)) AS __cnt"
let result = try await execute(query: countQuery)
guard let row = result.rows.first,
let cell = row.first,
let str = cell,
let count = Int(str) else {
return 0
}
return count
}
func fetchRows(query: String, offset: Int, limit: Int) async throws -> PluginQueryResult {
var base = query.trimmingCharacters(in: .whitespacesAndNewlines)
while base.hasSuffix(";") {
base = String(base.dropLast()).trimmingCharacters(in: .whitespacesAndNewlines)
}
base = stripLimitOffset(from: base)
let paginated = "\(base) LIMIT \(limit) OFFSET \(offset)"
return try await execute(query: paginated)
}
// MARK: - Schema Operations
func fetchTables(schema: String?) async throws -> [PluginTableInfo] {
let sql = """
SELECT name, engine FROM system.tables
WHERE database = currentDatabase() AND name NOT LIKE '.%'
ORDER BY name
"""
let result = try await execute(query: sql)
return result.rows.compactMap { row -> PluginTableInfo? in
guard let name = row[safe: 0] ?? nil else { return nil }
let engine = row[safe: 1] ?? nil
let tableType = (engine?.contains("View") == true) ? "VIEW" : "TABLE"
return PluginTableInfo(name: name, type: tableType)
}
}
func fetchColumns(table: String, schema: String?) async throws -> [PluginColumnInfo] {
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
let pkSql = """
SELECT primary_key, sorting_key FROM system.tables
WHERE database = currentDatabase() AND name = '\(escapedTable)'
"""
let pkResult = try await execute(query: pkSql)
let primaryKey = pkResult.rows.first.flatMap { $0[safe: 0] ?? nil } ?? ""
let sortingKey = pkResult.rows.first.flatMap { $0[safe: 1] ?? nil } ?? ""
let keyString = primaryKey.isEmpty ? sortingKey : primaryKey
let pkColumns = Set(keyString.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) })
let sql = """
SELECT name, type, default_kind, default_expression, comment
FROM system.columns
WHERE database = currentDatabase() AND table = '\(escapedTable)'
ORDER BY position
"""
let result = try await execute(query: sql)
return result.rows.compactMap { row -> PluginColumnInfo? in
guard let name = row[safe: 0] ?? nil else { return nil }
let dataType = (row[safe: 1] ?? nil) ?? "String"
let defaultKind = row[safe: 2] ?? nil
let defaultExpr = row[safe: 3] ?? nil
let comment = row[safe: 4] ?? nil
let isNullable = dataType.hasPrefix("Nullable(")
var defaultValue: String?
if let kind = defaultKind, !kind.isEmpty, let expr = defaultExpr, !expr.isEmpty {
defaultValue = expr
}
var extra: String?
if let kind = defaultKind, !kind.isEmpty, kind != "DEFAULT" {
extra = kind
}
return PluginColumnInfo(
name: name,
dataType: dataType,
isNullable: isNullable,
isPrimaryKey: pkColumns.contains(name),
defaultValue: defaultValue,
extra: extra,
comment: (comment?.isEmpty == false) ? comment : nil
)
}
}
func fetchAllColumns(schema: String?) async throws -> [String: [PluginColumnInfo]] {
// Pre-fetch PK columns for all tables. Falls back to sorting_key when
// primary_key is empty (MergeTree without explicit PRIMARY KEY clause).
// Note: expression-based keys like toDate(col) won't match bare column names.
let pkSql = """
SELECT name, primary_key, sorting_key FROM system.tables
WHERE database = currentDatabase()
"""
let pkResult = try await execute(query: pkSql)
var pkLookup: [String: Set<String>] = [:]
for row in pkResult.rows {
guard let tableName = row[safe: 0] ?? nil else { continue }
let primaryKey = (row[safe: 1] ?? nil) ?? ""
let sortingKey = (row[safe: 2] ?? nil) ?? ""
let keyString = primaryKey.isEmpty ? sortingKey : primaryKey
guard !keyString.isEmpty else { continue }
let cols = Set(keyString.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) })
pkLookup[tableName] = cols
}
let sql = """
SELECT table, name, type, default_kind, default_expression, comment
FROM system.columns
WHERE database = currentDatabase()
ORDER BY table, position
"""
let result = try await execute(query: sql)
var columnsByTable: [String: [PluginColumnInfo]] = [:]
for row in result.rows {
guard let tableName = row[safe: 0] ?? nil,
let colName = row[safe: 1] ?? nil else { continue }
let dataType = (row[safe: 2] ?? nil) ?? "String"
let defaultKind = row[safe: 3] ?? nil
let defaultExpr = row[safe: 4] ?? nil
let comment = row[safe: 5] ?? nil
let isNullable = dataType.hasPrefix("Nullable(")
var defaultValue: String?
if let kind = defaultKind, !kind.isEmpty, let expr = defaultExpr, !expr.isEmpty {
defaultValue = expr
}
var extra: String?
if let kind = defaultKind, !kind.isEmpty, kind != "DEFAULT" {
extra = kind
}
let colInfo = PluginColumnInfo(
name: colName,
dataType: dataType,
isNullable: isNullable,
isPrimaryKey: pkLookup[tableName]?.contains(colName) == true,
defaultValue: defaultValue,
extra: extra,
comment: (comment?.isEmpty == false) ? comment : nil
)
columnsByTable[tableName, default: []].append(colInfo)
}
return columnsByTable
}
func fetchIndexes(table: String, schema: String?) async throws -> [PluginIndexInfo] {
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
var indexes: [PluginIndexInfo] = []
let sortingKeySql = """
SELECT sorting_key FROM system.tables
WHERE database = currentDatabase() AND name = '\(escapedTable)'
"""
let sortingResult = try await execute(query: sortingKeySql)
if let row = sortingResult.rows.first,
let sortingKey = row[safe: 0] ?? nil, !sortingKey.isEmpty {
let columns = sortingKey.components(separatedBy: ",").map {
$0.trimmingCharacters(in: .whitespacesAndNewlines)
}
indexes.append(PluginIndexInfo(
name: "PRIMARY (sorting key)",
columns: columns,
isUnique: false,
isPrimary: true,
type: "SORTING KEY"
))
}
let skippingSql = """
SELECT name, expr FROM system.data_skipping_indices
WHERE database = currentDatabase() AND table = '\(escapedTable)'
"""
let skippingResult = try await execute(query: skippingSql)
for row in skippingResult.rows {
guard let idxName = row[safe: 0] ?? nil else { continue }
let expr = (row[safe: 1] ?? nil) ?? ""
let columns = expr.components(separatedBy: ",").map {
$0.trimmingCharacters(in: .whitespacesAndNewlines)
}
indexes.append(PluginIndexInfo(
name: idxName,
columns: columns,
isUnique: false,
isPrimary: false,
type: "DATA_SKIPPING"
))
}
return indexes
}
func fetchForeignKeys(table: String, schema: String?) async throws -> [PluginForeignKeyInfo] {
[]
}
func fetchApproximateRowCount(table: String, schema: String?) async throws -> Int? {
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
let sql = """
SELECT sum(rows) FROM system.parts
WHERE database = currentDatabase() AND table = '\(escapedTable)' AND active = 1
"""
let result = try await execute(query: sql)
if let row = result.rows.first, let cell = row.first, let str = cell {
return Int(str)
}
return nil
}
func fetchTableDDL(table: String, schema: String?) async throws -> String {
let escapedTable = table.replacingOccurrences(of: "`", with: "``")
let sql = "SHOW CREATE TABLE `\(escapedTable)`"
let result = try await execute(query: sql)
return result.rows.first?.first?.flatMap { $0 } ?? ""
}
func fetchViewDefinition(view: String, schema: String?) async throws -> String {
let escapedView = view.replacingOccurrences(of: "'", with: "''")
let sql = """
SELECT as_select FROM system.tables
WHERE database = currentDatabase() AND name = '\(escapedView)'
"""
let result = try await execute(query: sql)
return result.rows.first?.first?.flatMap { $0 } ?? ""
}
func fetchTableMetadata(table: String, schema: String?) async throws -> PluginTableMetadata {
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
let engineSql = """
SELECT engine, comment FROM system.tables
WHERE database = currentDatabase() AND name = '\(escapedTable)'
"""
let engineResult = try await execute(query: engineSql)
let engine = engineResult.rows.first.flatMap { $0[safe: 0] ?? nil }
let tableComment = engineResult.rows.first.flatMap { $0[safe: 1] ?? nil }
let partsSql = """
SELECT sum(rows), sum(bytes_on_disk)
FROM system.parts
WHERE database = currentDatabase() AND table = '\(escapedTable)' AND active = 1
"""
let partsResult = try await execute(query: partsSql)
if let row = partsResult.rows.first {
let rowCount = (row[safe: 0] ?? nil).flatMap { Int64($0) }
let sizeBytes = (row[safe: 1] ?? nil).flatMap { Int64($0) } ?? 0
return PluginTableMetadata(
tableName: table,
dataSize: sizeBytes,
totalSize: sizeBytes,
rowCount: rowCount,
comment: (tableComment?.isEmpty == false) ? tableComment : nil,
engine: engine
)
}
return PluginTableMetadata(tableName: table, engine: engine)
}
func fetchDatabases() async throws -> [String] {
let result = try await execute(query: "SHOW DATABASES")
return result.rows.compactMap { $0.first ?? nil }
}
func fetchDatabaseMetadata(_ database: String) async throws -> PluginDatabaseMetadata {
let escapedDb = database.replacingOccurrences(of: "'", with: "''")
let sql = """
SELECT count() AS table_count, sum(total_bytes) AS size_bytes
FROM system.tables WHERE database = '\(escapedDb)'
"""
let result = try await execute(query: sql)
if let row = result.rows.first {
let tableCount = (row[safe: 0] ?? nil).flatMap { Int($0) } ?? 0
let sizeBytes = (row[safe: 1] ?? nil).flatMap { Int64($0) }
return PluginDatabaseMetadata(
name: database,
tableCount: tableCount,
sizeBytes: sizeBytes
)
}
return PluginDatabaseMetadata(name: database)
}
func fetchAllDatabaseMetadata() async throws -> [PluginDatabaseMetadata] {
let sql = """
SELECT database, count() AS table_count, sum(total_bytes) AS size_bytes
FROM system.tables
GROUP BY database
ORDER BY database
"""
let result = try await execute(query: sql)
return result.rows.compactMap { row -> PluginDatabaseMetadata? in
guard let name = row[safe: 0] ?? nil else { return nil }
let tableCount = (row[safe: 1] ?? nil).flatMap { Int($0) } ?? 0
let sizeBytes = (row[safe: 2] ?? nil).flatMap { Int64($0) }
return PluginDatabaseMetadata(name: name, tableCount: tableCount, sizeBytes: sizeBytes)
}
}
func createDatabase(name: String, charset: String, collation: String?) async throws {
let escapedName = name.replacingOccurrences(of: "`", with: "``")
_ = try await execute(query: "CREATE DATABASE `\(escapedName)`")
}
func cancelQuery() throws {
let queryId: String?
lock.lock()
queryId = _lastQueryId
currentTask?.cancel()
currentTask = nil
lock.unlock()
if let queryId, !queryId.isEmpty {
killQuery(queryId: queryId)
}
}
func applyQueryTimeout(_ seconds: Int) async throws {
guard seconds > 0 else { return }
_ = try await execute(query: "SET max_execution_time = \(seconds)")
}
// MARK: - Database Switching
func switchDatabase(to database: String) async throws {
lock.lock()
_currentDatabase = database
lock.unlock()
}
// MARK: - Kill Query
private func killQuery(queryId: String) {
lock.lock()
let hasSession = session != nil
lock.unlock()
guard hasSession else { return }
let killConfig = URLSessionConfiguration.default
killConfig.timeoutIntervalForRequest = 5
let killSession = URLSession(configuration: killConfig)
do {
let escapedId = queryId.replacingOccurrences(of: "'", with: "''")
let request = try buildRequest(
query: "KILL QUERY WHERE query_id = '\(escapedId)'",
database: ""
)
let task = killSession.dataTask(with: request) { _, _, _ in
killSession.invalidateAndCancel()
}
task.resume()
} catch {
killSession.invalidateAndCancel()
}
}
// MARK: - Private HTTP Layer
private func executeRaw(_ query: String, queryId: String? = nil) async throws -> CHQueryResult {
lock.lock()
guard let session = self.session else {
lock.unlock()
throw ClickHouseError.notConnected
}
let database = _currentDatabase
if let queryId {
_lastQueryId = queryId
}
lock.unlock()
let request = try buildRequest(query: query, database: database, queryId: queryId)
let isSelect = Self.isSelectLikeQuery(query)
let (data, response) = try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(Data, URLResponse), Error>) in
let task = session.dataTask(with: request) { data, response, error in
if let error {
continuation.resume(throwing: error)
return
}
guard let data, let response else {
continuation.resume(throwing: ClickHouseError(message: "Empty response from server"))
return
}
continuation.resume(returning: (data, response))
}
self.lock.lock()
self.currentTask = task
self.lock.unlock()
task.resume()
}
} onCancel: {
self.lock.lock()
self.currentTask?.cancel()
self.currentTask = nil
self.lock.unlock()
}
lock.lock()
currentTask = nil
lock.unlock()
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
let body = String(data: data, encoding: .utf8) ?? "Unknown error"
Self.logger.error("ClickHouse HTTP \(httpResponse.statusCode): \(body)")
throw ClickHouseError(message: body.trimmingCharacters(in: .whitespacesAndNewlines))
}
if isSelect {
return parseTabSeparatedResponse(data)
}
return CHQueryResult(columns: [], columnTypeNames: [], rows: [], affectedRows: 0, isTruncated: false)
}
private func executeRawWithParams(_ query: String, params: [String: String?], queryId: String? = nil) async throws -> CHQueryResult {
lock.lock()
guard let session = self.session else {
lock.unlock()
throw ClickHouseError.notConnected
}
let database = _currentDatabase
if let queryId {
_lastQueryId = queryId
}
lock.unlock()
let request = try buildRequest(query: query, database: database, queryId: queryId, params: params)
let isSelect = Self.isSelectLikeQuery(query)
let (data, response) = try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(Data, URLResponse), Error>) in
let task = session.dataTask(with: request) { data, response, error in
if let error {
continuation.resume(throwing: error)
return
}
guard let data, let response else {
continuation.resume(throwing: ClickHouseError(message: "Empty response from server"))
return
}
continuation.resume(returning: (data, response))
}
self.lock.lock()
self.currentTask = task
self.lock.unlock()
task.resume()
}
} onCancel: {
self.lock.lock()
self.currentTask?.cancel()
self.currentTask = nil
self.lock.unlock()
}
lock.lock()
currentTask = nil
lock.unlock()
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
let body = String(data: data, encoding: .utf8) ?? "Unknown error"
Self.logger.error("ClickHouse HTTP \(httpResponse.statusCode): \(body)")
throw ClickHouseError(message: body.trimmingCharacters(in: .whitespacesAndNewlines))
}
if isSelect {
return parseTabSeparatedResponse(data)
}
return CHQueryResult(columns: [], columnTypeNames: [], rows: [], affectedRows: 0, isTruncated: false)
}
private func buildRequest(query: String, database: String, queryId: String? = nil, params: [String: String?]? = nil) throws -> URLRequest {
let useTLS = config.additionalFields["sslMode"] != nil
&& config.additionalFields["sslMode"] != "Disabled"
var components = URLComponents()
components.scheme = useTLS ? "https" : "http"
components.host = config.host
components.port = config.port
components.path = "/"
var queryItems = [URLQueryItem]()
if !database.isEmpty {
queryItems.append(URLQueryItem(name: "database", value: database))
}
if let queryId {
queryItems.append(URLQueryItem(name: "query_id", value: queryId))
}
queryItems.append(URLQueryItem(name: "send_progress_in_http_headers", value: "1"))
if let params {
for (key, value) in params.sorted(by: { $0.key < $1.key }) {
queryItems.append(URLQueryItem(name: "param_\(key)", value: value))
}
}
if !queryItems.isEmpty {
components.queryItems = queryItems
}
guard let url = components.url else {
throw ClickHouseError(message: "Failed to construct request URL")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let credentials = "\(config.username):\(config.password)"
if let credData = credentials.data(using: .utf8) {
request.setValue("Basic \(credData.base64EncodedString())", forHTTPHeaderField: "Authorization")
}
let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: ";+$", with: "", options: .regularExpression)
if Self.isSelectLikeQuery(trimmedQuery) {
request.httpBody = (trimmedQuery + " FORMAT TabSeparatedWithNamesAndTypes").data(using: .utf8)
} else {
request.httpBody = trimmedQuery.data(using: .utf8)
}
return request
}
private static func isSelectLikeQuery(_ query: String) -> Bool {
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard let firstWord = trimmed.split(separator: " ", maxSplits: 1).first else {
return false
}
return selectPrefixes.contains(firstWord.uppercased())
}
private func parseTabSeparatedResponse(_ data: Data) -> CHQueryResult {
guard let text = String(data: data, encoding: .utf8), !text.isEmpty else {
return CHQueryResult(columns: [], columnTypeNames: [], rows: [], affectedRows: 0, isTruncated: false)
}
let lines = text.components(separatedBy: "\n")
guard lines.count >= 2 else {
return CHQueryResult(columns: [], columnTypeNames: [], rows: [], affectedRows: 0, isTruncated: false)
}
let columns = lines[0].components(separatedBy: "\t")
let columnTypes = lines[1].components(separatedBy: "\t")
var rows: [[String?]] = []
var truncated = false
for i in 2..<lines.count {
let line = lines[i]
if line.isEmpty { continue }
let fields = line.components(separatedBy: "\t")
let row = fields.map { field -> String? in
if field == "\\N" {
return nil
}
return Self.unescapeTsvField(field)
}
rows.append(row)
if rows.count >= PluginRowLimits.defaultMax {
truncated = true
break
}
}
return CHQueryResult(
columns: columns,
columnTypeNames: columnTypes,
rows: rows,
affectedRows: rows.count,
isTruncated: truncated
)
}
private static func unescapeTsvField(_ field: String) -> String {
var result = ""
result.reserveCapacity((field as NSString).length)
var iterator = field.makeIterator()
while let char = iterator.next() {
if char == "\\" {
if let next = iterator.next() {
switch next {
case "\\": result.append("\\")
case "t": result.append("\t")
case "n": result.append("\n")
default:
result.append("\\")
result.append(next)
}
} else {
result.append("\\")
}
} else {
result.append(char)
}
}
return result
}
private func stripLimitOffset(from query: String) -> String {
let ns = query as NSString
let len = ns.length
guard len > 0 else { return query }
let upper = query.uppercased() as NSString
var depth = 0
var i = len - 1
while i >= 4 {
let ch = upper.character(at: i)
if ch == 0x29 { depth += 1 }
else if ch == 0x28 { depth -= 1 }
else if depth == 0 && ch == 0x54 {
let start = i - 4
if start >= 0 {
let candidate = upper.substring(with: NSRange(location: start, length: 5))
if candidate == "LIMIT" {
if start == 0 || CharacterSet.whitespacesAndNewlines
.contains(UnicodeScalar(upper.character(at: start - 1)) ?? UnicodeScalar(0)) {
return ns.substring(to: start)
.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
}
}
i -= 1
}
return query
}
/// Convert `?` placeholders to `{p1:String}` and build parameter map for ClickHouse HTTP params.
private static func buildClickHouseParams(
query: String,
parameters: [String?]
) -> (String, [String: String?]) {
var converted = ""
var paramIndex = 0
var inSingleQuote = false
var inDoubleQuote = false
var isEscaped = false
for char in query {
if isEscaped {
isEscaped = false
converted.append(char)
continue
}
if char == "\\" && (inSingleQuote || inDoubleQuote) {
isEscaped = true
converted.append(char)
continue
}
if char == "'" && !inDoubleQuote {
inSingleQuote.toggle()
} else if char == "\"" && !inSingleQuote {
inDoubleQuote.toggle()
}
if char == "?" && !inSingleQuote && !inDoubleQuote && paramIndex < parameters.count {
paramIndex += 1
converted.append("{p\(paramIndex):String}")
} else {
converted.append(char)
}
}
var paramMap: [String: String?] = [:]
for i in 0..<paramIndex where i < parameters.count {
paramMap["p\(i + 1)"] = parameters[i]
}
return (converted, paramMap)
}
// MARK: - TLS Delegate
private class InsecureTLSDelegate: NSObject, URLSessionDelegate {
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let serverTrust = challenge.protectionSpace.serverTrust {
completionHandler(.useCredential, URLCredential(trust: serverTrust))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
}