diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 222ac6dcb..debe9590a 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -222,6 +222,12 @@ extension Association { relation = relation.unordered() } } + + public func withStableOrder() -> Self { + withDestinationRelation { relation in + relation = relation.withStableOrder() + } + } } // TableRequest conformance diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 96b890cb4..c573a2f3c 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -344,6 +344,12 @@ extension QueryInterfaceRequest: OrderedRequest { $0.relation = $0.relation.unordered() } } + + public func withStableOrder() -> QueryInterfaceRequest { + with { + $0.relation = $0.relation.withStableOrder() + } + } } extension QueryInterfaceRequest: AggregatingRequest { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 9e64e7d25..def5c2f52 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -905,6 +905,7 @@ extension AggregatingRequest { /// - ``orderWhenConnected(_:)`` /// - ``reversed()`` /// - ``unordered()`` +/// - ``withStableOrder()`` public protocol OrderedRequest { /// Sorts the fetched rows according to the given SQL ordering terms. /// @@ -965,6 +966,14 @@ public protocol OrderedRequest { /// .unordered() /// ``` func unordered() -> Self + + /// Returns a request with a stable order. + /// + /// The returned request lifts ordering ambiguities and always return + /// its results in the same order. + /// + /// The purpose of this method is to make requests testable. + func withStableOrder() -> Self } extension OrderedRequest { @@ -1378,6 +1387,7 @@ extension JoinableRequest where Self: SelectionRequest { /// - ``TableRequest/orderByPrimaryKey()`` /// - ``OrderedRequest/reversed()`` /// - ``OrderedRequest/unordered()`` +/// - ``OrderedRequest/withStableOrder()`` /// /// ### Associations /// diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index c47b83a45..a7e206353 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -282,6 +282,21 @@ extension SQLRelation: Refinable { } } + func withStableOrder() -> Self { + with { + // Order by primary key. Don't order by rowid because those are + // not stable: rowids can change after a vacuum. + $0.ordering = $0.ordering.appending(Ordering(orderings: { db in + try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering } + })) + $0.children = children.mapValues { child in + child.with { + $0.relation = $0.relation.withStableOrder() + } + } + } + } + // Remove ordering iff relation has no LIMIT clause func unorderedUnlessLimited() -> Self { if limit != nil { diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index d5555ee9e..1987c4e3d 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -208,6 +208,15 @@ class DerivableRequestTests: GRDBTestCase { SELECT * FROM "author" """) + sqlQueries.removeAll() + _ /* stableOrderAuthors */ = try Author.all() + .orderByFullName() + .withStableOrder() + .fetchAll(db) + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "author" ORDER BY "lastName" COLLATE swiftLocalizedCaseInsensitiveCompare, "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare, "id" + """) + // ... for two requests (2) sqlQueries.removeAll() let bookTitles = try Book @@ -252,6 +261,23 @@ class DerivableRequestTests: GRDBTestCase { SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" """) + + sqlQueries.removeAll() + _ /* stableOrderBooks */ = try Book + .joining(required: Book.author.orderByFullName()) + .orderByTitle() + .withStableOrder() + .fetchAll(db) + XCTAssertEqual(lastSQLQuery, """ + SELECT "book".* FROM "book" \ + JOIN "author" ON "author"."id" = "book"."authorId" \ + ORDER BY \ + "book"."title" COLLATE swiftLocalizedCaseInsensitiveCompare, \ + "book"."id", \ + "author"."lastName" COLLATE swiftLocalizedCaseInsensitiveCompare, \ + "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare, \ + "author"."id" + """) } } diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 358cc0680..1ce98c182 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -436,6 +436,17 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalNonOptionalPrimaryKeySingle.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"minimalSingles\" ORDER BY \"id\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index da9e7bc9f..43e649f46 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -470,6 +470,17 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalRowID.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 81e5975c4..8c5c1f036 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -492,6 +492,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalSingle.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 07ce9f3ce..677772281 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -562,6 +562,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index cf1cbe4ef..f8b8c8e10 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -510,6 +510,17 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Citizenship.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"") + } + } + + // MARK: - Exists func testExistsWithNilPrimaryKeyReturnsFalse() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index d07baeaa1..8582a5e48 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -147,6 +147,17 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Item.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"items\" ORDER BY \"rowid\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index ab9abe37c..eb9023cf2 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -555,6 +555,17 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"persons\" ORDER BY \"id\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 8342ebab8..69664f729 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -497,6 +497,17 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Pet.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"pets\" ORDER BY \"UUID\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 05faac457..e1444cdf3 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -494,6 +494,17 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } + // MARK: - Stable order + + func testStableOrder() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Email.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"emails\" ORDER BY \"email\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws {