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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)?) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading