-
-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathSQLitePlugin.swift
More file actions
774 lines (640 loc) · 25.7 KB
/
SQLitePlugin.swift
File metadata and controls
774 lines (640 loc) · 25.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
//
// SQLitePlugin.swift
// TablePro
//
import Foundation
import os
import SQLite3
import TableProPluginKit
final class SQLitePlugin: NSObject, TableProPlugin, DriverPlugin {
static let pluginName = "SQLite Driver"
static let pluginVersion = "1.0.0"
static let pluginDescription = "SQLite file-based database support"
static let capabilities: [PluginCapability] = [.databaseDriver]
static let databaseTypeId = "SQLite"
static let databaseDisplayName = "SQLite"
static let iconName = "doc.fill"
static let defaultPort = 0
// MARK: - UI/Capability Metadata
static let requiresAuthentication = false
static let connectionMode: ConnectionMode = .fileBased
static let urlSchemes: [String] = ["sqlite"]
static let fileExtensions: [String] = ["db", "sqlite", "sqlite3"]
static let brandColorHex = "#003B57"
static let supportsDatabaseSwitching = false
static let databaseGroupingStrategy: GroupingStrategy = .flat
static let columnTypesByCategory: [String: [String]] = [
"Integer": ["INTEGER", "INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT"],
"Float": ["REAL", "DOUBLE", "FLOAT", "NUMERIC", "DECIMAL"],
"String": ["TEXT", "VARCHAR", "CHARACTER", "CHAR", "CLOB", "NVARCHAR", "NCHAR"],
"Date": ["DATE", "TIME", "DATETIME", "TIMESTAMP"],
"Binary": ["BLOB"],
"Boolean": ["BOOLEAN"]
]
static let sqlDialect: SQLDialectDescriptor? = SQLDialectDescriptor(
identifierQuote: "`",
keywords: [
"SELECT", "FROM", "WHERE", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER", "CROSS",
"ON", "AND", "OR", "NOT", "IN", "LIKE", "GLOB", "BETWEEN", "AS",
"ORDER", "BY", "GROUP", "HAVING", "LIMIT", "OFFSET",
"INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE",
"CREATE", "ALTER", "DROP", "TABLE", "INDEX", "VIEW", "TRIGGER",
"PRIMARY", "KEY", "FOREIGN", "REFERENCES", "UNIQUE", "CONSTRAINT",
"ADD", "COLUMN", "RENAME",
"NULL", "IS", "ASC", "DESC", "DISTINCT", "ALL",
"CASE", "WHEN", "THEN", "ELSE", "END", "COALESCE", "IFNULL", "NULLIF",
"UNION", "INTERSECT", "EXCEPT",
"AUTOINCREMENT", "WITHOUT", "ROWID", "PRAGMA",
"REPLACE", "ABORT", "FAIL", "IGNORE", "ROLLBACK",
"TEMP", "TEMPORARY", "VACUUM", "EXPLAIN", "QUERY", "PLAN"
],
functions: [
"COUNT", "SUM", "AVG", "MAX", "MIN", "GROUP_CONCAT", "TOTAL",
"LENGTH", "SUBSTR", "SUBSTRING", "LOWER", "UPPER", "TRIM", "LTRIM", "RTRIM",
"REPLACE", "INSTR", "PRINTF",
"DATE", "TIME", "DATETIME", "JULIANDAY", "STRFTIME",
"ABS", "ROUND", "RANDOM",
"CAST", "TYPEOF",
"COALESCE", "IFNULL", "NULLIF", "HEX", "QUOTE"
],
dataTypes: [
"INTEGER", "REAL", "TEXT", "BLOB", "NUMERIC",
"INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT",
"UNSIGNED", "BIG", "INT2", "INT8",
"CHARACTER", "VARCHAR", "VARYING", "NCHAR", "NATIVE",
"NVARCHAR", "CLOB",
"DOUBLE", "PRECISION", "FLOAT",
"DECIMAL", "BOOLEAN", "DATE", "DATETIME"
],
tableOptions: [
"WITHOUT ROWID", "STRICT"
],
regexSyntax: .unsupported,
booleanLiteralStyle: .numeric,
likeEscapeStyle: .explicit,
paginationStyle: .limit
)
func createDriver(config: DriverConnectionConfig) -> any PluginDatabaseDriver {
SQLitePluginDriver(config: config)
}
}
// MARK: - SQLite Connection Actor
private actor SQLiteConnectionActor {
private static let logger = Logger(subsystem: "com.TablePro", category: "SQLiteConnectionActor")
private var db: OpaquePointer?
var isConnected: Bool { db != nil }
func open(path: String) throws {
let result = sqlite3_open(path, &db)
if result != SQLITE_OK {
let errorMessage = db.map { String(cString: sqlite3_errmsg($0)) }
?? "Unknown SQLite error"
throw SQLitePluginError.connectionFailed(errorMessage)
}
}
func close() {
if db != nil {
sqlite3_close(db)
db = nil
}
}
func applyBusyTimeout(_ milliseconds: Int32) {
guard let db else { return }
sqlite3_busy_timeout(db, milliseconds)
}
var dbHandleForInterrupt: Int { db.map { Int(bitPattern: $0) } ?? 0 }
func executeQuery(_ query: String) throws -> SQLiteRawResult {
guard let db else {
throw SQLitePluginError.notConnected
}
let startTime = Date()
var statement: OpaquePointer?
let prepareResult = sqlite3_prepare_v2(db, query, -1, &statement, nil)
if prepareResult != SQLITE_OK {
let errorMessage = String(cString: sqlite3_errmsg(db))
throw SQLitePluginError.queryFailed(errorMessage)
}
defer {
sqlite3_finalize(statement)
}
let columnCount = sqlite3_column_count(statement)
var columns: [String] = []
var columnTypeNames: [String] = []
for i in 0..<columnCount {
if let name = sqlite3_column_name(statement, i) {
columns.append(String(cString: name))
} else {
columns.append("column_\(i)")
}
if let typePtr = sqlite3_column_decltype(statement, i) {
columnTypeNames.append(String(cString: typePtr))
} else {
columnTypeNames.append("")
}
}
var rows: [[String?]] = []
var rowsAffected = 0
var truncated = false
while sqlite3_step(statement) == SQLITE_ROW {
if rows.count >= PluginRowLimits.defaultMax {
truncated = true
break
}
var row: [String?] = []
for i in 0..<columnCount {
if sqlite3_column_type(statement, i) == SQLITE_NULL {
row.append(nil)
} else if let text = sqlite3_column_text(statement, i) {
row.append(String(cString: text))
} else {
row.append(nil)
}
}
rows.append(row)
}
if columns.isEmpty {
rowsAffected = Int(sqlite3_changes(db))
}
let executionTime = Date().timeIntervalSince(startTime)
return SQLiteRawResult(
columns: columns,
columnTypeNames: columnTypeNames,
rows: rows,
rowsAffected: rowsAffected,
executionTime: executionTime,
isTruncated: truncated
)
}
func executeParameterizedQuery(_ query: String, stringParams: [String?]) throws -> SQLiteRawResult {
guard let db else {
throw SQLitePluginError.notConnected
}
let startTime = Date()
var statement: OpaquePointer?
let prepareResult = sqlite3_prepare_v2(db, query, -1, &statement, nil)
if prepareResult != SQLITE_OK {
let errorMessage = String(cString: sqlite3_errmsg(db))
throw SQLitePluginError.queryFailed(errorMessage)
}
defer {
sqlite3_finalize(statement)
}
for (index, param) in stringParams.enumerated() {
let bindIndex = Int32(index + 1)
if let stringValue = param {
let bindResult = sqlite3_bind_text(statement, bindIndex, stringValue, -1, nil)
if bindResult != SQLITE_OK {
let errorMessage = String(cString: sqlite3_errmsg(db))
throw SQLitePluginError.queryFailed(
"Failed to bind parameter \(index): \(errorMessage)"
)
}
} else {
let bindResult = sqlite3_bind_null(statement, bindIndex)
if bindResult != SQLITE_OK {
let errorMessage = String(cString: sqlite3_errmsg(db))
throw SQLitePluginError.queryFailed(
"Failed to bind NULL parameter \(index): \(errorMessage)"
)
}
}
}
let columnCount = sqlite3_column_count(statement)
var columns: [String] = []
var columnTypeNames: [String] = []
for i in 0..<columnCount {
if let name = sqlite3_column_name(statement, i) {
columns.append(String(cString: name))
} else {
columns.append("column_\(i)")
}
if let typePtr = sqlite3_column_decltype(statement, i) {
columnTypeNames.append(String(cString: typePtr))
} else {
columnTypeNames.append("")
}
}
var rows: [[String?]] = []
var rowsAffected = 0
var truncated = false
while sqlite3_step(statement) == SQLITE_ROW {
if rows.count >= PluginRowLimits.defaultMax {
truncated = true
break
}
var row: [String?] = []
for i in 0..<columnCount {
if sqlite3_column_type(statement, i) == SQLITE_NULL {
row.append(nil)
} else if let text = sqlite3_column_text(statement, i) {
row.append(String(cString: text))
} else {
row.append(nil)
}
}
rows.append(row)
}
if columns.isEmpty {
rowsAffected = Int(sqlite3_changes(db))
}
let executionTime = Date().timeIntervalSince(startTime)
return SQLiteRawResult(
columns: columns,
columnTypeNames: columnTypeNames,
rows: rows,
rowsAffected: rowsAffected,
executionTime: executionTime,
isTruncated: truncated
)
}
}
private struct SQLiteRawResult: Sendable {
let columns: [String]
let columnTypeNames: [String]
let rows: [[String?]]
let rowsAffected: Int
let executionTime: TimeInterval
let isTruncated: Bool
}
// MARK: - SQLite Plugin Driver
final class SQLitePluginDriver: PluginDatabaseDriver, @unchecked Sendable {
private let config: DriverConnectionConfig
private let connectionActor = SQLiteConnectionActor()
private let interruptLock = NSLock()
nonisolated(unsafe) private var _dbHandleForInterrupt: OpaquePointer?
private static let logger = Logger(subsystem: "com.TablePro", category: "SQLitePluginDriver")
private static let limitRegex = try? NSRegularExpression(pattern: "(?i)\\s+LIMIT\\s+\\d+")
private static let offsetRegex = try? NSRegularExpression(pattern: "(?i)\\s+OFFSET\\s+\\d+")
var currentSchema: String? { nil }
var serverVersion: String? { String(cString: sqlite3_libversion()) }
var supportsSchemas: Bool { false }
var supportsTransactions: Bool { true }
func quoteIdentifier(_ name: String) -> String {
let escaped = name.replacingOccurrences(of: "`", with: "``")
return "`\(escaped)`"
}
init(config: DriverConnectionConfig) {
self.config = config
}
// MARK: - Connection
func connect() async throws {
let path = expandPath(config.database)
if !FileManager.default.fileExists(atPath: path) {
let directory = (path as NSString).deletingLastPathComponent
try? FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)
}
try await connectionActor.open(path: path)
let rawHandle = await connectionActor.dbHandleForInterrupt
setInterruptHandle(rawHandle != 0 ? OpaquePointer(bitPattern: rawHandle) : nil)
}
func disconnect() {
interruptLock.lock()
_dbHandleForInterrupt = nil
interruptLock.unlock()
let actor = connectionActor
Task { await actor.close() }
}
func ping() async throws {
_ = try await execute(query: "SELECT 1")
}
func applyQueryTimeout(_ seconds: Int) async throws {
guard seconds > 0 else { return }
await connectionActor.applyBusyTimeout(Int32(seconds * 1_000))
}
// MARK: - Query Execution
func execute(query: String) async throws -> PluginQueryResult {
let rawResult = try await connectionActor.executeQuery(query)
return PluginQueryResult(
columns: rawResult.columns,
columnTypeNames: rawResult.columnTypeNames,
rows: rawResult.rows,
rowsAffected: rawResult.rowsAffected,
executionTime: rawResult.executionTime,
isTruncated: rawResult.isTruncated
)
}
func executeParameterized(query: String, parameters: [String?]) async throws -> PluginQueryResult {
let rawResult = try await connectionActor.executeParameterizedQuery(query, stringParams: parameters)
return PluginQueryResult(
columns: rawResult.columns,
columnTypeNames: rawResult.columnTypeNames,
rows: rawResult.rows,
rowsAffected: rawResult.rowsAffected,
executionTime: rawResult.executionTime,
isTruncated: rawResult.isTruncated
)
}
func cancelQuery() throws {
interruptLock.lock()
let db = _dbHandleForInterrupt
interruptLock.unlock()
guard let db else { return }
sqlite3_interrupt(db)
}
// MARK: - EXPLAIN
func buildExplainQuery(_ sql: String) -> String? {
"EXPLAIN QUERY PLAN \(sql)"
}
// MARK: - View Templates
func createViewTemplate() -> String? {
"CREATE VIEW IF NOT EXISTS view_name AS\nSELECT column1, column2\nFROM table_name\nWHERE condition;"
}
func editViewFallbackTemplate(viewName: String) -> String? {
let quoted = quoteIdentifier(viewName)
return "DROP VIEW IF EXISTS \(quoted);\nCREATE VIEW \(quoted) AS\nSELECT * FROM table_name;"
}
// MARK: - Foreign Key Checks
func foreignKeyDisableStatements() -> [String]? {
["PRAGMA foreign_keys = OFF"]
}
func foreignKeyEnableStatements() -> [String]? {
["PRAGMA foreign_keys = ON"]
}
// MARK: - Pagination
func fetchRowCount(query: String) async throws -> Int {
let baseQuery = stripLimitOffset(from: query)
let countQuery = "SELECT COUNT(*) FROM (\(baseQuery))"
let result = try await execute(query: countQuery)
guard let firstRow = result.rows.first, let countStr = firstRow.first else { return 0 }
return Int(countStr ?? "0") ?? 0
}
func fetchRows(query: String, offset: Int, limit: Int) async throws -> PluginQueryResult {
let baseQuery = stripLimitOffset(from: query)
let paginatedQuery = "\(baseQuery) LIMIT \(limit) OFFSET \(offset)"
return try await execute(query: paginatedQuery)
}
// MARK: - Schema Operations
func fetchTables(schema: String?) async throws -> [PluginTableInfo] {
let query = """
SELECT name, type FROM sqlite_master
WHERE type IN ('table', 'view')
AND name NOT LIKE 'sqlite_%'
ORDER BY name
"""
let result = try await execute(query: query)
return result.rows.compactMap { row in
guard let name = row[safe: 0] ?? nil else { return nil }
let typeString = (row[safe: 1] ?? nil) ?? "table"
let tableType = typeString.lowercased() == "view" ? "VIEW" : "TABLE"
return PluginTableInfo(name: name, type: tableType)
}
}
func fetchColumns(table: String, schema: String?) async throws -> [PluginColumnInfo] {
let safeTable = escapeStringLiteral(table)
let query = "PRAGMA table_info('\(safeTable)')"
let result = try await execute(query: query)
return result.rows.compactMap { row in
guard row.count >= 6,
let name = row[1],
let dataType = row[2] else {
return nil
}
let isNullable = row[3] == "0"
let isPrimaryKey = row[5] == "1"
let defaultValue = row[4]
return PluginColumnInfo(
name: name,
dataType: dataType,
isNullable: isNullable,
isPrimaryKey: isPrimaryKey,
defaultValue: defaultValue
)
}
}
func fetchAllColumns(schema: String?) async throws -> [String: [PluginColumnInfo]] {
let query = """
SELECT m.name AS tbl, p.cid, p.name, p.type, p."notnull", p.dflt_value, p.pk
FROM sqlite_master m, pragma_table_info(m.name) p
WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'
ORDER BY m.name, p.cid
"""
let result = try await execute(query: query)
var allColumns: [String: [PluginColumnInfo]] = [:]
for row in result.rows {
guard row.count >= 7,
let tableName = row[0],
let columnName = row[2],
let dataType = row[3] else {
continue
}
let isNullable = row[4] == "0"
let defaultValue = row[5]
let isPrimaryKey = row[6] == "1"
let column = PluginColumnInfo(
name: columnName,
dataType: dataType,
isNullable: isNullable,
isPrimaryKey: isPrimaryKey,
defaultValue: defaultValue
)
allColumns[tableName, default: []].append(column)
}
return allColumns
}
func fetchAllForeignKeys(schema: String?) async throws -> [String: [PluginForeignKeyInfo]] {
let tables = try await fetchTables(schema: schema)
var result: [String: [PluginForeignKeyInfo]] = [:]
for table in tables {
let fks = try await fetchForeignKeys(table: table.name, schema: schema)
if !fks.isEmpty { result[table.name] = fks }
}
return result
}
func fetchIndexes(table: String, schema: String?) async throws -> [PluginIndexInfo] {
let safeTable = escapeStringLiteral(table)
let query = """
SELECT il.name, il."unique", il.origin, ii.name AS col_name
FROM pragma_index_list('\(safeTable)') il
LEFT JOIN pragma_index_info(il.name) ii ON 1=1
ORDER BY il.seq, ii.seqno
"""
let result = try await execute(query: query)
var indexMap: [(name: String, isUnique: Bool, isPrimary: Bool, columns: [String])] = []
var indexLookup: [String: Int] = [:]
for row in result.rows {
guard row.count >= 4,
let indexName = row[0] else { continue }
let isUnique = row[1] == "1"
let origin = row[2] ?? "c"
if let idx = indexLookup[indexName] {
if let colName = row[3] {
indexMap[idx].columns.append(colName)
}
} else {
let columns: [String] = row[3].map { [$0] } ?? []
indexLookup[indexName] = indexMap.count
indexMap.append((
name: indexName,
isUnique: isUnique,
isPrimary: origin == "pk",
columns: columns
))
}
}
return indexMap.map { entry in
PluginIndexInfo(
name: entry.name,
columns: entry.columns,
isUnique: entry.isUnique,
isPrimary: entry.isPrimary,
type: "BTREE"
)
}.sorted { $0.isPrimary && !$1.isPrimary }
}
func fetchForeignKeys(table: String, schema: String?) async throws -> [PluginForeignKeyInfo] {
let safeTable = escapeStringLiteral(table)
let query = "PRAGMA foreign_key_list('\(safeTable)')"
let result = try await execute(query: query)
return result.rows.compactMap { row in
guard row.count >= 5,
let refTable = row[2],
let fromCol = row[3],
let toCol = row[4] else {
return nil
}
let id = row[0] ?? "0"
let onUpdate = row.count >= 6 ? (row[5] ?? "NO ACTION") : "NO ACTION"
let onDelete = row.count >= 7 ? (row[6] ?? "NO ACTION") : "NO ACTION"
return PluginForeignKeyInfo(
name: "fk_\(table)_\(id)",
column: fromCol,
referencedTable: refTable,
referencedColumn: toCol,
onDelete: onDelete,
onUpdate: onUpdate
)
}
}
func fetchTableDDL(table: String, schema: String?) async throws -> String {
let safeTable = escapeStringLiteral(table)
let query = """
SELECT sql FROM sqlite_master
WHERE type = 'table' AND name = '\(safeTable)'
"""
let result = try await execute(query: query)
guard let firstRow = result.rows.first,
let ddl = firstRow[0] else {
throw SQLitePluginError.queryFailed("Failed to fetch DDL for table '\(table)'")
}
let formatted = formatDDL(ddl)
return formatted.hasSuffix(";") ? formatted : formatted + ";"
}
func fetchViewDefinition(view: String, schema: String?) async throws -> String {
let safeView = escapeStringLiteral(view)
let query = """
SELECT sql FROM sqlite_master
WHERE type = 'view' AND name = '\(safeView)'
"""
let result = try await execute(query: query)
guard let firstRow = result.rows.first,
let ddl = firstRow[0] else {
throw SQLitePluginError.queryFailed("Failed to fetch definition for view '\(view)'")
}
return ddl
}
func fetchTableMetadata(table: String, schema: String?) async throws -> PluginTableMetadata {
let safeTableName = table.replacingOccurrences(of: "\"", with: "\"\"")
let countQuery = "SELECT COUNT(*) FROM (SELECT 1 FROM \"\(safeTableName)\" LIMIT 100001)"
let countResult = try await execute(query: countQuery)
let rowCount: Int64? = {
guard let row = countResult.rows.first, let countStr = row.first else { return nil }
return Int64(countStr ?? "0")
}()
return PluginTableMetadata(
tableName: table,
rowCount: rowCount,
engine: "SQLite"
)
}
func fetchDatabases() async throws -> [String] {
[]
}
func fetchDatabaseMetadata(_ database: String) async throws -> PluginDatabaseMetadata {
PluginDatabaseMetadata(name: database)
}
func createDatabase(name: String, charset: String, collation: String?) async throws {
throw SQLitePluginError.unsupportedOperation
}
// MARK: - Private Helpers
nonisolated private func setInterruptHandle(_ handle: OpaquePointer?) {
interruptLock.lock()
_dbHandleForInterrupt = handle
interruptLock.unlock()
}
private func expandPath(_ path: String) -> String {
if path.hasPrefix("~") {
return NSString(string: path).expandingTildeInPath
}
return path
}
private func stripLimitOffset(from query: String) -> String {
var result = query
if let limitRegex = Self.limitRegex {
let range = NSRange(result.startIndex..., in: result)
result = limitRegex.stringByReplacingMatches(in: result, range: range, withTemplate: "")
}
if let offsetRegex = Self.offsetRegex {
let range = NSRange(result.startIndex..., in: result)
result = offsetRegex.stringByReplacingMatches(in: result, range: range, withTemplate: "")
}
return result.trimmingCharacters(in: .whitespacesAndNewlines)
}
private func formatDDL(_ ddl: String) -> String {
guard ddl.uppercased().hasPrefix("CREATE TABLE") else {
return ddl
}
var formatted = ddl
if let range = formatted.range(of: "(") {
let before = String(formatted[..<range.lowerBound])
let after = String(formatted[range.upperBound...])
formatted = before + "(\n " + after.trimmingCharacters(in: .whitespaces)
}
var result = ""
var depth = 0
var i = 0
let chars = Array(formatted)
while i < chars.count {
let char = chars[i]
if char == "(" {
depth += 1
result.append(char)
} else if char == ")" {
depth -= 1
result.append(char)
} else if char == "," && depth == 1 {
result.append(",\n ")
i += 1
while i < chars.count && chars[i].isWhitespace {
i += 1
}
i -= 1
} else {
result.append(char)
}
i += 1
}
formatted = result
if let range = formatted.range(of: ")", options: .backwards) {
let before = String(formatted[..<range.lowerBound]).trimmingCharacters(in: .whitespaces)
let after = String(formatted[range.lowerBound...])
formatted = before + "\n" + after
}
return formatted.isEmpty ? ddl : formatted
}
}
// MARK: - Errors
enum SQLitePluginError: Error {
case connectionFailed(String)
case notConnected
case queryFailed(String)
case unsupportedOperation
}
extension SQLitePluginError: PluginDriverError {
var pluginErrorMessage: String {
switch self {
case .connectionFailed(let msg): return msg
case .notConnected: return String(localized: "Not connected to database")
case .queryFailed(let msg): return msg
case .unsupportedOperation: return String(localized: "Operation not supported")
}
}
}