From 35c700ba10692a16e72f5ac0d62d152fa17b3106 Mon Sep 17 00:00:00 2001 From: Yuuki Nishiyama Date: Thu, 19 Nov 2026 13:22:14 -0800 Subject: [PATCH] Add SQLiteEngine.moveTable to move unsent rows from another database file When a sensor's default dbPath changes, rows still waiting for upload in the old file would never be sent. moveTable(_:fromDatabaseAt:) copies the rows above the old database's sync marker, in order, into this database (after the rows already there), drops the old table and removes its marker. A marker from 1.6.1 or earlier is taken over by the old database first, so the new database never skips moved rows. Copy and drop are one transaction here; if the app stops before the old file is updated, the next call copies again (possible duplicates, no loss). It does nothing when there is nothing to move. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +++ .../db/sqlite/SQLiteEngine.swift | 79 ++++++++++++ .../MoveTableTests.swift | 119 ++++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 Tests/com.awareframework.ios.coreTests/MoveTableTests.swift diff --git a/README.md b/README.md index 1ebebea..b7774c7 100644 --- a/README.md +++ b/README.md @@ -417,6 +417,20 @@ Because the old key is deleted when it is moved, it is taken over by exactly one When it is unclear which database a marker belongs to, the smaller value is chosen: rows may be sent again (servers should drop duplicates, as above), but no row is skipped. An app version from 1.6.1 or earlier installed again over a newer one (possible with TestFlight or development builds, not from the App Store) no longer finds the old key and sends its rows again. +#### Moving a table to another database file + +When a sensor's default `dbPath` changes, `SQLiteEngine.moveTable(_:fromDatabaseAt:)` moves the rows still waiting for upload from the old file, so that they are not left behind: + +```swift +// In the sensor, after its table is created in the new database +(dbEngine as? SQLiteEngine)?.moveTable(GyroscopeData.databaseTableName, fromDatabaseAt: "aware") +``` + +- Only rows above the old database's marker move (uploaded rows stay out), in order, with new IDs after the rows the table already has. The next sync sends them. +- The old table is dropped and its marker removed. A marker from 1.6.1 or earlier is taken over by the old database first, so the new database never skips moved rows. +- The copy and the drop are one transaction in the new database. If the app stops before the old file is updated, the next call copies the rows again: the server may receive them twice, but none is lost. +- It does nothing when the old file or table does not exist, so it can be called at every launch. + --- ## SQLiteEngine Utilities diff --git a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift index 17f238f..7a0cfcd 100644 --- a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift +++ b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift @@ -542,6 +542,85 @@ open class SQLiteEngine: Engine { try getAllTableNames(in: db).contains(tableName) } + // MARK: - Moving a table from another database file + + /** + * Moves a table's rows that were not uploaded yet from the database at `oldPath` into this + * engine's database, then drops the table in the old database. + * + * For a sensor whose default `dbPath` changed: without this, the rows still waiting in the old + * file would never be uploaded. The table must already exist in this database. Rows keep their + * order and get new IDs here, after any rows this table already has, so they are uploaded by the + * next sync. Rows at or below the old database's sync marker were uploaded already and are not + * moved; the old marker is removed. + * + * The copy and the drop are one transaction in this database. If the app stops between the + * commit here and in the old file, the next call copies the rows again: the server may receive + * them twice, but none is lost. + * + * - Parameters: + * - tableName: The table, with the same name in both databases. + * - oldPath: The old `dbPath` (for example `"aware"` for `aware.sqlite`). + * - Returns: The number of rows moved (0 when the old file or table does not exist). + */ + @discardableResult + public func moveTable(_ tableName: String, fromDatabaseAt oldPath: String) -> Int { + guard let path = config.path, let queue = getSQLiteInstance() else { return 0 } + let oldURL = Self.fileURL(for: oldPath) + guard Self.sqliteFileName(for: oldPath) != Self.sqliteFileName(for: path), + FileManager.default.fileExists(atPath: oldURL.path) else { return 0 } + + let oldConfig = EngineConfig() + oldConfig.path = oldPath + oldConfig.tableName = tableName + let old = SQLiteEngine(oldConfig) + guard let oldQueue = old.getSQLiteInstance(), + (try? hasTable(tableName, in: oldQueue)) == true else { return 0 } + + // The old database's marker first: it takes over a marker from 1.6.1 or earlier, so that + // marker cannot be given to this database (whose new row IDs it does not describe) + let oldMax = old.maxAssignedId(tableName: tableName) + let oldKey = DbSyncUtils.markerKey(for: tableName, database: old.databaseIdentifier, maxAssignedId: oldMax) + let uploaded = DbSyncUtils.validatedLastUploadedId(forKey: oldKey, maxAssignedId: oldMax) + _ = DbSyncUtils.markerKey(for: tableName, database: databaseIdentifier, + maxAssignedId: maxAssignedId(tableName: tableName)) + + do { + let moved = try Self.retryLockedDatabaseWork { + try queue.writeWithoutTransaction { db -> Int in + try db.execute(sql: "PRAGMA busy_timeout = 10000") + try db.execute(sql: "ATTACH DATABASE ? AS moved_from", arguments: [oldURL.path]) + defer { try? db.execute(sql: "DETACH DATABASE moved_from") } + var count = 0 + try db.inTransaction { + let columns = { (schema: String) throws -> [String] in + try Row.fetchAll(db, sql: "PRAGMA \(schema).table_info(\(tableName))") + .compactMap { $0["name"] as? String } + } + let here = Set(try columns("main")) + let shared = try columns("moved_from").filter { $0 != "id" && here.contains($0) } + if !shared.isEmpty { + let list = shared.map { "\"\($0)\"" }.joined(separator: ", ") + try db.execute( + sql: "INSERT INTO main.\(tableName) (\(list)) SELECT \(list) FROM moved_from.\(tableName) WHERE id > ? ORDER BY id", + arguments: [uploaded]) + count = db.changesCount + } + try db.execute(sql: "DROP TABLE moved_from.\(tableName)") + return .commit + } + return count + } + } + UserDefaults.standard.removeObject(forKey: oldKey) + print("[AWARE::Core] Moved \(moved) rows of \(tableName) from \(old.databaseIdentifier) to \(databaseIdentifier)") + return moved + } catch { + print("[Error][SQLiteEngine] Moving \(tableName) from \(old.databaseIdentifier) failed: \(error)") + return 0 + } + } + public func getAllTableNames() throws -> [String] { guard let db = getSQLiteInstance() else { return [] diff --git a/Tests/com.awareframework.ios.coreTests/MoveTableTests.swift b/Tests/com.awareframework.ios.coreTests/MoveTableTests.swift new file mode 100644 index 0000000..351818b --- /dev/null +++ b/Tests/com.awareframework.ios.coreTests/MoveTableTests.swift @@ -0,0 +1,119 @@ +// +// MoveTableTests.swift +// com.awareframework.ios.core.Tests +// +// SQLiteEngine.moveTable(_:fromDatabaseAt:): rows not uploaded yet move to the new database file, +// in order and once; uploaded rows and the old table do not stay behind. +// + +import XCTest +import GRDB +@testable import com_awareframework_ios_core + +final class MoveTableTests: XCTestCase { + + private let table = "move_table_test" + private var oldPath = "" + private var newPath = "" + + override func setUp() { + super.setUp() + oldPath = "move_old_\(UUID().uuidString)" + newPath = "move_new_\(UUID().uuidString)" + } + + override func tearDown() { + for path in [oldPath, newPath] { + UserDefaults.standard.removeObject( + forKey: DbSyncUtils.databaseKey(for: table, database: SQLiteEngine.sqliteFileName(for: path))) + } + UserDefaults.standard.removeObject(forKey: DbSyncUtils.legacyKey(for: table)) + super.tearDown() + } + + private func engine(_ path: String, rows: Int = 0, extraColumn: Bool = false) throws -> SQLiteEngine { + let config = Engine.EngineConfig() + config.path = path + config.tableName = table + let engine = SQLiteEngine(config) + let queue = try XCTUnwrap(engine.getSQLiteInstance()) + try queue.write { db in + try db.execute(sql: """ + CREATE TABLE IF NOT EXISTS \(table) (id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp INTEGER NOT NULL, deviceId TEXT NOT NULL, x REAL\(extraColumn ? ", extra TEXT" : "")) + """) + for i in 0.. [Int64] { + (engine.fetch(filter: nil, limit: nil) ?? []).compactMap { $0["timestamp"] as? Int64 } + } + + func testMovesOnlyRowsNotUploadedAndDropsTheOldTable() throws { + _ = try engine(oldPath, rows: 10) + setMarker(4, path: oldPath) // rows 1...4 were uploaded + let new = try engine(newPath, extraColumn: true) // the new table may have more columns + + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: oldPath), 6) + XCTAssertEqual(timestamps(new), (1_004..<1_010).map(Int64.init), "rows 5...10, in order") + let xs = (new.fetch(filter: nil, limit: nil) ?? []).compactMap { $0["x"] as? Double } + XCTAssertEqual(xs.first, 4.0 / 3, "values unchanged") + + let old = try XCTUnwrap(SQLiteEngine({ let c = Engine.EngineConfig(); c.path = oldPath; return c }()) + .getSQLiteInstance()) + // Asked from SQLite itself: GRDB's tableExists() caches the schema per connection, and the + // table was dropped through another connection + let left = try old.read { + try Int.fetchOne($0, sql: "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?", + arguments: [table]) ?? -1 + } + XCTAssertEqual(left, 0, "old table dropped") + XCTAssertNil(UserDefaults.standard.object( + forKey: DbSyncUtils.databaseKey(for: table, database: SQLiteEngine.sqliteFileName(for: oldPath))), + "old marker removed") + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: oldPath), 0, "nothing left to move") + } + + func testRowsAreAddedAfterRowsAlreadyThere() throws { + _ = try engine(oldPath, rows: 3) + let new = try engine(newPath, rows: 2) + setMarker(2, path: newPath) // the new table's rows were uploaded + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: oldPath), 3) + let ids = (new.fetch(filter: "id > 2", limit: nil) ?? []).compactMap { $0["id"] as? Int64 } + XCTAssertEqual(ids, [3, 4, 5], "moved rows come after the new marker, so the next sync sends them") + } + + /// A marker from 1.6.1 or earlier (table name only) belongs to the old database. If the new + /// database took it over, it would skip the moved rows, which get new IDs from 1. + func testOldStyleMarkerDoesNotSkipMovedRows() throws { + _ = try engine(oldPath, rows: 10) + UserDefaults.standard.set(3, forKey: DbSyncUtils.legacyKey(for: table)) + let new = try engine(newPath) + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: oldPath), 7, "rows 4...10") + let key = DbSyncUtils.markerKey(for: table, database: new.databaseIdentifier, + maxAssignedId: new.maxAssignedId(tableName: table)) + XCTAssertEqual(DbSyncUtils.getLastUploadedId(forKey: key), 0, "every moved row is uploaded") + XCTAssertNil(UserDefaults.standard.object(forKey: DbSyncUtils.legacyKey(for: table))) + } + + func testNothingToMove() throws { + let new = try engine(newPath) + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: "missing_\(UUID().uuidString)"), 0, "no old file") + _ = try engine(oldPath) + let other = try XCTUnwrap(SQLiteEngine({ let c = Engine.EngineConfig(); c.path = oldPath; return c }()) + .getSQLiteInstance()) + try other.write { try $0.execute(sql: "DROP TABLE \(table)") } + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: oldPath), 0, "no old table") + XCTAssertEqual(new.moveTable(table, fromDatabaseAt: newPath), 0, "same database") + } +}