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
3 changes: 3 additions & 0 deletions Sources/CoreModelSQLite/Database.swift
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,9 @@ internal extension FetchRequest {
return sort.property.rawValue.quotedIdentifier + (sort.ascending ? " ASC" : " DESC")
}
sql += " ORDER BY " + terms.joined(separator: ", ")
} else {
// match CoreData's default behavior of sorting by object ID when no sort descriptors are provided
sql += " ORDER BY \(SQLiteDatabase.primaryKeyColumn.quotedIdentifier) ASC"
}
if fetchLimit > 0 {
sql += " LIMIT \(fetchLimit)"
Expand Down
18 changes: 18 additions & 0 deletions Tests/CoreModelSQLiteTests/CoreModelSQLiteTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,24 @@ func makeDatabase() throws -> SQLiteDatabase {
#expect(inCount == 2)
}

@Test func defaultSortByID() async throws {
let database = try makeDatabase()
// insert out of ID order, to ensure the default sort isn't just insertion order
let ids: [ObjectID] = ["person5", "person1", "person9", "person3", "person7"]
let people = ids.map { id in
ModelData(entity: "Person", id: id, attributes: ["name": .string("Person \(id.rawValue)")])
}
try await database.insert(people)

// no sort descriptors provided, should default to sorting by id, like CoreData
let request = FetchRequest(entity: "Person")
let results = try await database.fetch(request)
#expect(results.map { $0.id } == ids.sorted { $0.rawValue < $1.rawValue })

let fetchedIDs = try await database.fetchID(request)
#expect(fetchedIDs == ids.sorted { $0.rawValue < $1.rawValue })
}

@Test func toOneRelationship() async throws {
let database = try makeDatabase()
let team = ModelData(entity: "Team", id: "team1", attributes: ["name": .string("Red")])
Expand Down
Loading