Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .claude/rules/data-sync-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,9 @@ This path holds user data. A silent wrong answer here looks exactly like an empt
| Approved sign-ins with this Mac's own credentials (Entra, AWS profile or SSO, Google ADC or OAuth, Kerberos, `~/.pgpass`), per connection, field values and destination digest | UserDefaults `com.TablePro.localCredentialApprovals`, plus `com.TablePro.localCredentialApprovalsMigrated` for the one-time approval of this Mac's rows; device-local, never synced | `ConnectionApprovalStore.localCredentials` |
| Snowflake SSO and MFA tokens, per host and user. A bare account's `NAME.USER` item stays for 0.83.1, which reads only that key | Keychain, device-local | `SnowflakeTokenCache` |
| Whether `connections.json` was ever given an integrity tag, so a deleted tag reads as modified | Keychain `com.TablePro.connectionStoreStamped.<sha256 of path>`, device-local | `ConnectionStoreIntegrity` |
| The last copy of `connections.json` and `credentialProfiles.json` that parsed, taken before each save with its tag, restored when the file no longer parses | `<file>.backup` and `<file>.backup.hmac` beside the file, device-local, never synced | `IntegrityStampedFileStore` |
| A `connections.json` or `credentialProfiles.json` that no longer parsed, set aside when its backup was restored; the next one replaces it | `<file>.unreadable` beside the file, device-local, never synced | `IntegrityStampedFileStore` |
| Records this build cannot read from a file changed outside TablePro, which a save would otherwise sign; added to, never replaced | `<file>.unreadable-records` beside the file, device-local, never synced | `IntegrityStampedFileStore` |
| Whether Local only connections' secrets were copied to device-only items | UserDefaults `com.TablePro.localOnlySecretsKeptOnDevice`, device-local, never synced | `ConnectionStorage` |
| iCloud Keychain copies of Local only secrets the keychain refused to remove, retried at launch | UserDefaults `com.TablePro.localOnlySyncedCopiesPendingRemoval`, device-local, never synced | `ConnectionStorage` |
| Whether plugin secure fields moved out of `connections.json` into the Keychain, set only when every field moved and the save succeeded | UserDefaults `com.TablePro.pluginSecureFieldsMovedToKeychain`, device-local, never synced | `ConnectionStorage` |
Expand Down
69 changes: 32 additions & 37 deletions apple/TablePro/Core/ChangeTracking/DataChangeManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ final class DataChangeManager: ObservableObject, ChangeManaging {

// MARK: - Undo/Redo Properties

var undoManager: UndoManager? { undoManagerProvider?() }
var canUndo: Bool { undoManagerProvider?()?.canUndo ?? false }
var canRedo: Bool { undoManagerProvider?()?.canRedo ?? false }

Expand Down Expand Up @@ -188,14 +189,16 @@ final class DataChangeManager: ObservableObject, ChangeManaging {
columnTypeNames: [String: String] = [:],
triggerReload: Bool = true
) {
self.tableName = tableName
self.schemaName = schemaName
self.columns = columns
self.primaryKeyColumns = primaryKeyColumns
self.databaseType = databaseType
self.generatedColumns = generatedColumns
self.rowMatchPolicy = rowMatchPolicy
self.columnTypeNames = columnTypeNames
describeTable(
tableName: tableName,
schemaName: schemaName,
columns: columns,
primaryKeyColumns: primaryKeyColumns,
databaseType: databaseType,
generatedColumns: generatedColumns,
rowMatchPolicy: rowMatchPolicy,
columnTypeNames: columnTypeNames
)

discardUndoHistory()
objectWillChange.send()
Expand All @@ -207,6 +210,27 @@ final class DataChangeManager: ObservableObject, ChangeManaging {
}
}

// What the staged edits are written against, set without touching them or the undo history.
func describeTable(
tableName: String,
schemaName: String?,
columns: [String],
primaryKeyColumns: [String],
databaseType: DatabaseType,
generatedColumns: Set<String>,
rowMatchPolicy: RowMatchPolicy,
columnTypeNames: [String: String]
) {
if self.tableName != tableName { self.tableName = tableName }
if self.schemaName != schemaName { self.schemaName = schemaName }
if self.columns != columns { self.columns = columns }
if self.primaryKeyColumns != primaryKeyColumns { self.primaryKeyColumns = primaryKeyColumns }
if self.databaseType != databaseType { self.databaseType = databaseType }
if self.generatedColumns != generatedColumns { self.generatedColumns = generatedColumns }
if self.rowMatchPolicy != rowMatchPolicy { self.rowMatchPolicy = rowMatchPolicy }
self.columnTypeNames = columnTypeNames
}

func setPrimaryKeyColumns(_ primaryKeyColumns: [String]) {
self.primaryKeyColumns = primaryKeyColumns
}
Expand Down Expand Up @@ -979,35 +1003,6 @@ final class DataChangeManager: ObservableObject, ChangeManaging {
reloadVersion += 1
}

// MARK: - Per-Tab State Management

func saveState() -> TabChangeSnapshot {
pending.snapshot(primaryKeyColumns: primaryKeyColumns, columns: columns)
}

func restoreState(
from state: TabChangeSnapshot,
tableName: String,
schemaName: String? = nil,
databaseType: DatabaseType,
generatedColumns: Set<String>,
rowMatchPolicy: RowMatchPolicy = .none,
columnTypeNames: [String: String] = [:]
) {
self.tableName = tableName
self.schemaName = schemaName
self.columns = state.columns
self.primaryKeyColumns = state.primaryKeyColumns
self.databaseType = databaseType
self.generatedColumns = generatedColumns
self.rowMatchPolicy = rowMatchPolicy
self.columnTypeNames = columnTypeNames
discardUndoHistory()
objectWillChange.send()
pending.restore(from: state)
self.hasChanges = !pending.isEmpty
}

// MARK: - O(1) Lookups

func isRowDeleted(_ rowID: RowID) -> Bool {
Expand Down
32 changes: 0 additions & 32 deletions apple/TablePro/Core/ChangeTracking/PendingChanges.swift
Original file line number Diff line number Diff line change
Expand Up @@ -402,31 +402,6 @@ struct PendingChanges: Equatable {
supersededUpdates.removeAll()
}

mutating func restore(from snapshot: TabChangeSnapshot) {
changes = snapshot.changes
deletedRowIDs = snapshot.deletedRowIDs
insertedRowIDs = snapshot.insertedRowIDs
modifiedCells = snapshot.modifiedCells
insertedRowData = snapshot.insertedRowData
supersededUpdates = snapshot.supersededUpdates
let sequences = (changes + supersededUpdates.values).flatMap { [$0.sequence] + $0.runs.map(\.sequence) }
nextSequence = (sequences.max() ?? -1) + 1
rebuildChangeIndex()
}

func snapshot(primaryKeyColumns: [String], columns: [String]) -> TabChangeSnapshot {
var snap = TabChangeSnapshot()
snap.changes = changes
snap.deletedRowIDs = deletedRowIDs
snap.insertedRowIDs = insertedRowIDs
snap.modifiedCells = modifiedCells
snap.insertedRowData = insertedRowData
snap.supersededUpdates = supersededUpdates
snap.primaryKeyColumns = primaryKeyColumns
snap.columns = columns
return snap
}

// MARK: - Internals

private mutating func appendChange(_ change: RowChange) {
Expand Down Expand Up @@ -481,13 +456,6 @@ struct PendingChanges: Equatable {
changes.removeLast()
}

private mutating func rebuildChangeIndex() {
changeIndex.removeAll(keepingCapacity: true)
for (index, change) in changes.enumerated() {
changeIndex[RowChangeKey(rowID: change.rowID, type: change.type)] = index
}
}

private mutating func removeModifiedCell(rowID: RowID, columnIndex: Int) {
modifiedCells[rowID]?.remove(columnIndex)
if modifiedCells[rowID]?.isEmpty == true {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ extension QueryExecutionCoordinator {
var run = try await DatabaseManager.shared.withScopedDriver(
scope: scope,
route: DatabaseManager.shared.executionRoute(for: scope),
cancellation: .cancellableRead(lease)
cancellation: .cancellableRead(lease),
sessionWork: .statements
) { driver in
let startState = await driver.heldSessionTransactionState()
let manual = ManualCommit.decision(
Expand Down Expand Up @@ -538,7 +539,7 @@ extension QueryExecutionCoordinator {
}
}
parent.seedBufferFromActiveResult(tabId: tabId)
parent.dropParkedEdits(ofBackgroundTab: tabId)
parent.dropEdits(ofReplacedResultIn: tabId)
if parent.tabManager.selectedTabId == tabId {
parent.toolbarState.isResultsCollapsed = false
parent.toolbarState.recordQueryTiming(timing, for: tabId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,31 +369,24 @@ extension QueryExecutionCoordinator {
isEditable: isEditable
)

if parent.tabManager.selectedTabId == tabId {
parent.changeManager.configureForTable(
tableName: tableName ?? "",
schemaName: parent.tabManager.tabs[idx].tableContext.schemaName,
columns: columns,
primaryKeyColumns: resolvedPKs,
databaseType: conn.type,
generatedColumns: generatedColumns,
rowMatchPolicy: resolved.rowMatchPolicy,
columnTypeNames: newTableRows.columnTypeNames
)
parent.changeManagerMatchesSelectedResult()
}
parent.dropParkedEdits(ofBackgroundTab: tabId)
// The tab's own edits named rows of the result this replaces.
parent.changeManager(forTab: tabId).configureForTable(
tableName: tableName ?? "",
schemaName: parent.tabManager.tabs[idx].tableContext.schemaName,
columns: columns,
primaryKeyColumns: resolvedPKs,
databaseType: conn.type,
generatedColumns: generatedColumns,
rowMatchPolicy: resolved.rowMatchPolicy,
columnTypeNames: newTableRows.columnTypeNames
)

if trigger.recordsHistory {
recordSuccessfulRun(
query: historySQL ?? sql, tabId: tabId, connection: conn,
executionTime: executionTime, rowCount: rows.count, timing: timing
)
}

if parent.tabManager.selectedTabId == tabId, isEditable, !parent.changeManager.hasChanges {
parent.changeManager.clearChangesAndUndoHistory()
}
}

private func applyExplainResult(
Expand Down Expand Up @@ -451,7 +444,7 @@ extension QueryExecutionCoordinator {
}
}
parent.seedBufferFromActiveResult(tabId: tabId)
parent.dropParkedEdits(ofBackgroundTab: tabId)
parent.dropEdits(ofReplacedResultIn: tabId)
parent.toolbarState.isResultsCollapsed = false

recordHistory(
Expand Down Expand Up @@ -688,14 +681,12 @@ extension QueryExecutionCoordinator {
tab.metadataVersion += 1
}

if parent.tabManager.selectedTabId == tabId, !parsed.primaryKeyColumns.isEmpty {
parent.changeManager.setPrimaryKeyColumns(parsed.primaryKeyColumns)
}

if parent.tabManager.selectedTabId == tabId {
parent.changeManager.setGeneratedColumns(parsed.generatedColumns)
parent.changeManager.setRowMatchPolicy(parsed.rowMatchPolicy)
let changeManager = parent.changeManager(forTab: tabId)
if !parsed.primaryKeyColumns.isEmpty {
changeManager.setPrimaryKeyColumns(parsed.primaryKeyColumns)
}
changeManager.setGeneratedColumns(parsed.generatedColumns)
changeManager.setRowMatchPolicy(parsed.rowMatchPolicy)

// The metadata delta rebuilt the model's columns; the foreign key arrows need the rows redrawn.
let refreshed = isActiveTab(tabId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,11 +361,6 @@ extension QueryExecutionCoordinator {
}
parent.toolbarState.isResultsCollapsed = false

if parent.tabManager.selectedTabId == tabId {
parent.changeManager.clearChangesAndUndoHistory()
parent.changeManagerMatchesSelectedResult()
} else {
parent.dropParkedEdits(ofBackgroundTab: tabId)
}
parent.dropEdits(ofReplacedResultIn: tabId)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ extension QueryExecutionCoordinator {
let (fetchResult, tableEdits) = try await DatabaseManager.shared.withScopedDriver(
scope: scope,
route: DatabaseManager.shared.executionRoute(for: scope),
cancellation: .cancellableRead(lease)
cancellation: .cancellableRead(lease),
sessionWork: .statements
) { [queryExecutor = parent.queryExecutor, boundValues] driver in
let fetched = try await held.running([statement.sql], on: driver) {
// Before it runs, so a statement that fails or a connection lost under it is still noted.
Expand Down Expand Up @@ -593,7 +594,8 @@ extension QueryExecutionCoordinator {
var run = try await DatabaseManager.shared.withScopedDriver(
scope: scope,
route: DatabaseManager.shared.executionRoute(for: scope),
cancellation: .cancellableRead(lease)
cancellation: .cancellableRead(lease),
sessionWork: .statements
) { driver in
let context = driver.readOnlyRunContext(safeModeIsReadOnly: safeModeIsReadOnly)
let startState = await driver.heldSessionTransactionState()
Expand Down Expand Up @@ -975,7 +977,7 @@ extension QueryExecutionCoordinator {
}
}
parent.seedBufferFromActiveResult(tabId: tabId)
parent.dropParkedEdits(ofBackgroundTab: tabId)
parent.dropEdits(ofReplacedResultIn: tabId)
if parent.tabManager.selectedTabId == tabId {
parent.toolbarState.isResultsCollapsed = false
parent.toolbarState.recordQueryTiming(timing, for: tabId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,6 @@ extension RowEditingCoordinator {
pendingTruncates.removeAll()
pendingDeletes.removeAll()
parent.changeManager.clearChangesAndUndoHistory()

if let (_, index) = parent.tabManager.selectedTabAndIndex {
parent.tabManager.mutate(at: index) { $0.pendingChanges = TabChangeSnapshot() }
}
parent.resumeDeferredTableRefresh()
}

Expand Down
Loading
Loading