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
10 changes: 8 additions & 2 deletions .claude/rules/data-sync-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,20 @@ This path holds user data. A silent wrong answer here looks exactly like an empt
| Appearance mode (Auto, Light, Dark) | UserDefaults, device-local, never synced | `AppSettingsStorage` through `AppSettingsManager.appearanceMode` |
| Light and dark theme ids (iCloud-synced, category `appearance`) | UserDefaults | `AppearanceSettings` through `AppSettingsManager` |
| User themes (iCloud-synced, one `AppSettings` record `theme.<id>` each) | JSON, one file per theme | `ThemeCatalog` (sync rules: `.claude/rules/theme.md`, Sync) |
| Query history | SQLite FTS5 | `QueryHistoryStorage` |
| Query history | SQLite FTS5 `query_history.db`, which the History pane, Insights and the plan and Rewind snapshots read; each run, deletion, clear and retention pass also reaches the core's history under the run's id, and a deletion or clear reports a failure while the core still holds what went | `QueryHistoryStorage`, copied by `QueryHistoryCoreMirror` |
| Saved queries and their folders (iCloud-synced) | SQLite `sql_favorites.db`, which this build and the previous stable read; each write also reaches the core's copy | `SQLFavoriteStorage` through `SQLFavoriteManager`, copied by `CoreMirror` |
| The core's copy of the saved queries and folders, the favourite tables and databases, the table folders and the history (core ADR 0010, slices 3 and 9), each under the Mac's id. A launch takes in what changed in the Swift stores, the previous stable's edits included, and a write that reached only the core goes back to them. A collision the core settles (ADR 0052) is written back and marked dirty | SQLite `Core/state/history.db` in the support directory | the core's `tablepro-storage` through `CoreHistoryDatabase` |
| What a Swift store and the core's copy held when they last agreed, a digest per record, so a push tells which side changed each one. A record either side changed goes to the other, the Swift store's version when both did; one the core refused keeps its last agreement and goes again | UserDefaults `com.TablePro.coreMirror.savedQueries`, `.favoriteTables`, `.favoriteDatabases`, `.tableFolders`, device-local, never synced | `CoreMirror` |
| The runs `query_history.db` and the core's history both held when they last agreed, so a run leaves the core only when it left the Mac's store after that. In the same file, so a damaged one set aside takes it along and the core keeps its runs; the previous stable never touches it | Table `core_mirror` in `query_history.db` | `QueryHistoryCoreMirror` |
| Query tab edit history: up to 50 versions per tab, kept 30 days or the shorter Query History window, after the tab closes too; purged with the connection and by Clear History | SQLite `query_tab_versions.db`, device-local, never synced | `QueryTabVersionStorage` |
| Tab state | JSON | `TabPersistenceCoordinator`, `TabDiskActor` |
| Filter defaults and presets | UserDefaults | `FilterSettingsStorage`, `FilterPresetStorage` |
| Per-table filters | JSON, one file per table | `FilterSettingsStorage` |
| Generate Rows settings per table | UserDefaults, device-local | `RowGenerationSettingsStore` |
| Row inspector field heights, per column name | UserDefaults, device-local | `InspectorFieldHeightStore` |
| Favorite tables (iCloud-synced) | UserDefaults | `FavoriteTablesStorage` |
| Favorite tables (iCloud-synced) | UserDefaults; each change also reaches the core's copy | `FavoriteTablesStorage` |
| Favorite databases and their environment (iCloud-synced) | UserDefaults `com.TablePro.favoriteDatabases`; each change also reaches the core's copy | `FavoriteDatabasesStorage` |
| Table folders and what they hold (iCloud-synced) | UserDefaults, one document per connection under `com.TablePro.tableFolders.`; each change also reaches the core's copy | `TableFolderStorage` |
| Team library read cache, per server and account: each team's pull cursor and items (synced with tablepro-cloud's `/v2`, never iCloud). Unsent edits stay in memory only; the library 0.88 and earlier kept, with its unsent edits, is read once for the tablepro.app sign-in the core restores, behind the UserDefaults flag `com.TablePro.teamLibrary.earlierLibraryConsidered`, then deleted; its edits are uploaded once (`TeamLibrarySync` has the rules) | JSON, one file per team in `TeamLibraryCache/<digest of server and account>/`; 0.88 and earlier: `TeamLibrary/` and `team_library.json` | `TeamLibraryStorage` through `TeamLibrarySync` |
| TablePro account: the device, the entitlement, the chosen server, a company server's license and entitlement keys | `Account/account.json` in Application Support, device-local, never synced | the core's `tablepro-account` through `AccountServices` |
| The account's refresh token: tablepro.app's in the item earlier builds read, each company server's in its own | Keychain `com.TablePro.account.refreshToken`, and one item per company server, device-only | the core through `KeychainHostSecrets` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ internal enum PostLaunchWork {

