-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathLibPQPluginConnection.swift
More file actions
601 lines (503 loc) · 18 KB
/
LibPQPluginConnection.swift
File metadata and controls
601 lines (503 loc) · 18 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
//
// LibPQPluginConnection.swift
// PostgreSQLDriverPlugin
//
// Swift wrapper around libpq (PostgreSQL C API)
// Provides thread-safe, async-friendly PostgreSQL connections.
// Adapted from TablePro's LibPQConnection for the plugin architecture.
//
import CLibPQ
import Foundation
import OSLog
private let logger = Logger(subsystem: "com.TablePro.PostgreSQLDriver", category: "LibPQPluginConnection")
// MARK: - SSL Configuration
struct PQSSLConfig {
var mode: String = "Disabled"
var caCertificatePath: String = ""
var clientCertificatePath: String = ""
var clientKeyPath: String = ""
init() {}
init(additionalFields: [String: String]) {
self.mode = additionalFields["sslMode"] ?? "Disabled"
self.caCertificatePath = additionalFields["sslCaCertPath"] ?? ""
self.clientCertificatePath = additionalFields["sslClientCertPath"] ?? ""
self.clientKeyPath = additionalFields["sslClientKeyPath"] ?? ""
}
var libpqSslMode: String {
switch mode {
case "Disabled": return "disable"
case "Preferred": return "prefer"
case "Required": return "require"
case "Verify CA": return "verify-ca"
case "Verify Identity": return "verify-full"
default: return "disable"
}
}
var verifiesCertificate: Bool {
mode == "Verify CA" || mode == "Verify Identity"
}
}
// MARK: - Error Types
struct LibPQPluginError: Error, LocalizedError {
let message: String
let sqlState: String?
let detail: String?
var errorDescription: String? {
var desc = "PostgreSQL Error: \(message)"
if let state = sqlState {
desc += " (SQLSTATE: \(state))"
}
if let detail = detail, !detail.isEmpty {
desc += "\nDetail: \(detail)"
}
return desc
}
static let notConnected = LibPQPluginError(
message: "Not connected to database", sqlState: nil, detail: nil)
static let connectionFailed = LibPQPluginError(
message: "Failed to establish connection", sqlState: nil, detail: nil)
}
// MARK: - Query Result
struct LibPQPluginQueryResult {
let columns: [String]
let columnOids: [UInt32]
let columnTypeNames: [String]
let rows: [[String?]]
let affectedRows: Int
let commandTag: String?
let isTruncated: Bool
}
// MARK: - Type Mapping
private func pgOidToTypeName(_ oid: UInt32) -> String {
switch oid {
case 16: return "boolean"
case 17: return "bytea"
case 18: return "char"
case 19: return "name"
case 20: return "bigint"
case 21: return "smallint"
case 23: return "integer"
case 25: return "text"
case 26: return "oid"
case 114: return "json"
case 142: return "xml"
case 600: return "point"
case 601: return "lseg"
case 602: return "path"
case 603: return "box"
case 604: return "polygon"
case 628: return "line"
case 650: return "cidr"
case 700: return "real"
case 701: return "double precision"
case 718: return "circle"
case 829: return "macaddr"
case 869: return "inet"
case 1_009: return "text[]"
case 1_042: return "char"
case 1_043: return "varchar"
case 1_082: return "date"
case 1_083: return "time"
case 1_114: return "timestamp"
case 1_184: return "timestamptz"
case 1_266: return "timetz"
case 1_700: return "numeric"
case 2_950: return "uuid"
case 3_802: return "jsonb"
default: return "unknown"
}
}
// MARK: - Connection Class
final class LibPQPluginConnection: @unchecked Sendable {
private var conn: OpaquePointer?
private let queue = DispatchQueue(label: "com.TablePro.libpq.plugin", qos: .userInitiated)
private let host: String
private let port: Int
private let user: String
private let password: String?
private let database: String
private let sslConfig: PQSSLConfig
private let stateLock = NSLock()
private var _isConnected: Bool = false
private var _isShuttingDown: Bool = false
private var _cachedServerVersion: String?
private var _isCancelled: Bool = false
private static let maxRows = 100_000
var isConnected: Bool {
stateLock.lock()
defer { stateLock.unlock() }
return _isConnected
}
private var isShuttingDown: Bool {
get {
stateLock.lock()
defer { stateLock.unlock() }
return _isShuttingDown
}
set {
stateLock.lock()
_isShuttingDown = newValue
stateLock.unlock()
}
}
init(
host: String,
port: Int,
user: String,
password: String?,
database: String,
sslConfig: PQSSLConfig = PQSSLConfig()
) {
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.sslConfig = sslConfig
}
deinit {
let handle = conn
let cleanupQueue = queue
conn = nil
if let handle = handle {
cleanupQueue.async {
PQfinish(handle)
}
}
}
// MARK: - Connection Management
func connect() async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
queue.async { [self] in
func escapeConnParam(_ value: String) -> String {
value.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "'", with: "\\'")
}
var connStr = "host='\(escapeConnParam(host))' port='\(port)' dbname='\(escapeConnParam(database))' connect_timeout='10'"
if !user.isEmpty {
connStr += " user='\(escapeConnParam(user))'"
}
if let password = password, !password.isEmpty {
connStr += " password='\(escapeConnParam(password))'"
}
connStr += " sslmode='\(sslConfig.libpqSslMode)'"
if sslConfig.verifiesCertificate, !sslConfig.caCertificatePath.isEmpty {
connStr += " sslrootcert='\(escapeConnParam(sslConfig.caCertificatePath))'"
}
if !sslConfig.clientCertificatePath.isEmpty {
connStr += " sslcert='\(escapeConnParam(sslConfig.clientCertificatePath))'"
}
if !sslConfig.clientKeyPath.isEmpty {
connStr += " sslkey='\(escapeConnParam(sslConfig.clientKeyPath))'"
}
let connection = connStr.withCString { cStr in
PQconnectdb(cStr)
}
guard let connection = connection else {
continuation.resume(throwing: LibPQPluginError.connectionFailed)
return
}
if PQstatus(connection) != CONNECTION_OK {
let error = self.getError(from: connection)
PQfinish(connection)
continuation.resume(throwing: error)
return
}
_ = "SET client_encoding TO 'UTF8'".withCString { cStr in
PQexec(connection, cStr)
}
let version = PQserverVersion(connection)
if version > 0 {
let major = version / 10_000
let minor = (version / 100) % 100
let revision = version % 100
self._cachedServerVersion = "\(major).\(minor).\(revision)"
}
self.stateLock.lock()
self.conn = connection
self._isConnected = true
self.stateLock.unlock()
continuation.resume()
}
}
}
func disconnect() {
isShuttingDown = true
stateLock.lock()
_isConnected = false
let handle = conn
conn = nil
stateLock.unlock()
_cachedServerVersion = nil
if let handle {
queue.async {
PQfinish(handle)
}
}
}
// MARK: - Query Cancellation
func cancelCurrentQuery() {
stateLock.lock()
_isCancelled = true
let currentConn = conn
stateLock.unlock()
guard let currentConn else { return }
let cancelObj = PQgetCancel(currentConn)
guard let cancelObj else { return }
defer { PQfreeCancel(cancelObj) }
var errbuf = [CChar](repeating: 0, count: 256)
PQcancel(cancelObj, &errbuf, Int32(errbuf.count))
}
// MARK: - Query Execution
func executeQuery(_ query: String) async throws -> LibPQPluginQueryResult {
let queryToRun = String(query)
return try await withCheckedThrowingContinuation { [self] (cont: CheckedContinuation<LibPQPluginQueryResult, Error>) in
queue.async { [self] in
guard !isShuttingDown else {
cont.resume(throwing: LibPQPluginError.notConnected)
return
}
do {
let result = try executeQuerySync(queryToRun)
cont.resume(returning: result)
} catch {
cont.resume(throwing: error)
}
}
}
}
func executeParameterizedQuery(_ query: String, parameters: [String?]) async throws -> LibPQPluginQueryResult {
let queryToRun = String(query)
let params = parameters
return try await withCheckedThrowingContinuation { [self] (cont: CheckedContinuation<LibPQPluginQueryResult, Error>) in
queue.async { [self] in
guard !isShuttingDown else {
cont.resume(throwing: LibPQPluginError.notConnected)
return
}
do {
let result = try executeParameterizedQuerySync(queryToRun, parameters: params)
cont.resume(returning: result)
} catch {
cont.resume(throwing: error)
}
}
}
}
// MARK: - Server Information
func serverVersion() -> String? {
_cachedServerVersion
}
func currentDatabase() -> String {
database
}
// MARK: - Synchronous Query Execution
private func executeQuerySync(_ query: String) throws -> LibPQPluginQueryResult {
stateLock.lock()
let conn = self.conn
stateLock.unlock()
guard !isShuttingDown, let conn else {
throw LibPQPluginError.notConnected
}
let localQuery = String(query)
let result: OpaquePointer? = localQuery.withCString { queryPtr in
PQexec(conn, queryPtr)
}
guard let result = result else {
throw getError(from: conn)
}
let status = PQresultStatus(result)
switch status {
case PGRES_COMMAND_OK:
let affected = getAffectedRows(from: result)
let cmdTag = getCommandTag(from: result)
PQclear(result)
return LibPQPluginQueryResult(
columns: [],
columnOids: [],
columnTypeNames: [],
rows: [],
affectedRows: affected,
commandTag: cmdTag,
isTruncated: false
)
case PGRES_TUPLES_OK:
let queryResult = try fetchResults(from: result)
PQclear(result)
return queryResult
default:
let error = getResultError(from: result)
PQclear(result)
throw error
}
}
private func executeParameterizedQuerySync(_ query: String, parameters: [String?]) throws -> LibPQPluginQueryResult {
stateLock.lock()
let conn = self.conn
stateLock.unlock()
guard !isShuttingDown, let conn else {
throw LibPQPluginError.notConnected
}
var paramValues: [UnsafePointer<CChar>?] = []
defer {
for ptr in paramValues {
if let ptr = ptr {
free(UnsafeMutablePointer(mutating: ptr))
}
}
}
for param in parameters {
if let param = param {
let cStr = strdup(param)
paramValues.append(UnsafePointer(cStr))
} else {
paramValues.append(nil)
}
}
let localQuery = String(query)
let result: OpaquePointer? = localQuery.withCString { queryPtr in
PQexecParams(
conn,
queryPtr,
Int32(parameters.count),
nil,
paramValues,
nil,
nil,
0
)
}
guard let result = result else {
throw getError(from: conn)
}
let status = PQresultStatus(result)
switch status {
case PGRES_COMMAND_OK:
let affected = getAffectedRows(from: result)
let cmdTag = getCommandTag(from: result)
PQclear(result)
return LibPQPluginQueryResult(
columns: [],
columnOids: [],
columnTypeNames: [],
rows: [],
affectedRows: affected,
commandTag: cmdTag,
isTruncated: false
)
case PGRES_TUPLES_OK:
let queryResult = try fetchResults(from: result)
PQclear(result)
return queryResult
default:
let error = getResultError(from: result)
PQclear(result)
throw error
}
}
// MARK: - Result Parsing
private func fetchResults(from result: OpaquePointer) throws -> LibPQPluginQueryResult {
let numFields = Int(PQnfields(result))
let numRows = Int(PQntuples(result))
var columns: [String] = []
var columnOids: [UInt32] = []
var columnTypeNames: [String] = []
columns.reserveCapacity(numFields)
columnOids.reserveCapacity(numFields)
columnTypeNames.reserveCapacity(numFields)
for i in 0..<numFields {
if let namePtr = PQfname(result, Int32(i)) {
columns.append(String(cString: namePtr))
} else {
columns.append("column_\(i)")
}
let oid = PQftype(result, Int32(i))
columnOids.append(UInt32(oid))
columnTypeNames.append(pgOidToTypeName(UInt32(oid)))
}
let maxRows = Self.maxRows
let effectiveRowCount = min(numRows, maxRows)
let truncated = numRows > maxRows
var rows: [[String?]] = []
rows.reserveCapacity(effectiveRowCount)
for rowIndex in 0..<effectiveRowCount {
stateLock.lock()
let shouldCancel = _isCancelled
if shouldCancel { _isCancelled = false }
stateLock.unlock()
if shouldCancel {
PQclear(result)
throw LibPQPluginError(message: "Query cancelled", sqlState: nil, detail: nil)
}
var row: [String?] = []
row.reserveCapacity(numFields)
for colIndex in 0..<numFields {
if PQgetisnull(result, Int32(rowIndex), Int32(colIndex)) == 1 {
row.append(nil)
} else if let valuePtr = PQgetvalue(result, Int32(rowIndex), Int32(colIndex)) {
let length = Int(PQgetlength(result, Int32(rowIndex), Int32(colIndex)))
let bufferPtr = UnsafeRawBufferPointer(start: valuePtr, count: length)
if let str = String(bytes: bufferPtr, encoding: .utf8) {
if columnOids[colIndex] == 16 {
row.append(str == "t" ? "true" : "false")
} else {
row.append(str)
}
} else {
row.append(String(bytes: bufferPtr, encoding: .isoLatin1) ?? "")
}
} else {
row.append(nil)
}
}
rows.append(row)
}
if truncated {
logger.warning("Result set truncated at \(maxRows) rows")
}
return LibPQPluginQueryResult(
columns: columns,
columnOids: columnOids,
columnTypeNames: columnTypeNames,
rows: rows,
affectedRows: numRows,
commandTag: getCommandTag(from: result),
isTruncated: truncated
)
}
// MARK: - Private Helpers
private func getError(from conn: OpaquePointer) -> LibPQPluginError {
var message = "Unknown error"
if let msgPtr = PQerrorMessage(conn) {
message = String(cString: msgPtr).trimmingCharacters(in: .whitespacesAndNewlines)
}
return LibPQPluginError(message: message, sqlState: nil, detail: nil)
}
private func getResultError(from result: OpaquePointer) -> LibPQPluginError {
var message = "Unknown error"
var sqlState: String?
var detail: String?
if let msgPtr = PQresultErrorMessage(result) {
message = String(cString: msgPtr).trimmingCharacters(in: .whitespacesAndNewlines)
}
if let statePtr = PQresultErrorField(result, Int32(80)) {
sqlState = String(cString: statePtr)
}
if let detailPtr = PQresultErrorField(result, Int32(68)) {
detail = String(cString: detailPtr)
}
return LibPQPluginError(message: message, sqlState: sqlState, detail: detail)
}
private func getAffectedRows(from result: OpaquePointer) -> Int {
if let affectedPtr = PQcmdTuples(result), affectedPtr.pointee != 0 {
return Int(String(cString: affectedPtr)) ?? 0
}
return 0
}
private func getCommandTag(from result: OpaquePointer) -> String? {
if let tagPtr = PQcmdStatus(result), tagPtr.pointee != 0 {
return String(cString: tagPtr)
}
return nil
}
}