Skip to content

Commit 46ebd93

Browse files
authored
Merge pull request #6 from PureSwift/feature/default-sort
Default sort by id when no sort descriptors provided
2 parents 877f9ef + 851af0e commit 46ebd93

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

‎Sources/CoreModelSQLite/Database.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,9 @@ internal extension FetchRequest {
359359
return sort.property.rawValue.quotedIdentifier + (sort.ascending ? " ASC" : " DESC")
360360
}
361361
sql += " ORDER BY " + terms.joined(separator: ", ")
362+
} else {
363+
// match CoreData's default behavior of sorting by object ID when no sort descriptors are provided
364+
sql += " ORDER BY \(SQLiteDatabase.primaryKeyColumn.quotedIdentifier) ASC"
362365
}
363366
if fetchLimit > 0 {
364367
sql += " LIMIT \(fetchLimit)"

‎Tests/CoreModelSQLiteTests/CoreModelSQLiteTests.swift‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,24 @@ func makeDatabase() throws -> SQLiteDatabase {
195195
#expect(inCount == 2)
196196
}
197197

198+
@Test func defaultSortByID() async throws {
199+
let database = try makeDatabase()
200+
// insert out of ID order, to ensure the default sort isn't just insertion order
201+
let ids: [ObjectID] = ["person5", "person1", "person9", "person3", "person7"]
202+
let people = ids.map { id in
203+
ModelData(entity: "Person", id: id, attributes: ["name": .string("Person \(id.rawValue)")])
204+
}
205+
try await database.insert(people)
206+
207+
// no sort descriptors provided, should default to sorting by id, like CoreData
208+
let request = FetchRequest(entity: "Person")
209+
let results = try await database.fetch(request)
210+
#expect(results.map { $0.id } == ids.sorted { $0.rawValue < $1.rawValue })
211+
212+
let fetchedIDs = try await database.fetchID(request)
213+
#expect(fetchedIDs == ids.sorted { $0.rawValue < $1.rawValue })
214+
}
215+
198216
@Test func toOneRelationship() async throws {
199217
let database = try makeDatabase()
200218
let team = ModelData(entity: "Team", id: "team1", attributes: ["name": .string("Red")])

0 commit comments

Comments
 (0)