From 5c39a19b2ad1f134f6cce5367c8a3882a728d009 Mon Sep 17 00:00:00 2001 From: Yuuki Nishiyama Date: Wed, 18 Nov 2026 15:46:17 -0800 Subject: [PATCH] Return fetched rows in row ID order unless the filter orders them SQL does not define the order of rows without ORDER BY. The sync reads `id > lastUploadedId` with `LIMIT batchSize` and moves its marker, and deletes rows, up to the last row it read, so it relies on the batch being the lowest IDs in order. SQLite returns them in that order today, but not by contract: with the rows in another order (shown with PRAGMA reverse_unordered_selects), rows that were not uploaded would be skipped and deleted, and others sent twice. The Apple Watch transfer pages the same way. - fetch(filter:limit:) appends ORDER BY rowid (id is the rowid) unless the filter has its own ORDER BY, as in "... ORDER BY timestamp DESC". The query plan is unchanged (rowid range search), and tables without an `id` column still work. - Tests: ID order under reverse_unordered_selects (fails without this change), a filter with its own ORDER BY, and the ORDER BY detection. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../db/sqlite/SQLiteEngine.swift | 14 +++++++ .../com_awareframework_ios_coreTests.swift | 37 +++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 321af8e..ce2bdf6 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ All settings can also be given as a dictionary with `DbSyncConfig(_:)` or `set(c `DbSyncHelper` uploads each table incrementally: -1. **Progress is tracked by row ID.** Every table of every database stores the ID of the last row uploaded successfully in `UserDefaults` (see [Sync markers](#sync-markers)). A sync sends rows with `id` greater than that value, in batches of `batchSize`, in ID order. +1. **Progress is tracked by row ID.** Every table of every database stores the ID of the last row uploaded successfully in `UserDefaults` (see [Sync markers](#sync-markers)). A sync sends rows with `id` greater than that value, in batches of `batchSize`, in ID order. `Engine.fetch(filter:limit:)` returns rows in row ID order (`ORDER BY rowid`) unless the filter has its own `ORDER BY`, so each batch is the lowest IDs above the marker whatever query plan SQLite chooses. 2. **Only HTTP 2xx counts as success.** The last uploaded ID advances (and, with `removeAfterSync`, uploaded rows older than `keepDataAfterSync` are deleted) only after the server answers with a 2xx status. 3. **Failed rows are retried.** On a non-2xx status, a network error, or a timeout (30 s per request), the last uploaded ID does not change and the sync of that table stops. The same rows are sent again at the next sync. Nothing is lost while the server is down, and the backlog is sent in batches once it is back. 4. **Uploaded rows are not sent again.** Rows at or below the last uploaded ID are never selected again, whether or not they are kept locally. diff --git a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift index b3a7285..5ede9e4 100644 --- a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift +++ b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift @@ -218,6 +218,7 @@ open class SQLiteEngine: Engine { do { var sql = "SELECT * FROM \(tableName)" if let f = filter { sql += " WHERE \(f)" } + if !Self.containsOrderBy(filter) { sql += " ORDER BY rowid" } if let l = limit { sql += " LIMIT \(l)" } return try Self.retryLockedDatabaseWork { try db.read { db in @@ -244,6 +245,19 @@ open class SQLiteEngine: Engine { completion?(fetch(filter: filter, limit: limit), nil) } + /// Whether a `filter` already orders the rows (e.g. `"timestamp >= 0 ORDER BY timestamp DESC"`). + /// + /// Without its own `ORDER BY`, `fetch` returns rows in row ID order (`ORDER BY rowid`; `id` is the + /// rowid). SQL does not define the order of rows without `ORDER BY`. The sync reads + /// `id > lastUploadedId` with `LIMIT batchSize` and moves its marker, and deletes rows, up to the + /// last row it read, so it needs the batch to be the lowest IDs in order: in any other order, + /// rows that were not uploaded would be skipped or deleted. A range search on the rowid already + /// returns rows in that order, so `ORDER BY rowid` adds no sort. + static func containsOrderBy(_ filter: String?) -> Bool { + guard let filter else { return false } + return filter.range(of: #"\border\s+by\b"#, options: [.regularExpression, .caseInsensitive]) != nil + } + // MARK: - Remove open override func removeAll(completion: ((Error?) -> Void)?) { diff --git a/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift b/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift index 1cc3762..0f04f9a 100644 --- a/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift +++ b/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift @@ -391,6 +391,43 @@ class UnitTests: XCTestCase { XCTAssertNoThrow(try SQLiteEngine.createParentDirectory(ofDatabaseAt: path)) } + /// `fetch` returns rows in ID order even when SQLite returns unordered rows in another order. + /// `PRAGMA reverse_unordered_selects` makes SQLite reverse every SELECT without ORDER BY. + func testFetchReturnsRowsInIdOrder() throws { + guard let engine = makeEmptySQLiteEngine("fetch_order_test"), let queue = engine.getSQLiteInstance() else { + return XCTFail("SQLite engine is not available") + } + engine.save((0..<10).map { i in sample(at: Int64(1_000 + i)) } as [any BaseDbModelSQLite]) + let all = ids(engine) + try queue.writeWithoutTransaction { db in try db.execute(sql: "PRAGMA reverse_unordered_selects = ON") } + defer { + try? queue.writeWithoutTransaction { db in try db.execute(sql: "PRAGMA reverse_unordered_selects = OFF") } + engine.removeAll() + } + + // The sync's query: the next batch must be the lowest IDs above the marker, in order + let batch = (engine.fetch(filter: "id > \(all[1])", limit: 3) ?? []).compactMap { $0["id"] as? Int64 } + XCTAssertEqual(batch, Array(all[2...4])) + let first = (engine.fetch(filter: nil, limit: 2) ?? []).compactMap { $0["id"] as? Int64 } + XCTAssertEqual(first, Array(all[0...1])) + + // A filter with its own ORDER BY keeps it (no second ORDER BY is added) + let latest = (engine.fetch(filter: "timestamp >= 1003 ORDER BY timestamp DESC", limit: 2) ?? []) + .compactMap { $0["timestamp"] as? Int64 } + XCTAssertEqual(latest, [1009, 1008]) + let lowercase = (engine.fetch(filter: "timestamp >= 0 order by timestamp desc", limit: 1) ?? []) + .compactMap { $0["timestamp"] as? Int64 } + XCTAssertEqual(lowercase, [1009]) + } + + func testContainsOrderBy() { + XCTAssertFalse(SQLiteEngine.containsOrderBy(nil)) + XCTAssertFalse(SQLiteEngine.containsOrderBy("id > 10")) + XCTAssertFalse(SQLiteEngine.containsOrderBy("label = 'border'")) + XCTAssertTrue(SQLiteEngine.containsOrderBy("timestamp >= 0 ORDER BY timestamp DESC")) + XCTAssertTrue(SQLiteEngine.containsOrderBy("id > 0 order\nby id")) + } + /// Makes a SQLite engine with an empty table `A` in its own database file. private func makeEmptySQLiteEngine(_ dbPath: String) -> SQLiteEngine? { let sensor = AwareSensor()