Task { await PluginManager.shared.sweepPluginSignatures() }
Task { await QueryHistoryManager.shared.performStartupCleanup() }
// The core's history.db takes in what the stores the previous stable reads hold (core ADR 0010, slices 3 and 9).
Task {
await SQLFavoriteManager.shared.pushToCore()
await FavoriteTablesStorage.shared.coreMirror?.push()
await FavoriteDatabasesStorage.shared.coreMirror?.push()
await TableFolderStorage.shared.coreMirror?.push()
}
let supportDirectory = AppStorageEnvironment.shared.supportDirectory
Task.detached(priority: .utility) { RetiredTableLoadHistory.remove(in: supportDirectory) }
SignInPrompt.live.presentIfNeeded()
Expand Down
98 changes: 98 additions & 0 deletions apple/TablePro/Core/Storage/CoreMirror/CoreHistoryDatabase.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//
// CoreHistoryDatabase.swift
// TablePro
//

import Foundation
import os
import TableProFFI
import TableProLogRedaction

// The core's history.db (core ADR 0060): the saved queries and their folders, the favourite tables and databases,
// the table folders and the history, in one file under `TablePro/Core/`. Opened on first use; a failed open is
// tried again on the next call.
internal actor CoreHistoryDatabase {
internal static let shared = CoreHistoryDatabase(
folder: AppStorageEnvironment.shared.supportDirectory.appendingPathComponent("Core", isDirectory: true)
)

private static let logger = Logger(subsystem: "com.TablePro", category: "CoreHistoryDatabase")

nonisolated internal let folder: URL
private let clientVersion: String
private var core: Core?
private var store: QueryHistoryStore?

internal init(folder: URL, clientVersion: String = CoreHistoryDatabase.appVersion) {
self.folder = folder
self.clientVersion = clientVersion
}

nonisolated internal static var appVersion: String {
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"
}

internal func history() async throws -> QueryHistoryStore {
if let store { return store }
do {
// Private as the core keeps its own folders, since history.db holds the SQL a person ran.
try FileManager.default.createDirectory(
at: folder,
withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700]
)
let core = try self.core ?? Core(
config: HostConfig(clientVersion: clientVersion, storageDir: folder.path),
secrets: NoHistorySecrets()
)
self.core = core
let opened = try await core.history()
store = opened
return opened
} catch {
Self.logger.error("The core's history store did not open: \(LogRedaction.publicDescription(of: error), privacy: .public)")
throw error
}
}

internal func savedQueries() async throws -> SavedQueryStore {
try await history().savedQueries()
}

internal func favourites() async throws -> FavouriteStore {
try await history().favourites()
}

internal func tableFolders() async throws -> TableFolderStore {
try await history().tableFolders()
}
}

// A whole-store write the core refused because the store moved since it was read (storage.import_outdated).
internal func refusingOutdated(_ work: () async throws -> Void) async throws {
do {
try await work()
} catch CoreError.Failed(let info) where info.code == "storage.import_outdated" {
throw CoreMirrorError.outdated
}
}

// Nothing in history.db is a secret, and this core is opened for that file alone.
private final class NoHistorySecrets: HostSecrets, Sendable {
func load(connectionId: String, kind: SecretKindTag) throws -> String? { nil }

func store(connectionId: String, kind: SecretKindTag, secret: String, label: String) throws {
throw HostSecretError.Unavailable(detail: "the history store keeps no secrets")
}

func relabel(connectionId: String, kind: SecretKindTag, label: String) throws {}
func delete(connectionId: String, kind: SecretKindTag) throws {}
func deleteConnection(connectionId: String) throws {}
func loadItem(item: SecretItemTag) throws -> String? { nil }

func storeItem(item: SecretItemTag, secret: String) throws {
throw HostSecretError.Unavailable(detail: "the history store keeps no secrets")
}

func deleteItem(item: SecretItemTag) throws {}
}
Loading
Loading