-
-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathQueryTab.swift
More file actions
663 lines (577 loc) · 21.6 KB
/
QueryTab.swift
File metadata and controls
663 lines (577 loc) · 21.6 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
//
// QueryTab.swift
// TablePro
//
// Model for query tabs
//
import Foundation
import Observation
import TableProPluginKit
/// Type of tab
enum TabType: Equatable, Codable, Hashable {
case query // SQL editor tab
case table // Direct table view tab
}
/// Minimal representation of a tab for persistence
struct PersistedTab: Codable {
let id: UUID
let title: String
let query: String
let tabType: TabType
let tableName: String?
var isView: Bool = false
var databaseName: String = "" // Database context for this tab (for multi-database restore)
}
/// Stores pending changes for a tab (used to preserve state when switching tabs)
struct TabPendingChanges: Equatable {
var changes: [RowChange]
var deletedRowIndices: Set<Int>
var insertedRowIndices: Set<Int>
var modifiedCells: [Int: Set<Int>]
var insertedRowData: [Int: [String?]] // Lazy storage for inserted row values
var primaryKeyColumn: String?
var columns: [String]
init() {
self.changes = []
self.deletedRowIndices = []
self.insertedRowIndices = []
self.modifiedCells = [:]
self.insertedRowData = [:]
self.primaryKeyColumn = nil
self.columns = []
}
var hasChanges: Bool {
!changes.isEmpty || !insertedRowIndices.isEmpty || !deletedRowIndices.isEmpty
}
}
/// Sort direction for column sorting
enum SortDirection: Equatable {
case ascending
case descending
var indicator: String {
switch self {
case .ascending: return "▲"
case .descending: return "▼"
}
}
mutating func toggle() {
self = self == .ascending ? .descending : .ascending
}
}
/// A single column in a multi-column sort
struct SortColumn: Equatable {
var columnIndex: Int
var direction: SortDirection
}
/// Tracks sorting state for a table (supports multi-column sort)
struct SortState: Equatable {
var columns: [SortColumn] = []
init() {}
var isSorting: Bool { !columns.isEmpty }
// Backward-compatible computed properties for single-column access
var columnIndex: Int? { columns.first?.columnIndex }
var direction: SortDirection { columns.first?.direction ?? .ascending }
}
/// Tracks pagination state for navigating large datasets
struct PaginationState: Equatable {
var totalRowCount: Int? // Total rows in table (from COUNT(*))
var pageSize: Int // Rows per page (passed from manager/coordinator)
var currentPage: Int = 1 // Current page number (1-based)
var currentOffset: Int = 0 // Current OFFSET for SQL query
var isLoading: Bool = false // Loading indicator
var isApproximateRowCount: Bool = false // True when totalRowCount is from fast estimate
/// Default page size constant (used when no explicit value is provided)
/// Note: For new tabs, callers should pass AppSettingsManager.shared.dataGrid.defaultPageSize
static let defaultPageSize = 1_000
init(
totalRowCount: Int? = nil,
pageSize: Int = PaginationState.defaultPageSize,
currentPage: Int = 1,
currentOffset: Int = 0,
isLoading: Bool = false
) {
self.totalRowCount = totalRowCount
self.pageSize = pageSize
self.currentPage = currentPage
self.currentOffset = currentOffset
self.isLoading = isLoading
}
// MARK: - Computed Properties
/// Total number of pages
var totalPages: Int {
guard let total = totalRowCount, total > 0 else { return 1 }
return (total + pageSize - 1) / pageSize // Ceiling division
}
/// Whether there is a next page available
var hasNextPage: Bool {
currentPage < totalPages
}
/// Whether there is a previous page available
var hasPreviousPage: Bool {
currentPage > 1
}
/// Starting row number for current page (1-based)
var rangeStart: Int {
currentOffset + 1
}
/// Ending row number for current page (1-based)
var rangeEnd: Int {
guard let total = totalRowCount else {
return currentOffset + pageSize
}
return min(currentOffset + pageSize, total)
}
// MARK: - Navigation Methods
/// Navigate to next page
mutating func goToNextPage() {
guard hasNextPage else { return }
currentPage += 1
currentOffset = (currentPage - 1) * pageSize
}
/// Navigate to previous page
mutating func goToPreviousPage() {
guard hasPreviousPage else { return }
currentPage -= 1
currentOffset = (currentPage - 1) * pageSize
}
/// Navigate to first page
mutating func goToFirstPage() {
currentPage = 1
currentOffset = 0
}
/// Navigate to last page
mutating func goToLastPage() {
currentPage = totalPages
currentOffset = (totalPages - 1) * pageSize
}
/// Navigate to specific page
mutating func goToPage(_ page: Int) {
guard page > 0 && page <= totalPages else { return }
currentPage = page
currentOffset = (page - 1) * pageSize
}
/// Reset pagination to first page
mutating func reset() {
currentPage = 1
currentOffset = 0
isLoading = false
}
/// Update page size (limit)
mutating func updatePageSize(_ newSize: Int) {
guard newSize > 0 else { return }
pageSize = newSize
// Recalculate current page based on current offset
currentPage = (currentOffset / pageSize) + 1
}
/// Update offset directly and recalculate page
mutating func updateOffset(_ newOffset: Int) {
guard newOffset >= 0 else { return }
currentOffset = newOffset
currentPage = (currentOffset / pageSize) + 1
}
}
/// Stores column layout (widths and order) within a tab session
struct ColumnLayoutState: Equatable {
var columnWidths: [String: CGFloat] = [:]
var columnOrder: [String]?
var hiddenColumns: Set<String> = []
}
/// Reference-type wrapper for large result data.
/// When QueryTab (a struct) is copied via CoW, only this 8-byte reference is copied
/// instead of duplicating potentially large result arrays.
final class RowBuffer {
var rows: [QueryResultRow]
var columns: [String]
var columnTypes: [ColumnType]
var columnDefaults: [String: String?]
var columnForeignKeys: [String: ForeignKeyInfo]
var columnEnumValues: [String: [String]]
var columnNullable: [String: Bool]
init(
rows: [QueryResultRow] = [],
columns: [String] = [],
columnTypes: [ColumnType] = [],
columnDefaults: [String: String?] = [:],
columnForeignKeys: [String: ForeignKeyInfo] = [:],
columnEnumValues: [String: [String]] = [:],
columnNullable: [String: Bool] = [:]
) {
self.rows = rows
self.columns = columns
self.columnTypes = columnTypes
self.columnDefaults = columnDefaults
self.columnForeignKeys = columnForeignKeys
self.columnEnumValues = columnEnumValues
self.columnNullable = columnNullable
}
/// Create a deep copy of this buffer (used when explicit data duplication is needed)
func copy() -> RowBuffer {
RowBuffer(
rows: rows,
columns: columns,
columnTypes: columnTypes,
columnDefaults: columnDefaults,
columnForeignKeys: columnForeignKeys,
columnEnumValues: columnEnumValues,
columnNullable: columnNullable
)
}
/// Whether this buffer's row data has been evicted to save memory
private(set) var isEvicted: Bool = false
/// Evict row data to free memory. Column metadata is preserved.
func evict() {
guard !isEvicted else { return }
rows = []
isEvicted = true
}
/// Restore row data after eviction
func restore(rows newRows: [QueryResultRow]) {
self.rows = newRows
isEvicted = false
}
}
/// Represents a single tab (query or table)
struct QueryTab: Identifiable, Equatable {
let id: UUID
var title: String
var query: String
var lastExecutedAt: Date?
var tabType: TabType
// Results — stored in a reference-type buffer to avoid CoW duplication
// of large data when the struct is mutated (MEM-1 fix)
var rowBuffer: RowBuffer
// Backward-compatible computed accessors for result data
var resultColumns: [String] {
get { rowBuffer.columns }
set { rowBuffer.columns = newValue }
}
var columnTypes: [ColumnType] {
get { rowBuffer.columnTypes }
set { rowBuffer.columnTypes = newValue }
}
var columnDefaults: [String: String?] {
get { rowBuffer.columnDefaults }
set { rowBuffer.columnDefaults = newValue }
}
var columnForeignKeys: [String: ForeignKeyInfo] {
get { rowBuffer.columnForeignKeys }
set { rowBuffer.columnForeignKeys = newValue }
}
var columnEnumValues: [String: [String]] {
get { rowBuffer.columnEnumValues }
set { rowBuffer.columnEnumValues = newValue }
}
var columnNullable: [String: Bool] {
get { rowBuffer.columnNullable }
set { rowBuffer.columnNullable = newValue }
}
var resultRows: [QueryResultRow] {
get { rowBuffer.rows }
set { rowBuffer.rows = newValue }
}
var executionTime: TimeInterval?
var rowsAffected: Int // Number of rows affected by non-SELECT queries
var errorMessage: String?
var isExecuting: Bool
// Editing support
var tableName: String?
var primaryKeyColumn: String? // Detected PK from schema (set by Phase 2 metadata)
var isEditable: Bool
var isView: Bool // True for database views (read-only)
var databaseName: String // Database this tab was opened in (for multi-database restore)
var showStructure: Bool // Toggle to show structure view instead of data
var explainText: String?
var explainExecutionTime: TimeInterval?
// Per-tab change tracking (preserves changes when switching tabs)
var pendingChanges: TabPendingChanges
// Per-tab row selection (preserves selection when switching tabs)
var selectedRowIndices: Set<Int>
// Per-tab sort state (column sorting)
var sortState: SortState
// Track if user has interacted with this tab (sort, edit, select, etc)
// Prevents tab from being replaced when opening new tables
var hasUserInteraction: Bool
// Pagination state for lazy loading (table tabs only)
var pagination: PaginationState
// Per-tab filter state (preserves filters when switching tabs)
var filterState: TabFilterState
// Per-tab column layout (widths/order persist across reloads within tab session)
var columnLayout: ColumnLayoutState
// Whether this tab is a preview (temporary) tab that gets replaced on next navigation
var isPreview: Bool
// Version counter incremented when resultRows changes (used for sort caching)
var resultVersion: Int
// Version counter incremented when FK/metadata arrives (Phase 2), used to invalidate caches
var metadataVersion: Int
init(
id: UUID = UUID(),
title: String = "Query",
query: String = "",
tabType: TabType = .query,
tableName: String? = nil
) {
self.id = id
self.title = title
self.query = query
self.tabType = tabType
self.lastExecutedAt = nil
self.rowBuffer = RowBuffer()
self.executionTime = nil
self.rowsAffected = 0
self.errorMessage = nil
self.isExecuting = false
self.tableName = tableName
self.primaryKeyColumn = nil
self.isEditable = tabType == .table // Table tabs are editable by default
self.isView = false
self.databaseName = ""
self.showStructure = false
self.pendingChanges = TabPendingChanges()
self.selectedRowIndices = []
self.sortState = SortState()
self.hasUserInteraction = false
self.pagination = PaginationState()
self.filterState = TabFilterState()
self.columnLayout = ColumnLayoutState()
self.isPreview = false
self.resultVersion = 0
self.metadataVersion = 0
}
/// Initialize from persisted tab state (used when restoring tabs)
init(from persisted: PersistedTab) {
self.id = persisted.id
self.title = persisted.title
self.query = persisted.query
self.tabType = persisted.tabType
self.tableName = persisted.tableName
self.primaryKeyColumn = nil
// Initialize runtime state with defaults
self.lastExecutedAt = nil
self.rowBuffer = RowBuffer()
self.executionTime = nil
self.rowsAffected = 0
self.errorMessage = nil
self.isExecuting = false
self.isEditable = persisted.tabType == .table && !persisted.isView
self.isView = persisted.isView
self.databaseName = persisted.databaseName
self.showStructure = false
self.pendingChanges = TabPendingChanges()
self.selectedRowIndices = []
self.sortState = SortState()
self.hasUserInteraction = false
self.pagination = PaginationState()
self.filterState = TabFilterState()
self.columnLayout = ColumnLayoutState()
self.isPreview = false
self.resultVersion = 0
self.metadataVersion = 0
}
/// Build a clean base query for a table tab (no filters/sort).
/// Used when restoring table tabs from persistence to avoid stale WHERE clauses.
@MainActor static func buildBaseTableQuery(
tableName: String,
databaseType: DatabaseType,
quoteIdentifier: ((String) -> String)? = nil
) -> String {
let quote = quoteIdentifier ?? quoteIdentifierFromDialect(PluginManager.shared.sqlDialect(for: databaseType))
let pageSize = AppSettingsManager.shared.dataGrid.defaultPageSize
// Use plugin's query builder when available (NoSQL drivers like etcd, Redis)
if let pluginDriver = PluginManager.shared.queryBuildingDriver(for: databaseType),
let pluginQuery = pluginDriver.buildBrowseQuery(
table: tableName, sortColumns: [], columns: [], limit: pageSize, offset: 0
) {
return pluginQuery
}
switch PluginManager.shared.editorLanguage(for: databaseType) {
case .javascript:
let escaped = tableName.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
return "db[\"\(escaped)\"].find({}).limit(\(pageSize))"
case .bash:
return "SCAN 0 MATCH * COUNT \(pageSize)"
default:
let quotedName = quote(tableName)
switch PluginManager.shared.paginationStyle(for: databaseType) {
case .offsetFetch:
let orderBy = PluginManager.shared.offsetFetchOrderBy(for: databaseType)
return "SELECT * FROM \(quotedName) \(orderBy) OFFSET 0 ROWS FETCH NEXT \(pageSize) ROWS ONLY;"
case .limit:
return "SELECT * FROM \(quotedName) LIMIT \(pageSize);"
}
}
}
/// Maximum query size to persist (500KB). Queries larger than this are typically
/// imported SQL dumps — serializing them to JSON blocks the main thread.
static let maxPersistableQuerySize = 500_000
/// Convert tab to persisted format for storage
func toPersistedTab() -> PersistedTab {
// Truncate very large queries to prevent JSON encoding from blocking main thread
let persistedQuery: String
if (query as NSString).length > Self.maxPersistableQuerySize {
persistedQuery = ""
} else {
persistedQuery = query
}
return PersistedTab(
id: id,
title: title,
query: persistedQuery,
tabType: tabType,
tableName: tableName,
isView: isView,
databaseName: databaseName
)
}
static func == (lhs: QueryTab, rhs: QueryTab) -> Bool {
lhs.id == rhs.id
&& lhs.title == rhs.title
&& lhs.isExecuting == rhs.isExecuting
&& lhs.errorMessage == rhs.errorMessage
&& lhs.executionTime == rhs.executionTime
&& lhs.resultVersion == rhs.resultVersion
&& lhs.pagination == rhs.pagination
&& lhs.sortState == rhs.sortState
&& lhs.showStructure == rhs.showStructure
&& lhs.isEditable == rhs.isEditable
&& lhs.isView == rhs.isView
&& lhs.tabType == rhs.tabType
&& lhs.rowsAffected == rhs.rowsAffected
&& lhs.isPreview == rhs.isPreview
&& lhs.hasUserInteraction == rhs.hasUserInteraction
}
}
/// Manager for query tabs
@MainActor @Observable
final class QueryTabManager {
var tabs: [QueryTab] = []
var selectedTabId: UUID?
var tabIds: [UUID] { tabs.map(\.id) }
var selectedTab: QueryTab? {
guard let id = selectedTabId else { return tabs.first }
return tabs.first { $0.id == id }
}
var selectedTabIndex: Int? {
guard let id = selectedTabId else { return nil }
return tabs.firstIndex { $0.id == id }
}
init() {
// Start with no tabs - shows empty state
tabs = []
selectedTabId = nil
}
// MARK: - Tab Management
func addTab(initialQuery: String? = nil, title: String? = nil, databaseName: String = "") {
let queryCount = tabs.count(where: { $0.tabType == .query })
let tabTitle = title ?? "Query \(queryCount + 1)"
var newTab = QueryTab(title: tabTitle, tabType: .query)
// If initialQuery provided, use it; otherwise tab starts empty
if let query = initialQuery {
newTab.query = query
newTab.hasUserInteraction = true // Mark as having content
}
newTab.databaseName = databaseName
tabs.append(newTab)
selectedTabId = newTab.id
}
func addTableTab(
tableName: String,
databaseType: DatabaseType = .mysql,
databaseName: String = "",
quoteIdentifier: ((String) -> String)? = nil
) {
// Check if table tab already exists (match on databaseName)
if let existingTab = tabs.first(where: {
$0.tabType == .table && $0.tableName == tableName && $0.databaseName == databaseName
}) {
selectedTabId = existingTab.id
return
}
let pageSize = AppSettingsManager.shared.dataGrid.defaultPageSize
let query = QueryTab.buildBaseTableQuery(
tableName: tableName, databaseType: databaseType, quoteIdentifier: quoteIdentifier
)
var newTab = QueryTab(
title: tableName,
query: query,
tabType: .table,
tableName: tableName
)
newTab.pagination = PaginationState(pageSize: pageSize)
newTab.databaseName = databaseName
tabs.append(newTab)
selectedTabId = newTab.id
}
func addPreviewTableTab(
tableName: String,
databaseType: DatabaseType = .mysql,
databaseName: String = "",
quoteIdentifier: ((String) -> String)? = nil
) {
let pageSize = AppSettingsManager.shared.dataGrid.defaultPageSize
let query = QueryTab.buildBaseTableQuery(
tableName: tableName, databaseType: databaseType, quoteIdentifier: quoteIdentifier
)
var newTab = QueryTab(
title: tableName,
query: query,
tabType: .table,
tableName: tableName
)
newTab.pagination = PaginationState(pageSize: pageSize)
newTab.databaseName = databaseName
newTab.isPreview = true
tabs.append(newTab)
selectedTabId = newTab.id
}
/// Replace the currently selected tab's content with a new table.
/// - Returns: `true` if the replacement happened (caller should run the query),
/// `false` if there is no selected tab.
@discardableResult
func replaceTabContent(
tableName: String, databaseType: DatabaseType = .mysql,
isView: Bool = false, databaseName: String = "",
isPreview: Bool = false,
quoteIdentifier: ((String) -> String)? = nil
) -> Bool {
guard let selectedId = selectedTabId,
let selectedIndex = tabs.firstIndex(where: { $0.id == selectedId })
else {
return false
}
let query = QueryTab.buildBaseTableQuery(
tableName: tableName,
databaseType: databaseType,
quoteIdentifier: quoteIdentifier
)
let pageSize = AppSettingsManager.shared.dataGrid.defaultPageSize
// Build locally and write back once to avoid 14 CoW copies (UI-11).
var tab = tabs[selectedIndex]
tab.rowBuffer = RowBuffer()
tab.title = tableName
tab.tableName = tableName
tab.query = query
tab.resultVersion += 1
tab.executionTime = nil
tab.errorMessage = nil
tab.lastExecutedAt = nil
tab.showStructure = false
tab.sortState = SortState()
tab.selectedRowIndices = []
tab.pendingChanges = TabPendingChanges()
tab.hasUserInteraction = false
tab.isView = isView
tab.isEditable = !isView
tab.filterState = TabFilterState()
tab.columnLayout = ColumnLayoutState()
tab.pagination = PaginationState(pageSize: pageSize)
tab.databaseName = databaseName
tab.isPreview = isPreview
tabs[selectedIndex] = tab
return true
}
func updateTab(_ tab: QueryTab) {
if let index = tabs.firstIndex(where: { $0.id == tab.id }) {
tabs[index] = tab
}
}
}