Repository Public
1// SP Notes Core2// File: Sources/SPNotesStore/StoreOpen.swift3// Description: Safe opening of the database file (2.0): the copy made before a migration, its removal at the next4// healthy launch, and a typed open result so that an app shows a blocking error instead of silently5// falling back to an empty in-memory store.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SQLite31112/// What opening a database file did.13public struct StoreOpenReport: Sendable, Equatable {14 /// The schema version of this build (and of the file once opened).15 public var schemaVersion: Int16 /// `PRAGMA user_version` of the file before it was opened (0 = new or never migrated file).17 public var foundVersion: Int18 /// The version the file was migrated from during this open, nil when no migration ran.19 public var migratedFrom: Int?20 /// The pre-migration copy that exists right now (made during this open, or kept from a recent one).21 public var backupURL: URL?22 /// Pre-migration copies removed during this open (the file was already up to date and passed `quick_check`).23 public var removedBackups: [URL] = []2425 public var didMigrate: Bool { migratedFrom != nil }2627 public init(schemaVersion: Int, foundVersion: Int = 0, migratedFrom: Int? = nil, backupURL: URL? = nil, removedBackups: [URL] = []) {28 self.schemaVersion = schemaVersion29 self.foundVersion = foundVersion30 self.migratedFrom = migratedFrom31 self.backupURL = backupURL32 self.removedBackups = removedBackups33 }34}3536/// Why a database file could not be opened. Every case means the same thing for an app: **do not continue with an37/// empty store** — show `userMessage` in a blocking screen; the user's data is still in the file (and in `backupURL`).38public enum StoreOpenError: Error, Sendable, Equatable, CustomStringConvertible, LocalizedError {39 /// The file was written by a newer version of the app.40 case newerSchema(found: Int, supported: Int)41 /// A read-only connection met a file that still needs a migration.42 case outdatedReadOnly(found: Int, required: Int)43 /// SQLite reports the file as damaged or not a database.44 case corrupt(String)45 /// Another process holds the file and did not release it in time.46 case locked(String)47 /// The file cannot be read or written (permissions, disk full, I/O error, missing directory).48 case storage(String)49 /// The pre-migration copy could not be written; the migration was not attempted and the file is unchanged.50 case backupFailed(String)51 /// A migration step failed and was rolled back: the file is still at version `from`.52 case migrationFailed(from: Int, to: Int, reason: String, backupURL: URL?)53 case other(String)5455 /// The pre-migration copy to mention to the user, when one exists.56 public var backupURL: URL? {57 if case .migrationFailed(_, _, _, let url) = self { return url }58 return nil59 }6061 /// True when retrying later (or after freeing space / closing another app) may work without any repair.62 public var isTransient: Bool {63 switch self {64 case .locked, .storage, .backupFailed: return true65 default: return false66 }67 }6869 /// French, user-facing, without technical detail.70 public var userMessage: String {71 switch self {72 case .newerSchema:73 return "Vos notes ont été enregistrées par une version plus récente de SP Notes. Mettez l’application à jour pour les ouvrir. Rien n’a été modifié."74 case .outdatedReadOnly:75 return "La base locale doit d’abord être mise à jour par l’application principale. Ouvrez SP Notes une fois, puis réessayez."76 case .corrupt:77 return "La base locale de notes est endommagée et n’a pas pu être ouverte. Vos notes n’ont pas été effacées : le fichier est conservé tel quel. Contactez le support avant toute autre action."78 case .locked:79 return "La base locale est utilisée par un autre processus. Fermez les autres fenêtres de SP Notes, puis réessayez."80 case .storage:81 return "La base locale n’a pas pu être lue ou écrite (espace disque, autorisations). Libérez de l’espace, puis réessayez. Vos notes n’ont pas été modifiées."82 case .backupFailed:83 return "La copie de sécurité préalable à la mise à jour de la base n’a pas pu être écrite ; la mise à jour n’a donc pas été tentée. Libérez de l’espace disque, puis réessayez. Vos notes n’ont pas été modifiées."84 case .migrationFailed:85 return "La mise à jour de la base locale a échoué et a été annulée. Vos notes sont intactes dans leur version précédente, et une copie de sécurité a été conservée. Réessayez ; si le problème persiste, contactez le support."86 case .other:87 return "La base locale de notes n’a pas pu être ouverte. Vos notes n’ont pas été modifiées."88 }89 }9091 public var description: String {92 switch self {93 case .newerSchema(let found, let supported): return "database version \(found) is newer than this build supports (\(supported))"94 case .outdatedReadOnly(let found, let required): return "database version \(found) is older than \(required) and the connection is read-only"95 case .corrupt(let detail): return "database is corrupt: \(detail)"96 case .locked(let detail): return "database is locked: \(detail)"97 case .storage(let detail): return "database storage error: \(detail)"98 case .backupFailed(let detail): return "pre-migration backup failed: \(detail)"99 case .migrationFailed(let from, let to, let reason, let url):100 return "migration \(from) → \(to) failed and was rolled back: \(reason)" + (url.map { " (backup: \($0.lastPathComponent))" } ?? "")101 case .other(let detail): return detail102 }103 }104105 public var errorDescription: String? { userMessage }106}107108/// The outcome of `NotesStore.open`: a store, or a typed error to show — never a silent substitute.109public enum StoreOpenResult: Sendable {110 case opened(NotesStore, StoreOpenReport)111 case failed(StoreOpenError)112113 public var store: NotesStore? {114 if case .opened(let store, _) = self { return store }115 return nil116 }117118 public var error: StoreOpenError? {119 if case .failed(let error) = self { return error }120 return nil121 }122123 /// The store, or throws the typed error.124 public func get() throws -> NotesStore {125 switch self {126 case .opened(let store, _): return store127 case .failed(let error): throw error128 }129 }130}131132extension NotesStore {133 /// Opens (creating and migrating when writable) the database file at `url` and reports the outcome as a value.134 /// Before a migration of existing data the file is copied to `<file>.backup-v<old version>`; the copy is removed135 /// by a later open that finds the file up to date, healthy, and the copy older than `backupRetention` seconds.136 /// On failure the file is left as it was: show `StoreOpenError.userMessage` and stop — do not use `inMemory()`.137 public static func open(url: URL, readOnly: Bool = false, backupRetention: TimeInterval = StoreBackup.defaultRetention) -> StoreOpenResult {138 let before = StoreBackup.peekVersion(path: url.path)139 do {140 let store = try NotesStore(path: url.path, readOnly: readOnly, backupRetention: backupRetention)141 return .opened(store, store.openReport)142 } catch {143 return .failed(openError(for: error, url: url, versionBefore: before))144 }145 }146147 /// Maps what `init(url:)` throws to the typed open error (for apps that keep calling the initializer).148 public static func openError(for error: Error, url: URL) -> StoreOpenError {149 openError(for: error, url: url, versionBefore: StoreBackup.peekVersion(path: url.path))150 }151152 static func openError(for error: Error, url: URL, versionBefore: Int?) -> StoreOpenError {153 if let already = error as? StoreOpenError { return already }154 let current = Schema.currentVersion155 let found = versionBefore ?? StoreBackup.peekVersion(path: url.path)156 let backup = found.flatMap { version -> URL? in157 let candidate = StoreBackup.backupURL(path: url.path, version: version)158 return FileManager.default.fileExists(atPath: candidate.path) ? candidate : nil159 }160 guard let store = error as? StoreError else { return .other(String(describing: error)) }161 switch store {162 case .backup(let why): return .backupFailed(why)163 case .schema(let why):164 if let found, found > current { return .newerSchema(found: found, supported: current) }165 if let found, found < current { return .outdatedReadOnly(found: found, required: current) }166 return .other(why)167 case .sqlite(let code, let message, _):168 switch code & 0xFF {169 case SQLITE_CORRUPT, SQLITE_NOTADB: return .corrupt(message)170 case SQLITE_BUSY, SQLITE_LOCKED: return .locked(message)171 case SQLITE_IOERR, SQLITE_FULL, SQLITE_CANTOPEN, SQLITE_PERM, SQLITE_READONLY, SQLITE_AUTH, SQLITE_NOMEM:172 if let found, found > 0, found < current { return .migrationFailed(from: found, to: current, reason: message, backupURL: backup) }173 return .storage(message)174 default:175 if let found, found > 0, found < current { return .migrationFailed(from: found, to: current, reason: message, backupURL: backup) }176 return .other(store.description)177 }178 default:179 if let found, found > 0, found < current { return .migrationFailed(from: found, to: current, reason: store.description, backupURL: backup) }180 return .other(store.description)181 }182 }183}184185/// The copy of the database made before a migration.186public enum StoreBackup {187 /// A backup younger than this is kept even when the file is healthy (another process — widget, share188 /// extension — may open the file seconds after the migration; that is not "the next launch").189 public static let defaultRetention: TimeInterval = 600190191 /// `<file>.backup-v<version>` next to the database.192 public static func backupURL(path: String, version: Int) -> URL { URL(fileURLWithPath: path + ".backup-v\(version)") }193194 /// The pre-migration copies that exist next to the database at `url`, oldest version first.195 public static func existingBackups(of url: URL) -> [URL] {196 let directory = url.deletingLastPathComponent()197 let prefix = url.lastPathComponent + ".backup-v"198 let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []199 return names.filter { $0.hasPrefix(prefix) && Int($0.dropFirst(prefix.count)) != nil }200 .sorted { (Int($0.dropFirst(prefix.count)) ?? 0) < (Int($1.dropFirst(prefix.count)) ?? 0) }201 .map { directory.appendingPathComponent($0) }202 }203204 /// `PRAGMA user_version` of a file read through a separate read-only connection; nil when it cannot be read.205 public static func peekVersion(path: String) -> Int? {206 guard path != ":memory:", FileManager.default.fileExists(atPath: path) else { return nil }207 return queryVersion(path: path) ?? headerVersion(path: path)208 }209210 private static func queryVersion(path: String) -> Int? {211 var handle: OpaquePointer?212 guard sqlite3_open_v2(path, &handle, SQLITE_OPEN_READONLY, nil) == SQLITE_OK, let handle else {213 if let handle { sqlite3_close_v2(handle) }214 return nil215 }216 defer { sqlite3_close_v2(handle) }217 sqlite3_busy_timeout(handle, 2000)218 var stmt: OpaquePointer?219 guard sqlite3_prepare_v2(handle, "PRAGMA user_version", -1, &stmt, nil) == SQLITE_OK, let stmt else { return nil }220 defer { sqlite3_finalize(stmt) }221 guard sqlite3_step(stmt) == SQLITE_ROW else { return nil }222 return Int(sqlite3_column_int64(stmt, 0))223 }224225 /// The user version stored in the 100-byte file header (big-endian at offset 60). Used when a read-only226 /// connection cannot be opened — a WAL database closed cleanly has no `-shm` file, which such a connection227 /// cannot create. nil when the file is not an SQLite database.228 private static func headerVersion(path: String) -> Int? {229 guard let handle = FileHandle(forReadingAtPath: path) else { return nil }230 defer { try? handle.close() }231 guard let header = try? handle.read(upToCount: 100), header.count == 100, header.starts(with: Array("SQLite format 3\u{0}".utf8)) else { return nil }232 return Int(header[60..<64].reduce(UInt32(0)) { $0 << 8 | UInt32($1) })233 }234235 /// Before `Schema.migrate`: copies a file holding data of an older version; on an up-to-date file removes the236 /// copies that are old enough once `quick_check` passes.237 static func prepare(_ db: Database, path: String, retention: TimeInterval, report: inout StoreOpenReport,238 targetVersion: Int = Schema.currentVersion) throws {239 let version = Int(try db.scalar("PRAGMA user_version"))240 report.foundVersion = version241 let url = URL(fileURLWithPath: path)242 if version < targetVersion { report.migratedFrom = version }243 if version > 0, version < targetVersion {244 let backup = backupURL(path: path, version: version)245 // A copy left by an earlier failed attempt is the pristine one: never overwrite it.246 if !FileManager.default.fileExists(atPath: backup.path) { try write(db, to: backup) }247 report.backupURL = backup248 } else if version == targetVersion {249 let backups = existingBackups(of: url)250 guard !backups.isEmpty else { return }251 let healthy = ((try? db.query("PRAGMA quick_check") { $0.string(0) }) ?? []) == ["ok"]252 for backup in backups {253 let modified = (try? FileManager.default.attributesOfItem(atPath: backup.path)[.modificationDate]) as? Date254 let age = modified.map { Date().timeIntervalSince($0) } ?? .infinity255 if healthy, age >= retention, (try? FileManager.default.removeItem(at: backup)) != nil {256 report.removedBackups.append(backup)257 } else {258 report.backupURL = backup259 }260 }261 }262 }263264 /// A consistent snapshot of the open database (WAL included) written with `VACUUM INTO`, then moved into place.265 static func write(_ db: Database, to backup: URL) throws {266 let temporary = URL(fileURLWithPath: backup.path + ".partial")267 try? FileManager.default.removeItem(at: temporary)268 do {269 try db.exec("VACUUM INTO '\(temporary.path.replacingOccurrences(of: "'", with: "''"))'")270 try FileManager.default.moveItem(at: temporary, to: backup)271 } catch {272 try? FileManager.default.removeItem(at: temporary)273 throw StoreError.backup(String(describing: error))274 }275 }276}277