SPB Git

Repository Public License

MigrationAndRecoveryTests.swift 15.2 KB 278 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct MigrationTests {7    @Test func freshDatabaseIsAtLatestVersion() async throws {8        let database = try await NavigatorDatabase.inMemory()9        #expect(database.openInfo.previousSchemaVersion == 0)10        #expect(database.openInfo.schemaVersion == Schema.latestVersion)11        #expect(try await database.schemaVersion() == Schema.latestVersion)12        let recorded = try await database.sqlite.read { connection in13            try connection.query("SELECT version FROM schema_migrations ORDER BY version").map { try $0.get("version", as: Int.self) }14        }15        #expect(recorded == Array(1...Schema.latestVersion))16        #expect(try await database.checkIntegrity(full: true).isEmpty)17    }1819    /// Writes a real version-1 database (schema v1 only, rows inserted with v1 SQL), then opens it with the20    /// current code and checks the data survived and the v2 columns were backfilled.21    @Test func migratesVersion1FixtureToLatest() async throws {22        let scratch = try ScratchDirectory()23        let profileID = ProfileID()24        let recent = Date.now.addingTimeInterval(-3_600)25        let old = Date.now.addingTimeInterval(-200 * 86_400)2627        let legacy = try await SQLiteDatabase(location: .file(scratch.databaseURL), configuration: .init(readerCount: 0))28        try await legacy.write { connection in29            let outcome = try Migrator.migrate(connection, upTo: 1)30            #expect(outcome.toVersion == 1)31            #expect(try Migrator.currentVersion(connection) == 1)32            // v1 has no frecency / host_key columns.33            let columns = try connection.query("PRAGMA table_info(history_urls)").map { try $0.get("name", as: String.self) }34            #expect(!columns.contains("frecency"))35            #expect(!columns.contains("host_key"))36            try connection.transaction {37                try connection.execute("""38                INSERT INTO profiles (id, name, kind, data_store_identifier, tint, created_at)39                VALUES (?, 'Legacy', 'standard', ?, 'lunarBlue', ?)40                """, [profileID, UUID(), old])41                try connection.execute("""42                INSERT INTO history_urls (id, profile_id, url, host, title, visit_count, typed_count, last_visited_at)43                VALUES (1, ?, 'https://www.swift.org/documentation/', 'www.swift.org', 'Swift Documentation', 3, 1, ?),44                       (2, ?, 'https://old.example.com/', 'old.example.com', 'Old page', 1, 0, ?),45                       (3, ?, 'https://reload.example.com/', 'reload.example.com', 'Only reloaded', 1, 0, ?)46                """, [profileID, recent, profileID, old, profileID, recent])47                for (index, visit) in [(1, recent, "typed"), (1, recent, "link"), (1, old, "link"), (2, old, "link"),48                                       (3, recent, "reload")].enumerated() {49                    try connection.execute("""50                    INSERT INTO history_visits (id, url_id, profile_id, title, visited_at, transition)51                    VALUES (?, ?, ?, '', ?, ?)52                    """, [HistoryID(), visit.0, profileID, visit.1.addingTimeInterval(Double(index)), visit.2])53                }54                try connection.execute("""55                INSERT INTO bookmarks (id, profile_id, kind, title, url, sort_order, is_favorite, created_at, updated_at)56                VALUES (?, ?, 'link', 'Swift', 'https://www.swift.org/', 0, 1, ?, ?)57                """, [BookmarkID(), profileID, old, old])58            }59        }60        await legacy.close()6162        let database = try await NavigatorDatabase(url: scratch.databaseURL)63        #expect(database.openInfo.previousSchemaVersion == 1)64        #expect(database.openInfo.schemaVersion == Schema.latestVersion)6566        // Existing data is intact.67        #expect(try await database.profiles.all().map(\.name) == ["Legacy"])68        #expect(try await database.bookmarks.favorites(profile: profileID).map(\.title) == ["Swift"])69        #expect(try await database.history.visitCount(profile: profileID) == 5)7071        // New columns are backfilled from the visits.72        let swift = try #require(try await database.history.page(for: url("https://www.swift.org/documentation/"), profile: profileID))73        let oldPage = try #require(try await database.history.page(for: url("https://old.example.com/"), profile: profileID))74        let reloaded = try #require(try await database.history.page(for: url("https://reload.example.com/"), profile: profileID))75        #expect(swift.frecency > oldPage.frecency)76        #expect(oldPage.frecency > Frecency.none)77        #expect(reloaded.frecency == Frecency.none)78        let hostKeys = try await database.sqlite.read { connection in79            try connection.query("SELECT host_key FROM history_urls ORDER BY id").map { try $0.get("host_key", as: String.self) }80        }81        #expect(hostKeys == ["swift.org", "old.example.com", "reload.example.com"])8283        // The migrated database behaves like a new one: suggestions rank by the backfilled score, the v1 FTS84        // index still answers, and new visits can be recorded.85        let suggestions = try await database.history.suggestions(for: "sw", profile: profileID)86        #expect(suggestions.first?.page.url == url("https://www.swift.org/documentation/"))87        #expect(suggestions.first?.matchesHostPrefix == true)88        try await database.history.recordVisit(NavigationEntry(profileID: profileID, url: url("https://new.example.com/"), title: "New"))89        #expect(try await database.history.search("new", profile: profileID).count == 1)90        #expect(try await database.checkIntegrity(full: true).isEmpty)91        await database.close()9293        // Opening again applies nothing.94        let reopened = try await NavigatorDatabase(url: scratch.databaseURL)95        #expect(reopened.openInfo.previousSchemaVersion == Schema.latestVersion)96        await reopened.close()97    }9899    @Test func failingMigrationRollsBackCompletely() async throws {100        struct Boom: Error {}101        let database = try await SQLiteDatabase(location: .memory, configuration: .init())102        let migrations = [103            Migration(version: 1, name: "one", sql: "CREATE TABLE a (id INTEGER PRIMARY KEY)"),104            Migration(version: 2, name: "two") { connection in105                try connection.executeScript("CREATE TABLE b (id INTEGER PRIMARY KEY); INSERT INTO a (id) VALUES (1);")106                throw Boom()107            },108            Migration(version: 3, name: "three", sql: "CREATE TABLE c (id INTEGER PRIMARY KEY)"),109        ]110        await #expect(throws: Boom.self) {111            try await database.write { _ = try Migrator.migrate($0, migrations: migrations) }112        }113        let state = try await database.read { connection in114            (try Migrator.currentVersion(connection),115             try connection.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('a', 'b', 'c') ORDER BY name")116                .map { try $0.get("name", as: String.self) },117             try connection.scalar("SELECT count(*) FROM a", as: Int.self))118        }119        // Version 1 is committed; version 2 left no trace; version 3 never ran.120        #expect(state.0 == 1)121        #expect(state.1 == ["a"])122        #expect(state.2 == 0)123    }124125    /// The design goal "adding v2 later is a one-liner": appending one `Migration` to a list upgrades a126    /// database created with the shorter list.127    @Test func appendingAMigrationUpgradesAnExistingDatabase() async throws {128        let database = try await SQLiteDatabase(location: .memory, configuration: .init())129        var migrations = [Migration(version: 1, name: "one", sql: "CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT)")]130        try await database.write { [migrations] in _ = try Migrator.migrate($0, migrations: migrations) }131        try await database.write { try $0.execute("INSERT INTO a (name) VALUES ('kept')") }132        migrations.append(Migration(version: 2, name: "two", sql: "ALTER TABLE a ADD COLUMN extra TEXT NOT NULL DEFAULT 'x'"))133        let outcome = try await database.write { [migrations] in try Migrator.migrate($0, migrations: migrations) }134        #expect(outcome == Migrator.Outcome(fromVersion: 1, toVersion: 2))135        #expect(outcome.applied == [2])136        let row = try #require(try await database.read { try $0.queryOne("SELECT name, extra FROM a") })137        #expect(try row.get("name", as: String.self) == "kept")138        #expect(try row.get("extra", as: String.self) == "x")139    }140141    @Test func refusesDatabaseNewerThanTheCode() async throws {142        let scratch = try ScratchDirectory()143        let first = try await NavigatorDatabase(url: scratch.databaseURL)144        let fixture = try await Fixture.make(in: first)145        let future = Schema.latestVersion + 5146        try await first.sqlite.write { try $0.executeScript("PRAGMA user_version = \(future)") }147        await first.close()148149        do {150            _ = try await NavigatorDatabase(url: scratch.databaseURL)151            Issue.record("a newer database must not open")152        } catch let error as PersistenceError {153            #expect(error == .databaseTooNew(found: future, supported: Schema.latestVersion))154            #expect(error.description.contains("newer"))155        }156        // Recovery must not treat "too new" as corruption and move the user's data away.157        await #expect(throws: PersistenceError.databaseTooNew(found: future, supported: Schema.latestVersion)) {158            _ = try await NavigatorDatabase.openRecovering(url: scratch.databaseURL)159        }160        #expect(FileManager.default.fileExists(atPath: scratch.databaseURL.path))161        // The file is untouched: same version, same data.162        let raw = try await SQLiteDatabase(location: .file(scratch.databaseURL), configuration: .init(readerCount: 0))163        let state = try await raw.read { connection in164            (try Migrator.currentVersion(connection), try connection.scalar("SELECT name FROM profiles", as: String.self))165        }166        #expect(state.0 == future)167        #expect(state.1 == fixture.profile.name)168        await raw.close()169    }170}171172@Suite struct RecoveryTests {173    @Test func garbageFileIsReportedCorruptAndLeftUntouched() async throws {174        let scratch = try ScratchDirectory()175        let garbage = Data("this is definitely not an SQLite database, it is somebody's precious bytes".utf8)176            + Data(repeating: 0xAB, count: 8_192)177        try garbage.write(to: scratch.databaseURL)178179        do {180            _ = try await NavigatorDatabase(url: scratch.databaseURL)181            Issue.record("garbage must not open")182        } catch let error as PersistenceError {183            guard case .corrupt(let path, _) = error else { Issue.record("unexpected \(error)"); return }184            #expect(path == scratch.databaseURL.path)185        }186        #expect(try Data(contentsOf: scratch.databaseURL) == garbage)187    }188189    @Test func recoveryMovesTheCorruptFileAsideAndStartsFresh() async throws {190        let scratch = try ScratchDirectory()191        let garbage = Data(repeating: 0x5A, count: 20_000)192        try garbage.write(to: scratch.databaseURL)193194        let (database, recovery) = try await NavigatorDatabase.openRecovering(url: scratch.databaseURL)195        let report = try #require(recovery)196        #expect(!report.reason.isEmpty)197        #expect(report.quarantineDirectory.lastPathComponent.hasPrefix("Navigator.sqlite.corrupt-"))198        #expect(report.movedFiles.map(\.lastPathComponent) == ["Navigator.sqlite"])199        // Nothing was deleted: the original bytes are in the quarantine directory.200        #expect(try Data(contentsOf: report.movedFiles[0]) == garbage)201202        // The replacement is a working, empty database.203        let fixture = try await Fixture.make(in: database)204        #expect(try await database.profiles.all() == [fixture.profile])205        #expect(try await database.checkIntegrity().isEmpty)206        await database.close()207208        // A healthy database reports no recovery.209        let (again, second) = try await NavigatorDatabase.openRecovering(url: scratch.databaseURL)210        #expect(second == nil)211        #expect(try await again.profiles.all() == [fixture.profile])212        await again.close()213    }214215    /// Damage in the middle of a real database: the header is valid, the content is not.216    @Test func damagedPagesAreDetectedByTheIntegrityCheck() async throws {217        let scratch = try ScratchDirectory()218        let database = try await NavigatorDatabase(url: scratch.databaseURL)219        let fixture = try await Fixture.make(in: database)220        try await database.history.recordVisits((0..<400).map {221            fixture.visit("https://site\($0).example.com/page/\($0)", title: "Page number \($0)")222        })223        // Leave the session "not clean", as a crash would.224        _ = try await database.session.beginSession()225        try await database.sqlite.write { _ = try $0.query("PRAGMA wal_checkpoint(TRUNCATE)") }226        await database.close()227228        var bytes = try Data(contentsOf: scratch.databaseURL)229        let pageSize = 4_096230        #expect(bytes.count > pageSize * 12)231        // Overwrite several pages after the first (header and schema stay readable).232        for page in 3..<(bytes.count / pageSize) where page % 2 == 1 {233            let range = (page * pageSize)..<((page + 1) * pageSize)234            bytes.replaceSubrange(range, with: Data(repeating: 0xEE, count: pageSize))235        }236        try bytes.write(to: scratch.databaseURL)237        for extra in NavigatorDatabase.fileURLs(for: scratch.databaseURL).dropFirst() {238            try? FileManager.default.removeItem(at: extra)239        }240241        // Default policy: the previous run was not clean, so the quick check runs and rejects the file.242        do {243            _ = try await NavigatorDatabase(url: scratch.databaseURL)244            Issue.record("a damaged database must not open")245        } catch let error as PersistenceError {246            guard case .corrupt = error else { Issue.record("unexpected \(error)"); return }247        }248        #expect(try Data(contentsOf: scratch.databaseURL) == bytes)249250        let (fresh, recovery) = try await NavigatorDatabase.openRecovering(url: scratch.databaseURL)251        let report = try #require(recovery)252        #expect(try Data(contentsOf: report.movedFiles[0]) == bytes)253        #expect(try await fresh.profiles.all().isEmpty)254        await fresh.close()255    }256257    @Test func cleanShutdownSkipsTheIntegrityCheckAndUncleanRunsIt() async throws {258        let scratch = try ScratchDirectory()259        let first = try await NavigatorDatabase(url: scratch.databaseURL)260        #expect(first.openInfo.ranIntegrityCheck == false)   // new database261        _ = try await first.session.beginSession()262        await first.close()                                  // no markCleanShutdown: a crash263264        let second = try await NavigatorDatabase(url: scratch.databaseURL)265        #expect(second.openInfo.ranIntegrityCheck == true)266        try await second.session.markCleanShutdown()267        await second.close()268269        let third = try await NavigatorDatabase(url: scratch.databaseURL)270        #expect(third.openInfo.ranIntegrityCheck == false)271        await third.close()272273        let always = try await NavigatorDatabase(url: scratch.databaseURL, options: .init(integrityCheck: .always))274        #expect(always.openInfo.ranIntegrityCheck == true)275        await always.close()276    }277}278
Files main
Menu

Theme