-
-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathStructureChangeManager.swift
More file actions
886 lines (778 loc) · 33.6 KB
/
StructureChangeManager.swift
File metadata and controls
886 lines (778 loc) · 33.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
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
//
// StructureChangeManager.swift
// TablePro
//
// Manager for tracking structure/schema changes with O(1) lookups.
// Mirrors DataChangeManager architecture for schema modifications.
//
import Foundation
import Observation
/// Manager for tracking and applying schema changes
@MainActor @Observable
final class StructureChangeManager: ChangeManaging {
private(set) var pendingChanges: [SchemaChangeIdentifier: SchemaChange] = [:]
@ObservationIgnored private var changeOrder: [SchemaChangeIdentifier] = []
private(set) var validationErrors: [SchemaChangeIdentifier: String] = [:]
var hasChanges: Bool { !pendingChanges.isEmpty }
var reloadVersion: Int = 0
// Current state (loaded from database)
private(set) var currentColumns: [EditableColumnDefinition] = []
private(set) var currentIndexes: [EditableIndexDefinition] = []
private(set) var currentForeignKeys: [EditableForeignKeyDefinition] = []
private(set) var currentPrimaryKey: [String] = []
// Working state (includes uncommitted changes + placeholders)
var workingColumns: [EditableColumnDefinition] = []
var workingIndexes: [EditableIndexDefinition] = []
var workingForeignKeys: [EditableForeignKeyDefinition] = []
var workingPrimaryKey: [String] = []
var tableName: String?
var databaseType: DatabaseType = .mysql
// MARK: - Undo/Redo Support
private let undoManager: UndoManager = {
let manager = UndoManager()
manager.levelsOfUndo = 100
return manager
}()
private var visualStateCache: [VisualStateCacheKey: RowVisualState] = [:]
var canUndo: Bool { undoManager.canUndo }
var canRedo: Bool { undoManager.canRedo }
// MARK: - Load Schema
func loadSchema(
tableName: String,
columns: [ColumnInfo],
indexes: [IndexInfo],
foreignKeys: [ForeignKeyInfo],
primaryKey: [String],
databaseType: DatabaseType
) {
self.tableName = tableName
self.databaseType = databaseType
// Convert to definitions
self.currentColumns = columns.map { EditableColumnDefinition.from($0) }
// Merge primary key info into columns (handles PostgreSQL where isPrimaryKey is always false)
if !primaryKey.isEmpty {
for i in currentColumns.indices {
currentColumns[i].isPrimaryKey = primaryKey.contains(currentColumns[i].name)
}
}
self.currentIndexes = indexes.map { EditableIndexDefinition.from($0) }
// Group foreign keys by name to merge multi-column FKs into single definitions
let groupedFKs = Dictionary(grouping: foreignKeys, by: { $0.name })
self.currentForeignKeys = groupedFKs.keys.sorted().compactMap { name -> EditableForeignKeyDefinition? in
guard let fkInfos = groupedFKs[name], let first = fkInfos.first else { return nil }
return EditableForeignKeyDefinition(
id: first.id,
name: first.name,
columns: fkInfos.map { $0.column },
referencedTable: first.referencedTable,
referencedColumns: fkInfos.map { $0.referencedColumn },
referencedSchema: first.referencedSchema,
onDelete: EditableForeignKeyDefinition.ReferentialAction(rawValue: first.onDelete.uppercased()) ?? .noAction,
onUpdate: EditableForeignKeyDefinition.ReferentialAction(rawValue: first.onUpdate.uppercased()) ?? .noAction
)
}
self.currentPrimaryKey = primaryKey
// Reset working state
resetWorkingState()
pendingChanges.removeAll()
changeOrder.removeAll()
validationErrors.removeAll()
undoManager.removeAllActions()
// Increment reloadVersion to trigger DataGridView column width recalculation
// This ensures columns auto-size based on actual cell content after initial load
reloadVersion += 1
}
private func resetWorkingState() {
workingColumns = currentColumns
workingIndexes = currentIndexes
workingForeignKeys = currentForeignKeys
workingPrimaryKey = currentPrimaryKey
}
private func trackChangeKey(_ key: SchemaChangeIdentifier) {
if !changeOrder.contains(key) {
changeOrder.append(key)
}
}
private func untrackChangeKey(_ key: SchemaChangeIdentifier) {
changeOrder.removeAll { $0 == key }
}
// MARK: - Add New Rows
func addNewColumn() {
let placeholder = EditableColumnDefinition.placeholder()
workingColumns.append(placeholder)
let key = SchemaChangeIdentifier.column(placeholder.id)
pendingChanges[key] = .addColumn(placeholder)
trackChangeKey(key)
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnAdd(column: placeholder))
}
undoManager.setActionName(String(localized: "Add Column"))
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
func addNewIndex() {
let placeholder = EditableIndexDefinition.placeholder()
workingIndexes.append(placeholder)
let key = SchemaChangeIdentifier.index(placeholder.id)
pendingChanges[key] = .addIndex(placeholder)
trackChangeKey(key)
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexAdd(index: placeholder))
}
undoManager.setActionName(String(localized: "Add Index"))
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
func addNewForeignKey() {
let placeholder = EditableForeignKeyDefinition.placeholder()
workingForeignKeys.append(placeholder)
let key = SchemaChangeIdentifier.foreignKey(placeholder.id)
pendingChanges[key] = .addForeignKey(placeholder)
trackChangeKey(key)
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyAdd(fk: placeholder))
}
undoManager.setActionName(String(localized: "Add Foreign Key"))
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
// MARK: - Paste Operations (public methods for adding copied items)
func addColumn(_ column: EditableColumnDefinition) {
workingColumns.append(column)
let key = SchemaChangeIdentifier.column(column.id)
pendingChanges[key] = .addColumn(column)
trackChangeKey(key)
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnAdd(column: column))
}
undoManager.setActionName(String(localized: "Add Column"))
reloadVersion += 1
rebuildVisualStateCache()
}
func addIndex(_ index: EditableIndexDefinition) {
workingIndexes.append(index)
let key = SchemaChangeIdentifier.index(index.id)
pendingChanges[key] = .addIndex(index)
trackChangeKey(key)
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexAdd(index: index))
}
undoManager.setActionName(String(localized: "Add Index"))
reloadVersion += 1
rebuildVisualStateCache()
}
func addForeignKey(_ foreignKey: EditableForeignKeyDefinition) {
workingForeignKeys.append(foreignKey)
let key = SchemaChangeIdentifier.foreignKey(foreignKey.id)
pendingChanges[key] = .addForeignKey(foreignKey)
trackChangeKey(key)
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyAdd(fk: foreignKey))
}
undoManager.setActionName(String(localized: "Add Foreign Key"))
reloadVersion += 1
rebuildVisualStateCache()
}
// MARK: - Column Operations
func updateColumn(id: UUID, with newColumn: EditableColumnDefinition) {
// Capture old working state for undo BEFORE modifying
if let workingIndex = workingColumns.firstIndex(where: { $0.id == id }) {
let oldWorking = workingColumns[workingIndex]
if oldWorking != newColumn {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnEdit(id: id, old: oldWorking, new: newColumn))
}
undoManager.setActionName(String(localized: "Edit Column"))
}
}
let key = SchemaChangeIdentifier.column(id)
if let index = currentColumns.firstIndex(where: { $0.id == id }) {
let oldColumn = currentColumns[index]
if oldColumn != newColumn {
pendingChanges[key] = .modifyColumn(old: oldColumn, new: newColumn)
trackChangeKey(key)
} else {
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
} else {
pendingChanges[key] = .addColumn(newColumn)
trackChangeKey(key)
}
if let index = workingColumns.firstIndex(where: { $0.id == id }) {
workingColumns[index] = newColumn
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
func deleteColumn(id: UUID) {
let key = SchemaChangeIdentifier.column(id)
if let column = currentColumns.first(where: { $0.id == id }) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnDelete(column: column, at: nil))
}
undoManager.setActionName(String(localized: "Delete Column"))
pendingChanges[key] = .deleteColumn(column)
trackChangeKey(key)
} else {
let rowIndex = workingColumns.firstIndex(where: { $0.id == id })
if let column = workingColumns.first(where: { $0.id == id }) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnDelete(column: column, at: rowIndex))
}
undoManager.setActionName(String(localized: "Delete Column"))
}
workingColumns.removeAll { $0.id == id }
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
// MARK: - Index Operations
func updateIndex(id: UUID, with newIndex: EditableIndexDefinition) {
// Capture old working state for undo BEFORE modifying
if let workingIdx = workingIndexes.firstIndex(where: { $0.id == id }) {
let oldWorking = workingIndexes[workingIdx]
if oldWorking != newIndex {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexEdit(id: id, old: oldWorking, new: newIndex))
}
undoManager.setActionName(String(localized: "Edit Index"))
}
}
let key = SchemaChangeIdentifier.index(id)
if let index = currentIndexes.firstIndex(where: { $0.id == id }) {
let oldIndex = currentIndexes[index]
if oldIndex != newIndex {
pendingChanges[key] = .modifyIndex(old: oldIndex, new: newIndex)
trackChangeKey(key)
} else {
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
} else {
pendingChanges[key] = .addIndex(newIndex)
trackChangeKey(key)
}
if let index = workingIndexes.firstIndex(where: { $0.id == id }) {
workingIndexes[index] = newIndex
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
func deleteIndex(id: UUID) {
let key = SchemaChangeIdentifier.index(id)
if let index = currentIndexes.first(where: { $0.id == id }) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexDelete(index: index, at: nil))
}
undoManager.setActionName(String(localized: "Delete Index"))
pendingChanges[key] = .deleteIndex(index)
trackChangeKey(key)
} else {
let rowIndex = workingIndexes.firstIndex(where: { $0.id == id })
if let index = workingIndexes.first(where: { $0.id == id }) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexDelete(index: index, at: rowIndex))
}
undoManager.setActionName(String(localized: "Delete Index"))
}
workingIndexes.removeAll { $0.id == id }
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
// MARK: - Foreign Key Operations
func updateForeignKey(id: UUID, with newFK: EditableForeignKeyDefinition) {
// Capture old working state for undo BEFORE modifying
if let workingIdx = workingForeignKeys.firstIndex(where: { $0.id == id }) {
let oldWorking = workingForeignKeys[workingIdx]
if oldWorking != newFK {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyEdit(id: id, old: oldWorking, new: newFK))
}
undoManager.setActionName(String(localized: "Edit Foreign Key"))
}
}
let key = SchemaChangeIdentifier.foreignKey(id)
if let index = currentForeignKeys.firstIndex(where: { $0.id == id }) {
let oldFK = currentForeignKeys[index]
if oldFK != newFK {
pendingChanges[key] = .modifyForeignKey(old: oldFK, new: newFK)
trackChangeKey(key)
} else {
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
} else {
pendingChanges[key] = .addForeignKey(newFK)
trackChangeKey(key)
}
if let index = workingForeignKeys.firstIndex(where: { $0.id == id }) {
workingForeignKeys[index] = newFK
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
func deleteForeignKey(id: UUID) {
let key = SchemaChangeIdentifier.foreignKey(id)
if let fk = currentForeignKeys.first(where: { $0.id == id }) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyDelete(fk: fk, at: nil))
}
undoManager.setActionName(String(localized: "Delete Foreign Key"))
pendingChanges[key] = .deleteForeignKey(fk)
trackChangeKey(key)
} else {
let rowIndex = workingForeignKeys.firstIndex(where: { $0.id == id })
if let fk = workingForeignKeys.first(where: { $0.id == id }) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyDelete(fk: fk, at: rowIndex))
}
undoManager.setActionName(String(localized: "Delete Foreign Key"))
}
workingForeignKeys.removeAll { $0.id == id }
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
// MARK: - Primary Key Operations
func updatePrimaryKey(_ columns: [String]) {
// Push undo action before modifying
if columns != workingPrimaryKey {
let oldPK = workingPrimaryKey
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.primaryKeyChange(old: oldPK, new: columns))
}
undoManager.setActionName(String(localized: "Change Primary Key"))
}
let key = SchemaChangeIdentifier.primaryKey
if columns != currentPrimaryKey {
pendingChanges[key] = .modifyPrimaryKey(old: currentPrimaryKey, new: columns)
trackChangeKey(key)
} else {
pendingChanges.removeValue(forKey: key)
untrackChangeKey(key)
}
workingPrimaryKey = columns
validate()
}
// MARK: - Validation
private func validate() {
validationErrors.removeAll()
// Validate all columns have name and dataType (no invalid placeholders)
for column in workingColumns {
if !column.isValid {
validationErrors[.column(column.id)] = "Column must have a name and data type"
}
}
// Validate column names are unique
let columnNames = workingColumns.filter { column in
column.isValid && !isColumnPendingDeletion(column.id)
}.map { $0.name }
let duplicateColumns = Dictionary(grouping: columnNames, by: { $0 })
.filter { $0.value.count > 1 }
.map { $0.key }
for duplicate in duplicateColumns {
for column in workingColumns.filter({ $0.name == duplicate && !isColumnPendingDeletion($0.id) }) {
validationErrors[.column(column.id)] = "Duplicate column name: \(duplicate)"
}
}
// Validate all indexes have required fields
for index in workingIndexes {
if !index.isValid {
validationErrors[.index(index.id)] = "Index must have a name and at least one column"
}
}
// Validate all foreign keys have required fields
for fk in workingForeignKeys {
if !fk.isValid {
validationErrors[.foreignKey(fk.id)] = "Foreign key must have name, columns, and referenced table"
}
}
// Validate index names are unique
let indexNames = workingIndexes.filter { $0.isValid }.map { $0.name }
let duplicateIndexes = Dictionary(grouping: indexNames, by: { $0 })
.filter { $0.value.count > 1 }
.map { $0.key }
for duplicate in duplicateIndexes {
for index in workingIndexes.filter({ $0.name == duplicate }) {
validationErrors[.index(index.id)] = "Duplicate index name: \(duplicate)"
}
}
// Validate index columns exist
for index in workingIndexes.filter({ $0.isValid }) {
for columnName in index.columns {
if !columnNames.contains(columnName) {
validationErrors[.index(index.id)] = "Index references non-existent column: \(columnName)"
}
}
}
// Validate foreign key columns exist
for fk in workingForeignKeys.filter({ $0.isValid }) {
for columnName in fk.columns {
if !columnNames.contains(columnName) {
validationErrors[.foreignKey(fk.id)] = "Foreign key references non-existent column: \(columnName)"
}
}
}
// Validate primary key columns exist
for columnName in workingPrimaryKey {
if !columnNames.contains(columnName) {
validationErrors[.primaryKey] = "Primary key references non-existent column: \(columnName)"
}
}
}
private func isColumnPendingDeletion(_ id: UUID) -> Bool {
if case .deleteColumn = pendingChanges[.column(id)] {
return true
}
return false
}
// MARK: - State Management
var canCommit: Bool {
hasChanges && validationErrors.isEmpty
}
func discardChanges() {
pendingChanges.removeAll()
changeOrder.removeAll()
validationErrors.removeAll()
resetWorkingState()
reloadVersion += 1
rebuildVisualStateCache()
undoManager.removeAllActions()
}
func getChangesArray() -> [SchemaChange] {
changeOrder.compactMap { pendingChanges[$0] }
}
// MARK: - Undo/Redo Operations
func undo() {
guard undoManager.canUndo else { return }
undoManager.undo()
}
func redo() {
guard undoManager.canRedo else { return }
undoManager.redo()
}
private func applySchemaUndo(_ action: SchemaUndoAction) {
switch action {
case .columnEdit(let id, let old, let new):
applyColumnEditUndo(id: id, old: old, new: new)
case .columnAdd(let column):
applyColumnAddUndo(column: column)
case .columnDelete(let column, let at):
applyColumnDeleteUndo(column: column, at: at)
case .indexEdit(let id, let old, let new):
applyIndexEditUndo(id: id, old: old, new: new)
case .indexAdd(let index):
applyIndexAddUndo(index: index)
case .indexDelete(let index, let at):
applyIndexDeleteUndo(index: index, at: at)
case .foreignKeyEdit(let id, let old, let new):
applyForeignKeyEditUndo(id: id, old: old, new: new)
case .foreignKeyAdd(let fk):
applyForeignKeyAddUndo(fk: fk)
case .foreignKeyDelete(let fk, let at):
applyForeignKeyDeleteUndo(fk: fk, at: at)
case .primaryKeyChange(let old, _):
applyPrimaryKeyChangeUndo(old: old)
}
validate()
reloadVersion += 1
rebuildVisualStateCache()
}
private func applyColumnEditUndo(id: UUID, old: EditableColumnDefinition, new: EditableColumnDefinition) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnEdit(id: id, old: new, new: old))
}
undoManager.setActionName(String(localized: "Edit Column"))
let colKey = SchemaChangeIdentifier.column(id)
if let index = workingColumns.firstIndex(where: { $0.id == id }) {
workingColumns[index] = old
if let currentIndex = currentColumns.firstIndex(where: { $0.id == id }) {
let current = currentColumns[currentIndex]
if old != current {
pendingChanges[colKey] = .modifyColumn(old: current, new: old)
trackChangeKey(colKey)
} else {
pendingChanges.removeValue(forKey: colKey)
untrackChangeKey(colKey)
}
} else {
pendingChanges[colKey] = .addColumn(old)
trackChangeKey(colKey)
}
}
}
private func applyColumnAddUndo(column: EditableColumnDefinition) {
let removedIndex = workingColumns.firstIndex(where: { $0.id == column.id })
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnDelete(column: column, at: removedIndex))
}
undoManager.setActionName(String(localized: "Add Column"))
let addColKey = SchemaChangeIdentifier.column(column.id)
if currentColumns.contains(where: { $0.id == column.id }) {
pendingChanges[addColKey] = .deleteColumn(column)
trackChangeKey(addColKey)
} else {
workingColumns.removeAll { $0.id == column.id }
pendingChanges.removeValue(forKey: addColKey)
untrackChangeKey(addColKey)
}
}
private func applyColumnDeleteUndo(column: EditableColumnDefinition, at: Int?) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.columnAdd(column: column))
}
undoManager.setActionName(String(localized: "Delete Column"))
let delColKey = SchemaChangeIdentifier.column(column.id)
if currentColumns.contains(where: { $0.id == column.id }) {
pendingChanges.removeValue(forKey: delColKey)
untrackChangeKey(delColKey)
} else {
if let at, at < workingColumns.count {
workingColumns.insert(column, at: at)
} else {
workingColumns.append(column)
}
pendingChanges[delColKey] = .addColumn(column)
trackChangeKey(delColKey)
}
}
private func applyIndexEditUndo(id: UUID, old: EditableIndexDefinition, new: EditableIndexDefinition) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexEdit(id: id, old: new, new: old))
}
undoManager.setActionName(String(localized: "Edit Index"))
let idxEditKey = SchemaChangeIdentifier.index(id)
if let idx = workingIndexes.firstIndex(where: { $0.id == id }) {
workingIndexes[idx] = old
if let currentIdx = currentIndexes.firstIndex(where: { $0.id == id }) {
let current = currentIndexes[currentIdx]
if old != current {
pendingChanges[idxEditKey] = .modifyIndex(old: current, new: old)
trackChangeKey(idxEditKey)
} else {
pendingChanges.removeValue(forKey: idxEditKey)
untrackChangeKey(idxEditKey)
}
} else {
pendingChanges[idxEditKey] = .addIndex(old)
trackChangeKey(idxEditKey)
}
}
}
private func applyIndexAddUndo(index: EditableIndexDefinition) {
let removedIndex = workingIndexes.firstIndex(where: { $0.id == index.id })
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexDelete(index: index, at: removedIndex))
}
undoManager.setActionName(String(localized: "Add Index"))
let idxAddKey = SchemaChangeIdentifier.index(index.id)
if currentIndexes.contains(where: { $0.id == index.id }) {
pendingChanges[idxAddKey] = .deleteIndex(index)
trackChangeKey(idxAddKey)
} else {
workingIndexes.removeAll { $0.id == index.id }
pendingChanges.removeValue(forKey: idxAddKey)
untrackChangeKey(idxAddKey)
}
}
private func applyIndexDeleteUndo(index: EditableIndexDefinition, at: Int?) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.indexAdd(index: index))
}
undoManager.setActionName(String(localized: "Delete Index"))
let idxDelKey = SchemaChangeIdentifier.index(index.id)
if currentIndexes.contains(where: { $0.id == index.id }) {
pendingChanges.removeValue(forKey: idxDelKey)
untrackChangeKey(idxDelKey)
} else {
if let at, at < workingIndexes.count {
workingIndexes.insert(index, at: at)
} else {
workingIndexes.append(index)
}
pendingChanges[idxDelKey] = .addIndex(index)
trackChangeKey(idxDelKey)
}
}
private func applyForeignKeyEditUndo(
id: UUID,
old: EditableForeignKeyDefinition,
new: EditableForeignKeyDefinition
) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyEdit(id: id, old: new, new: old))
}
undoManager.setActionName(String(localized: "Edit Foreign Key"))
let fkEditKey = SchemaChangeIdentifier.foreignKey(id)
if let idx = workingForeignKeys.firstIndex(where: { $0.id == id }) {
workingForeignKeys[idx] = old
if let currentIdx = currentForeignKeys.firstIndex(where: { $0.id == id }) {
let current = currentForeignKeys[currentIdx]
if old != current {
pendingChanges[fkEditKey] = .modifyForeignKey(old: current, new: old)
trackChangeKey(fkEditKey)
} else {
pendingChanges.removeValue(forKey: fkEditKey)
untrackChangeKey(fkEditKey)
}
} else {
pendingChanges[fkEditKey] = .addForeignKey(old)
trackChangeKey(fkEditKey)
}
}
}
private func applyForeignKeyAddUndo(fk: EditableForeignKeyDefinition) {
let removedIndex = workingForeignKeys.firstIndex(where: { $0.id == fk.id })
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyDelete(fk: fk, at: removedIndex))
}
undoManager.setActionName(String(localized: "Add Foreign Key"))
let fkAddKey = SchemaChangeIdentifier.foreignKey(fk.id)
if currentForeignKeys.contains(where: { $0.id == fk.id }) {
pendingChanges[fkAddKey] = .deleteForeignKey(fk)
trackChangeKey(fkAddKey)
} else {
workingForeignKeys.removeAll { $0.id == fk.id }
pendingChanges.removeValue(forKey: fkAddKey)
untrackChangeKey(fkAddKey)
}
}
private func applyForeignKeyDeleteUndo(fk: EditableForeignKeyDefinition, at: Int?) {
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.foreignKeyAdd(fk: fk))
}
undoManager.setActionName(String(localized: "Delete Foreign Key"))
let fkDelKey = SchemaChangeIdentifier.foreignKey(fk.id)
if currentForeignKeys.contains(where: { $0.id == fk.id }) {
pendingChanges.removeValue(forKey: fkDelKey)
untrackChangeKey(fkDelKey)
} else {
if let at, at < workingForeignKeys.count {
workingForeignKeys.insert(fk, at: at)
} else {
workingForeignKeys.append(fk)
}
pendingChanges[fkDelKey] = .addForeignKey(fk)
trackChangeKey(fkDelKey)
}
}
private func applyPrimaryKeyChangeUndo(old: [String]) {
let current = workingPrimaryKey
undoManager.registerUndo(withTarget: self) { target in
target.applySchemaUndo(.primaryKeyChange(old: current, new: old))
}
undoManager.setActionName(String(localized: "Change Primary Key"))
workingPrimaryKey = old
let pkKey = SchemaChangeIdentifier.primaryKey
if workingPrimaryKey != currentPrimaryKey {
pendingChanges[pkKey] = .modifyPrimaryKey(old: currentPrimaryKey, new: workingPrimaryKey)
trackChangeKey(pkKey)
} else {
pendingChanges.removeValue(forKey: pkKey)
untrackChangeKey(pkKey)
}
}
// MARK: - Visual State Management
func getVisualState(for row: Int, tab: StructureTab) -> RowVisualState {
let cacheKey = VisualStateCacheKey(tab: tab, row: row)
if let cached = visualStateCache[cacheKey] {
return cached
}
let state: RowVisualState
switch tab {
case .columns:
guard row < workingColumns.count else { return .empty }
let column = workingColumns[row]
let change = pendingChanges[.column(column.id)]
let isDeleted = change?.isDelete ?? false
let isInserted = !currentColumns.contains(where: { $0.id == column.id })
let isModified = change != nil && !isDeleted && !isInserted
state = RowVisualState(
isDeleted: isDeleted,
isInserted: isInserted,
modifiedColumns: isModified ? Set(0..<6) : []
)
case .indexes:
guard row < workingIndexes.count else { return .empty }
let index = workingIndexes[row]
let change = pendingChanges[.index(index.id)]
let isDeleted = change?.isDelete ?? false
let isInserted = !currentIndexes.contains(where: { $0.id == index.id })
let isModified = change != nil && !isDeleted && !isInserted
state = RowVisualState(
isDeleted: isDeleted,
isInserted: isInserted,
modifiedColumns: isModified ? Set(0..<5) : []
)
case .foreignKeys:
guard row < workingForeignKeys.count else { return .empty }
let fk = workingForeignKeys[row]
let change = pendingChanges[.foreignKey(fk.id)]
let isDeleted = change?.isDelete ?? false
let isInserted = !currentForeignKeys.contains(where: { $0.id == fk.id })
let isModified = change != nil && !isDeleted && !isInserted
state = RowVisualState(
isDeleted: isDeleted,
isInserted: isInserted,
modifiedColumns: isModified ? Set(0..<7) : []
)
case .ddl:
state = .empty
case .parts:
state = .empty
}
visualStateCache[cacheKey] = state
return state
}
func rebuildVisualStateCache() {
visualStateCache.removeAll()
}
private struct VisualStateCacheKey: Hashable {
let tab: StructureTab
let row: Int
}
// MARK: - ChangeManaging Conformance (Data-Specific No-Ops)
var rowChanges: [RowChange] { [] }
var insertedRowIndices: Set<Int> { [] }
func isRowDeleted(_ rowIndex: Int) -> Bool { false }
func recordCellChange(
rowIndex: Int,
columnIndex: Int,
columnName: String,
oldValue: String?,
newValue: String?,
originalRow: [String?]?
) {}
func undoRowDeletion(rowIndex: Int) {}
func undoRowInsertion(rowIndex: Int) {}
}
// MARK: - Schema Undo Action
enum SchemaUndoAction {
case columnEdit(id: UUID, old: EditableColumnDefinition, new: EditableColumnDefinition)
case columnAdd(column: EditableColumnDefinition)
case columnDelete(column: EditableColumnDefinition, at: Int?)
case indexEdit(id: UUID, old: EditableIndexDefinition, new: EditableIndexDefinition)
case indexAdd(index: EditableIndexDefinition)
case indexDelete(index: EditableIndexDefinition, at: Int?)
case foreignKeyEdit(id: UUID, old: EditableForeignKeyDefinition, new: EditableForeignKeyDefinition)
case foreignKeyAdd(fk: EditableForeignKeyDefinition)
case foreignKeyDelete(fk: EditableForeignKeyDefinition, at: Int?)
case primaryKeyChange(old: [String], new: [String])
}