-
-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathMSSQLPlugin.swift
More file actions
1654 lines (1481 loc) · 65 KB
/
MSSQLPlugin.swift
File metadata and controls
1654 lines (1481 loc) · 65 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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// MSSQLPlugin.swift
// TablePro
//
import CFreeTDS
import Foundation
import os
import TableProPluginKit
final class MSSQLPlugin: NSObject, TableProPlugin, DriverPlugin {
static let pluginName = "MSSQL Driver"
static let pluginVersion = "1.0.0"
static let pluginDescription = "Microsoft SQL Server support via FreeTDS db-lib"
static let capabilities: [PluginCapability] = [.databaseDriver]
static let databaseTypeId = "SQL Server"
static let databaseDisplayName = "SQL Server"
static let iconName = "mssql-icon"
static let defaultPort = 1433
static let additionalConnectionFields: [ConnectionField] = [
ConnectionField(id: "mssqlSchema", label: "Schema", placeholder: "dbo", defaultValue: "dbo")
]
// MARK: - UI/Capability Metadata
static let postConnectActions: [PostConnectAction] = [.selectDatabaseFromLastSession]
static let brandColorHex = "#E34517"
static let systemDatabaseNames: [String] = ["master", "tempdb", "model", "msdb"]
static let defaultSchemaName = "dbo"
static let databaseGroupingStrategy: GroupingStrategy = .bySchema
static let columnTypesByCategory: [String: [String]] = [
"Integer": ["TINYINT", "SMALLINT", "INT", "BIGINT"],
"Float": ["FLOAT", "REAL", "DECIMAL", "NUMERIC", "MONEY", "SMALLMONEY"],
"String": ["CHAR", "VARCHAR", "TEXT", "NCHAR", "NVARCHAR", "NTEXT"],
"Date": ["DATE", "TIME", "DATETIME", "DATETIME2", "SMALLDATETIME", "DATETIMEOFFSET"],
"Binary": ["BINARY", "VARBINARY", "IMAGE"],
"Boolean": ["BIT"],
"XML": ["XML"],
"UUID": ["UNIQUEIDENTIFIER"],
"Spatial": ["GEOMETRY", "GEOGRAPHY"],
"Other": ["SQL_VARIANT", "TIMESTAMP", "ROWVERSION", "CURSOR", "TABLE", "HIERARCHYID"]
]
static let sqlDialect: SQLDialectDescriptor? = SQLDialectDescriptor(
identifierQuote: "[",
keywords: [
"SELECT", "FROM", "WHERE", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER", "CROSS", "FULL",
"ON", "USING", "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN", "AS",
"ORDER", "BY", "GROUP", "HAVING", "TOP", "OFFSET", "FETCH", "NEXT", "ROWS", "ONLY",
"INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE",
"CREATE", "ALTER", "DROP", "TABLE", "INDEX", "VIEW", "DATABASE", "SCHEMA",
"PRIMARY", "KEY", "FOREIGN", "REFERENCES", "UNIQUE", "CONSTRAINT",
"ADD", "COLUMN", "RENAME", "EXEC",
"NULL", "IS", "ASC", "DESC", "DISTINCT", "ALL", "ANY", "SOME",
"IDENTITY", "NOLOCK", "WITH", "ROWCOUNT", "NEWID",
"CASE", "WHEN", "THEN", "ELSE", "END", "COALESCE", "NULLIF", "IIF",
"UNION", "INTERSECT", "EXCEPT",
"DECLARE", "BEGIN", "COMMIT", "ROLLBACK", "TRANSACTION",
"PRINT", "GO", "EXECUTE",
"OVER", "PARTITION", "ROW_NUMBER", "RANK", "DENSE_RANK",
"RETURNING", "OUTPUT", "INSERTED", "DELETED"
],
functions: [
"COUNT", "SUM", "AVG", "MAX", "MIN", "STRING_AGG",
"CONCAT", "SUBSTRING", "LEFT", "RIGHT", "LEN", "LOWER", "UPPER",
"TRIM", "LTRIM", "RTRIM", "REPLACE", "CHARINDEX", "PATINDEX",
"STUFF", "FORMAT",
"GETDATE", "GETUTCDATE", "SYSDATETIME", "CURRENT_TIMESTAMP",
"DATEADD", "DATEDIFF", "DATENAME", "DATEPART",
"CONVERT", "CAST",
"ROUND", "CEILING", "FLOOR", "ABS", "POWER", "SQRT", "RAND",
"ISNULL", "ISNUMERIC", "ISDATE", "COALESCE", "NEWID",
"OBJECT_ID", "OBJECT_NAME", "SCHEMA_NAME", "DB_NAME",
"SCOPE_IDENTITY", "@@IDENTITY", "@@ROWCOUNT"
],
dataTypes: [
"INT", "INTEGER", "TINYINT", "SMALLINT", "BIGINT",
"DECIMAL", "NUMERIC", "FLOAT", "REAL", "MONEY", "SMALLMONEY",
"CHAR", "VARCHAR", "NCHAR", "NVARCHAR", "TEXT", "NTEXT",
"BINARY", "VARBINARY", "IMAGE",
"DATE", "TIME", "DATETIME", "DATETIME2", "SMALLDATETIME", "DATETIMEOFFSET",
"BIT", "UNIQUEIDENTIFIER", "XML", "SQL_VARIANT",
"ROWVERSION", "TIMESTAMP", "HIERARCHYID"
],
tableOptions: [
"ON", "CLUSTERED", "NONCLUSTERED", "WITH", "TEXTIMAGE_ON"
],
regexSyntax: .unsupported,
booleanLiteralStyle: .numeric,
likeEscapeStyle: .explicit,
paginationStyle: .offsetFetch,
autoLimitStyle: .top
)
func createDriver(config: DriverConnectionConfig) -> any PluginDatabaseDriver {
MSSQLPluginDriver(config: config)
}
}
// MARK: - Global FreeTDS initialization
/// Per-connection error storage keyed by DBPROCESS pointer.
/// Falls back to a global error string when the DBPROCESS is nil (pre-connection errors).
private let freetdsErrorLock = NSLock()
private var freetdsConnectionErrors: [UnsafeRawPointer: String] = [:]
private var freetdsGlobalError = ""
private func freetdsGetError(for dbproc: UnsafeMutablePointer<DBPROCESS>?) -> String {
freetdsErrorLock.lock()
defer { freetdsErrorLock.unlock() }
if let dbproc {
return freetdsConnectionErrors[UnsafeRawPointer(dbproc)] ?? freetdsGlobalError
}
return freetdsGlobalError
}
private func freetdsClearError(for dbproc: UnsafeMutablePointer<DBPROCESS>?) {
freetdsErrorLock.lock()
defer { freetdsErrorLock.unlock() }
if let dbproc {
freetdsConnectionErrors[UnsafeRawPointer(dbproc)] = nil
} else {
freetdsGlobalError = ""
}
}
private func freetdsSetError(_ msg: String, for dbproc: UnsafeMutablePointer<DBPROCESS>?, overwrite: Bool = false) {
freetdsErrorLock.lock()
defer { freetdsErrorLock.unlock() }
if let dbproc {
let key = UnsafeRawPointer(dbproc)
if overwrite || (freetdsConnectionErrors[key]?.isEmpty ?? true) {
freetdsConnectionErrors[key] = msg
}
} else if overwrite || freetdsGlobalError.isEmpty {
freetdsGlobalError = msg
}
}
private func freetdsUnregister(_ dbproc: UnsafeMutablePointer<DBPROCESS>) {
freetdsErrorLock.lock()
defer { freetdsErrorLock.unlock() }
freetdsConnectionErrors.removeValue(forKey: UnsafeRawPointer(dbproc))
}
private let freetdsLogger = Logger(subsystem: "com.TablePro", category: "FreeTDSConnection")
private let freetdsInitOnce: Void = {
_ = dbinit()
_ = dberrhandle { dbproc, _, dberr, _, dberrstr, oserrstr in
var msg = "db-lib error \(dberr)"
if let s = dberrstr { msg += ": \(String(cString: s))" }
if let s = oserrstr, String(cString: s) != "Success" { msg += " (os: \(String(cString: s)))" }
freetdsLogger.error("FreeTDS: \(msg)")
freetdsSetError(msg, for: dbproc)
return INT_CANCEL
}
_ = dbmsghandle { dbproc, msgno, _, severity, msgtext, _, _, _ in
guard let text = msgtext else { return 0 }
let msg = String(cString: text)
if severity > 10 {
// SQL Server sends informational messages first, error messages last —
// overwrite so the most specific error is kept
freetdsSetError(msg, for: dbproc, overwrite: true)
freetdsLogger.error("FreeTDS msg \(msgno) sev \(severity): \(msg)")
} else {
freetdsLogger.debug("FreeTDS msg \(msgno): \(msg)")
}
return 0
}
}()
// MARK: - FreeTDS Connection
private struct FreeTDSQueryResult {
let columns: [String]
let columnTypeNames: [String]
let rows: [[String?]]
let affectedRows: Int
let isTruncated: Bool
}
private final class FreeTDSConnection: @unchecked Sendable {
private var dbproc: UnsafeMutablePointer<DBPROCESS>?
private let queue: DispatchQueue
private let host: String
private let port: Int
private let user: String
private let password: String
private let database: String
private let lock = NSLock()
private var _isConnected = false
private var _isCancelled = false
var isConnected: Bool {
lock.lock()
defer { lock.unlock() }
return _isConnected
}
init(host: String, port: Int, user: String, password: String, database: String) {
self.queue = DispatchQueue(label: "com.TablePro.freetds.\(host).\(port)", qos: .userInitiated)
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
_ = freetdsInitOnce
}
func connect() async throws {
try await pluginDispatchAsync(on: queue) { [self] in
try self.connectSync()
}
}
private func connectSync() throws {
guard let login = dblogin() else {
throw MSSQLPluginError.connectionFailed("Failed to create login")
}
defer { dbloginfree(login) }
_ = dbsetlname(login, user, Int32(DBSETUSER))
_ = dbsetlname(login, password, Int32(DBSETPWD))
_ = dbsetlname(login, "TablePro", Int32(DBSETAPP))
_ = dbsetlname(login, "us_english", Int32(DBSETNATLANG))
_ = dbsetlname(login, "UTF-8", Int32(DBSETCHARSET))
_ = dbsetlversion(login, UInt8(DBVERSION_74))
freetdsClearError(for: nil)
let serverName = "\(host):\(port)"
guard let proc = dbopen(login, serverName) else {
let detail = freetdsGetError(for: nil)
let msg = detail.isEmpty ? "Check host, port, and credentials" : detail
throw MSSQLPluginError.connectionFailed("Failed to connect to \(host):\(port) — \(msg)")
}
if !database.isEmpty {
if dbuse(proc, database) == FAIL {
_ = dbclose(proc)
throw MSSQLPluginError.connectionFailed("Cannot open database '\(database)'")
}
}
self.dbproc = proc
lock.lock()
_isConnected = true
lock.unlock()
}
func switchDatabase(_ database: String) async throws {
try await pluginDispatchAsync(on: queue) { [self] in
guard let proc = self.dbproc else {
throw MSSQLPluginError.notConnected
}
if dbuse(proc, database) == FAIL {
throw MSSQLPluginError.queryFailed("Cannot switch to database '\(database)'")
}
}
}
func disconnect() {
let handle = dbproc
dbproc = nil
lock.lock()
_isConnected = false
lock.unlock()
if let handle = handle {
freetdsUnregister(handle)
queue.async {
_ = dbclose(handle)
}
}
}
func cancelCurrentQuery() {
lock.lock()
_isCancelled = true
let proc = dbproc
lock.unlock()
guard let proc else { return }
dbcancel(proc)
}
func executeQuery(_ query: String) async throws -> FreeTDSQueryResult {
let queryToRun = String(query)
return try await pluginDispatchAsync(on: queue) { [self] in
try self.executeQuerySync(queryToRun)
}
}
private func executeQuerySync(_ query: String) throws -> FreeTDSQueryResult {
guard let proc = dbproc else {
throw MSSQLPluginError.notConnected
}
_ = dbcanquery(proc)
lock.lock()
_isCancelled = false
lock.unlock()
freetdsClearError(for: proc)
if dbcmd(proc, query) == FAIL {
throw MSSQLPluginError.queryFailed("Failed to prepare query")
}
if dbsqlexec(proc) == FAIL {
let detail = freetdsGetError(for: proc)
let msg = detail.isEmpty ? "Query execution failed" : detail
throw MSSQLPluginError.queryFailed(msg)
}
var allColumns: [String] = []
var allTypeNames: [String] = []
var allRows: [[String?]] = []
var firstResultSet = true
var truncated = false
while true {
lock.lock()
let cancelledBetweenResults = _isCancelled
if cancelledBetweenResults { _isCancelled = false }
lock.unlock()
if cancelledBetweenResults {
throw MSSQLPluginError.queryFailed("Query cancelled")
}
let resCode = dbresults(proc)
if resCode == FAIL {
throw MSSQLPluginError.queryFailed("Query execution failed")
}
if resCode == Int32(NO_MORE_RESULTS) {
break
}
let numCols = dbnumcols(proc)
if numCols <= 0 { continue }
var cols: [String] = []
var typeNames: [String] = []
for i in 1...numCols {
let name = dbcolname(proc, Int32(i)).map { String(cString: $0) } ?? "col\(i)"
cols.append(name)
typeNames.append(Self.freetdsTypeName(dbcoltype(proc, Int32(i))))
}
if firstResultSet {
allColumns = cols
allTypeNames = typeNames
firstResultSet = false
}
while true {
let rowCode = dbnextrow(proc)
if rowCode == Int32(NO_MORE_ROWS) { break }
if rowCode == FAIL { break }
lock.lock()
let cancelled = _isCancelled
if cancelled { _isCancelled = false }
lock.unlock()
if cancelled {
throw MSSQLPluginError.queryFailed("Query cancelled")
}
var row: [String?] = []
for i in 1...numCols {
let len = dbdatlen(proc, Int32(i))
let colType = dbcoltype(proc, Int32(i))
if len <= 0 && colType != Int32(SYBBIT) {
row.append(nil)
} else if let ptr = dbdata(proc, Int32(i)) {
let str = Self.columnValueAsString(proc: proc, ptr: ptr, srcType: colType, srcLen: len)
row.append(str)
} else {
row.append(nil)
}
}
allRows.append(row)
if allRows.count >= PluginRowLimits.defaultMax {
truncated = true
break
}
}
}
let affectedRows = allColumns.isEmpty ? 0 : allRows.count
return FreeTDSQueryResult(
columns: allColumns,
columnTypeNames: allTypeNames,
rows: allRows,
affectedRows: affectedRows,
isTruncated: truncated
)
}
private static func columnValueAsString(proc: UnsafeMutablePointer<DBPROCESS>, ptr: UnsafePointer<BYTE>, srcType: Int32, srcLen: DBINT) -> String? {
switch srcType {
case Int32(SYBCHAR), Int32(SYBVARCHAR), Int32(SYBTEXT):
return String(bytes: UnsafeBufferPointer(start: ptr, count: Int(srcLen)), encoding: .utf8)
?? String(bytes: UnsafeBufferPointer(start: ptr, count: Int(srcLen)), encoding: .isoLatin1)
case Int32(SYBNCHAR), Int32(SYBNVARCHAR), Int32(SYBNTEXT):
// With client charset UTF-8, FreeTDS converts UTF-16 wire data to UTF-8
// but may still report the original nvarchar type token
return String(bytes: UnsafeBufferPointer(start: ptr, count: Int(srcLen)), encoding: .utf8)
?? String(data: Data(bytes: ptr, count: Int(srcLen)), encoding: .utf16LittleEndian)
default:
let bufSize: DBINT = 256
var buf = [BYTE](repeating: 0, count: Int(bufSize))
let converted = buf.withUnsafeMutableBufferPointer { bufPtr in
dbconvert(proc, srcType, ptr, srcLen, Int32(SYBCHAR), bufPtr.baseAddress, bufSize)
}
if converted > 0 {
return String(bytes: buf.prefix(Int(converted)), encoding: .utf8)
}
return nil
}
}
private static func freetdsTypeName(_ type: Int32) -> String {
switch type {
case Int32(SYBCHAR), Int32(SYBVARCHAR): return "varchar"
case Int32(SYBNCHAR), Int32(SYBNVARCHAR): return "nvarchar"
case Int32(SYBTEXT): return "text"
case Int32(SYBNTEXT): return "ntext"
case Int32(SYBINT1): return "tinyint"
case Int32(SYBINT2): return "smallint"
case Int32(SYBINT4): return "int"
case Int32(SYBINT8): return "bigint"
case Int32(SYBFLT8): return "float"
case Int32(SYBREAL): return "real"
case Int32(SYBDECIMAL), Int32(SYBNUMERIC): return "decimal"
case Int32(SYBMONEY), Int32(SYBMONEY4): return "money"
case Int32(SYBBIT): return "bit"
case Int32(SYBBINARY), Int32(SYBVARBINARY): return "varbinary"
case Int32(SYBIMAGE): return "image"
case Int32(SYBDATETIME), Int32(SYBDATETIMN): return "datetime"
case Int32(SYBDATETIME4): return "smalldatetime"
case Int32(SYBUNIQUE): return "uniqueidentifier"
default: return "unknown"
}
}
}
// MARK: - MSSQL Plugin Driver
final class MSSQLPluginDriver: PluginDatabaseDriver, @unchecked Sendable {
private let config: DriverConnectionConfig
private var freeTDSConn: FreeTDSConnection?
private var _currentSchema: String
private var _serverVersion: String?
private static let logger = Logger(subsystem: "com.TablePro", category: "MSSQLPluginDriver")
var currentSchema: String? { _currentSchema }
var serverVersion: String? { _serverVersion }
var supportsSchemas: Bool { true }
var supportsTransactions: Bool { true }
func quoteIdentifier(_ name: String) -> String {
let escaped = name.replacingOccurrences(of: "]", with: "]]")
return "[\(escaped)]"
}
// MARK: - View Templates
func createViewTemplate() -> String? {
"CREATE OR ALTER VIEW view_name AS\nSELECT column1, column2\nFROM table_name\nWHERE condition;"
}
func editViewFallbackTemplate(viewName: String) -> String? {
let quoted = quoteIdentifier(viewName)
return "CREATE OR ALTER VIEW \(quoted) AS\nSELECT * FROM table_name;"
}
func castColumnToText(_ column: String) -> String {
"CAST(\(column) AS NVARCHAR(MAX))"
}
init(config: DriverConnectionConfig) {
self.config = config
self._currentSchema = config.additionalFields["mssqlSchema"]?.isEmpty == false
? config.additionalFields["mssqlSchema"]!
: "dbo"
}
private var escapedSchema: String {
_currentSchema.replacingOccurrences(of: "'", with: "''")
}
// MARK: - Connection
func connect() async throws {
let conn = FreeTDSConnection(
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database
)
try await conn.connect()
self.freeTDSConn = conn
if let result = try? await conn.executeQuery("SELECT @@VERSION"),
let versionStr = result.rows.first?.first ?? nil {
_serverVersion = String(versionStr.prefix(50))
}
}
func disconnect() {
freeTDSConn?.disconnect()
freeTDSConn = nil
}
func ping() async throws {
_ = try await execute(query: "SELECT 1")
}
// MARK: - Transaction Management
func beginTransaction() async throws {
_ = try await execute(query: "BEGIN TRANSACTION")
}
// MARK: - Query Execution
func execute(query: String) async throws -> PluginQueryResult {
guard let conn = freeTDSConn else {
throw MSSQLPluginError.notConnected
}
let startTime = Date()
let result = try await conn.executeQuery(query)
return PluginQueryResult(
columns: result.columns,
columnTypeNames: result.columnTypeNames,
rows: result.rows,
rowsAffected: result.affectedRows,
executionTime: Date().timeIntervalSince(startTime),
isTruncated: result.isTruncated
)
}
// MARK: - DML Statement Generation
func generateStatements(
table: String,
columns: [String],
changes: [PluginRowChange],
insertedRowData: [Int: [String?]],
deletedRowIndices: Set<Int>,
insertedRowIndices: Set<Int>
) -> [(statement: String, parameters: [String?])]? {
var statements: [(statement: String, parameters: [String?])] = []
var deleteChanges: [PluginRowChange] = []
for change in changes {
switch change.type {
case .insert:
guard insertedRowIndices.contains(change.rowIndex) else { continue }
if let values = insertedRowData[change.rowIndex] {
if let stmt = generateMssqlInsert(table: table, columns: columns, values: values) {
statements.append(stmt)
}
}
case .update:
if let stmt = generateMssqlUpdate(table: table, columns: columns, change: change) {
statements.append(stmt)
}
case .delete:
guard deletedRowIndices.contains(change.rowIndex) else { continue }
deleteChanges.append(change)
}
}
if !deleteChanges.isEmpty {
for change in deleteChanges {
if let stmt = generateMssqlDelete(table: table, columns: columns, change: change) {
statements.append(stmt)
}
}
}
return statements.isEmpty ? nil : statements
}
private func generateMssqlInsert(
table: String,
columns: [String],
values: [String?]
) -> (statement: String, parameters: [String?])? {
var nonDefaultColumns: [String] = []
var parameters: [String?] = []
for (index, value) in values.enumerated() {
if value == "__DEFAULT__" { continue }
guard index < columns.count else { continue }
nonDefaultColumns.append("[\(columns[index].replacingOccurrences(of: "]", with: "]]"))]")
parameters.append(value)
}
guard !nonDefaultColumns.isEmpty else { return nil }
let columnList = nonDefaultColumns.joined(separator: ", ")
let placeholders = parameters.map { _ in "?" }.joined(separator: ", ")
let escapedTable = "[\(table.replacingOccurrences(of: "]", with: "]]"))]"
let sql = "INSERT INTO \(escapedTable) (\(columnList)) VALUES (\(placeholders))"
return (statement: sql, parameters: parameters)
}
private func generateMssqlUpdate(
table: String,
columns: [String],
change: PluginRowChange
) -> (statement: String, parameters: [String?])? {
guard !change.cellChanges.isEmpty else { return nil }
let escapedTable = "[\(table.replacingOccurrences(of: "]", with: "]]"))]"
var parameters: [String?] = []
let setClauses = change.cellChanges.map { cellChange -> String in
let col = "[\(cellChange.columnName.replacingOccurrences(of: "]", with: "]]"))]"
parameters.append(cellChange.newValue)
return "\(col) = ?"
}.joined(separator: ", ")
// Check if we have original row data to identify by PK or all columns
guard let originalRow = change.originalRow else { return nil }
// Use all columns as WHERE clause for safety
var conditions: [String] = []
for (index, columnName) in columns.enumerated() {
guard index < originalRow.count else { continue }
let col = "[\(columnName.replacingOccurrences(of: "]", with: "]]"))]"
if let value = originalRow[index] {
parameters.append(value)
conditions.append("\(col) = ?")
} else {
conditions.append("\(col) IS NULL")
}
}
guard !conditions.isEmpty else { return nil }
let whereClause = conditions.joined(separator: " AND ")
// Without a reliable PK, use UPDATE TOP (1) for safety
let sql = "UPDATE TOP (1) \(escapedTable) SET \(setClauses) WHERE \(whereClause)"
return (statement: sql, parameters: parameters)
}
private func generateMssqlDelete(
table: String,
columns: [String],
change: PluginRowChange
) -> (statement: String, parameters: [String?])? {
guard let originalRow = change.originalRow else { return nil }
let escapedTable = "[\(table.replacingOccurrences(of: "]", with: "]]"))]"
var parameters: [String?] = []
var conditions: [String] = []
for (index, columnName) in columns.enumerated() {
guard index < originalRow.count else { continue }
let col = "[\(columnName.replacingOccurrences(of: "]", with: "]]"))]"
if let value = originalRow[index] {
parameters.append(value)
conditions.append("\(col) = ?")
} else {
conditions.append("\(col) IS NULL")
}
}
guard !conditions.isEmpty else { return nil }
let whereClause = conditions.joined(separator: " AND ")
let sql = "DELETE TOP (1) FROM \(escapedTable) WHERE \(whereClause)"
return (statement: sql, parameters: parameters)
}
func cancelQuery() throws {
freeTDSConn?.cancelCurrentQuery()
}
func applyQueryTimeout(_ seconds: Int) async throws {
guard seconds > 0 else { return }
let ms = seconds * 1_000
_ = try await execute(query: "SET LOCK_TIMEOUT \(ms)")
}
func executeParameterized(query: String, parameters: [String?]) async throws -> PluginQueryResult {
guard !parameters.isEmpty else {
return try await execute(query: query)
}
let (convertedQuery, paramDecls, paramAssigns) = Self.buildSpExecuteSql(
query: query, parameters: parameters
)
// If no placeholders were found, execute the query as-is
guard !paramDecls.isEmpty else {
return try await execute(query: query)
}
let sql = "EXEC sp_executesql N'\(Self.escapeNString(convertedQuery))', N'\(paramDecls)', \(paramAssigns)"
return try await execute(query: sql)
}
func fetchRowCount(query: String) async throws -> Int {
let countQuery = "SELECT COUNT_BIG(*) 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 = stripMSSQLOffsetFetch(from: base)
let orderBy = hasTopLevelOrderBy(base) ? "" : " ORDER BY (SELECT NULL)"
let paginated = "\(base)\(orderBy) OFFSET \(offset) ROWS FETCH NEXT \(limit) ROWS ONLY"
return try await execute(query: paginated)
}
func fetchApproximateRowCount(table: String, schema: String?) async throws -> Int? {
let esc = (schema ?? _currentSchema).replacingOccurrences(of: "'", with: "''")
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
let objectName = "[\(esc)].[\(escapedTable)]"
let sql = """
SELECT SUM(p.rows)
FROM sys.partitions p
WHERE p.object_id = OBJECT_ID(N'\(objectName)') AND p.index_id IN (0, 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
}
// MARK: - Schema Operations
func fetchTables(schema: String?) async throws -> [PluginTableInfo] {
let esc = effectiveSchemaEscaped(schema)
let sql = """
SELECT t.TABLE_NAME, t.TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES t
WHERE t.TABLE_SCHEMA = '\(esc)'
AND t.TABLE_TYPE IN ('BASE TABLE', 'VIEW')
ORDER BY t.TABLE_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 rawType = row[safe: 1] ?? nil
let tableType = (rawType == "VIEW") ? "VIEW" : "TABLE"
return PluginTableInfo(name: name, type: tableType)
}
}
func fetchColumns(table: String, schema: String?) async throws -> [PluginColumnInfo] {
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
let esc = effectiveSchemaEscaped(schema)
let sql = """
SELECT
c.COLUMN_NAME,
c.DATA_TYPE,
c.CHARACTER_MAXIMUM_LENGTH,
c.NUMERIC_PRECISION,
c.NUMERIC_SCALE,
c.IS_NULLABLE,
c.COLUMN_DEFAULT,
COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsIdentity') AS IS_IDENTITY,
CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS IS_PK
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT kcu.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND tc.TABLE_SCHEMA = '\(esc)'
AND tc.TABLE_NAME = '\(escapedTable)'
) pk ON c.COLUMN_NAME = pk.COLUMN_NAME
WHERE c.TABLE_NAME = '\(escapedTable)'
AND c.TABLE_SCHEMA = '\(esc)'
ORDER BY c.ORDINAL_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
let charLen = row[safe: 2] ?? nil
let numPrecision = row[safe: 3] ?? nil
let numScale = row[safe: 4] ?? nil
let isNullable = (row[safe: 5] ?? nil) == "YES"
let defaultValue = row[safe: 6] ?? nil
let isIdentity = (row[safe: 7] ?? nil) == "1"
let isPk = (row[safe: 8] ?? nil) == "1"
let baseType = (dataType ?? "nvarchar").lowercased()
let fixedSizeTypes: Set<String> = [
"int", "bigint", "smallint", "tinyint", "bit",
"money", "smallmoney", "float", "real",
"datetime", "datetime2", "smalldatetime", "date", "time",
"uniqueidentifier", "text", "ntext", "image", "xml",
"timestamp", "rowversion"
]
var fullType = baseType
if fixedSizeTypes.contains(baseType) {
// No suffix
} else if let charLen, let len = Int(charLen), len > 0 {
fullType += "(\(len))"
} else if charLen == "-1" {
fullType += "(max)"
} else if let prec = numPrecision, let scale = numScale,
let p = Int(prec), let s = Int(scale) {
fullType += "(\(p),\(s))"
}
return PluginColumnInfo(
name: name,
dataType: fullType,
isNullable: isNullable,
isPrimaryKey: isPk,
defaultValue: defaultValue,
extra: isIdentity ? "IDENTITY" : nil
)
}
}
func fetchIndexes(table: String, schema: String?) async throws -> [PluginIndexInfo] {
let esc = (schema ?? _currentSchema).replacingOccurrences(of: "]", with: "]]")
let bracketedTable = table.replacingOccurrences(of: "]", with: "]]")
let bracketedFull = "[\(esc)].[\(bracketedTable)]"
let sql = """
SELECT i.name, i.is_unique, i.is_primary_key, c.name AS column_name
FROM sys.indexes i
JOIN sys.index_columns ic
ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c
ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE i.object_id = OBJECT_ID('\(bracketedFull)')
AND i.name IS NOT NULL
ORDER BY i.index_id, ic.key_ordinal
"""
let result = try await execute(query: sql)
var indexMap: [String: (unique: Bool, primary: Bool, columns: [String])] = [:]
for row in result.rows {
guard let idxName = row[safe: 0] ?? nil,
let colName = row[safe: 3] ?? nil else { continue }
let isUnique = (row[safe: 1] ?? nil) == "1"
let isPrimary = (row[safe: 2] ?? nil) == "1"
if indexMap[idxName] == nil {
indexMap[idxName] = (unique: isUnique, primary: isPrimary, columns: [])
}
indexMap[idxName]?.columns.append(colName)
}
return indexMap.map { name, info in
PluginIndexInfo(
name: name,
columns: info.columns,
isUnique: info.unique,
isPrimary: info.primary,
type: "CLUSTERED"
)
}.sorted { $0.name < $1.name }
}
func fetchForeignKeys(table: String, schema: String?) async throws -> [PluginForeignKeyInfo] {
let escapedTable = table.replacingOccurrences(of: "'", with: "''")
let esc = effectiveSchemaEscaped(schema)
let sql = """
SELECT
fk.name AS constraint_name,
cp.name AS column_name,
tr.name AS ref_table,
cr.name AS ref_column
FROM sys.foreign_keys fk
JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
JOIN sys.tables tp ON fkc.parent_object_id = tp.object_id
JOIN sys.schemas s ON tp.schema_id = s.schema_id
JOIN sys.columns cp
ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
JOIN sys.tables tr ON fkc.referenced_object_id = tr.object_id
JOIN sys.columns cr
ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE tp.name = '\(escapedTable)' AND s.name = '\(esc)'
ORDER BY fk.name
"""
let result = try await execute(query: sql)
return result.rows.compactMap { row -> PluginForeignKeyInfo? in
guard let constraintName = row[safe: 0] ?? nil,
let columnName = row[safe: 1] ?? nil,
let refTable = row[safe: 2] ?? nil,
let refColumn = row[safe: 3] ?? nil else { return nil }
return PluginForeignKeyInfo(
name: constraintName,
column: columnName,
referencedTable: refTable,
referencedColumn: refColumn
)
}
}
func fetchAllColumns(schema: String?) async throws -> [String: [PluginColumnInfo]] {
let esc = effectiveSchemaEscaped(schema)
let sql = """
SELECT
c.TABLE_NAME,
c.COLUMN_NAME,
c.DATA_TYPE,
c.CHARACTER_MAXIMUM_LENGTH,
c.NUMERIC_PRECISION,
c.NUMERIC_SCALE,
c.IS_NULLABLE,
c.COLUMN_DEFAULT,
COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsIdentity') AS IS_IDENTITY,
CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS IS_PK
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT kcu.TABLE_NAME, kcu.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND tc.TABLE_SCHEMA = '\(esc)'
) pk ON c.TABLE_NAME = pk.TABLE_NAME AND c.COLUMN_NAME = pk.COLUMN_NAME
WHERE c.TABLE_SCHEMA = '\(esc)'
ORDER BY c.TABLE_NAME, c.ORDINAL_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 name = row[safe: 1] ?? nil else { continue }
let dataType = row[safe: 2] ?? nil
let charLen = row[safe: 3] ?? nil
let numPrecision = row[safe: 4] ?? nil
let numScale = row[safe: 5] ?? nil
let isNullable = (row[safe: 6] ?? nil) == "YES"
let defaultValue = row[safe: 7] ?? nil
let isIdentity = (row[safe: 8] ?? nil) == "1"
let isPk = (row[safe: 9] ?? nil) == "1"
let baseType = (dataType ?? "nvarchar").lowercased()
let fixedSizeTypes: Set<String> = [
"int", "bigint", "smallint", "tinyint", "bit",
"money", "smallmoney", "float", "real",
"datetime", "datetime2", "smalldatetime", "date", "time",
"uniqueidentifier", "text", "ntext", "image", "xml",
"timestamp", "rowversion"
]
var fullType = baseType
if fixedSizeTypes.contains(baseType) {
// No suffix
} else if let charLen, let len = Int(charLen), len > 0 {
fullType += "(\(len))"
} else if charLen == "-1" {
fullType += "(max)"
} else if let prec = numPrecision, let scale = numScale,
let p = Int(prec), let s = Int(scale) {
fullType += "(\(p),\(s))"
}
let col = PluginColumnInfo(
name: name,
dataType: fullType,
isNullable: isNullable,
isPrimaryKey: isPk,
defaultValue: defaultValue,
extra: isIdentity ? "IDENTITY" : nil
)
columnsByTable[tableName, default: []].append(col)
}
return columnsByTable
}
func fetchAllForeignKeys(schema: String?) async throws -> [String: [PluginForeignKeyInfo]] {
let esc = effectiveSchemaEscaped(schema)
let sql = """
SELECT
tp.name AS table_name,
fk.name AS constraint_name,
cp.name AS column_name,
tr.name AS ref_table,
cr.name AS ref_column
FROM sys.foreign_keys fk