From 7ffc332327d6ebe1a61d139de24e413e83d80cd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 Jul 2022 14:06:22 +0200 Subject: [PATCH] BREAKING: replace selectID() with selectPrimaryKey(as:) Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type: struct Player: Identifiable, MutablePersistableRecord { var id: Int64? } Player.selectID() // QueryInterface This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set, Int64??. Instead, we introduce selectPrimaryKey(as:), which allows the user to provide the desired type. Player.selectPrimaryKey(as: Int64.self) // QueryInterface --- CHANGELOG.md | 1 + .../GRDBAsyncDemoTests/AppDatabaseTests.swift | 2 +- Documentation/GRDB6MigrationGuide.md | 10 +++++ .../GoodPracticesForDesigningRecordTypes.md | 6 +-- GRDB/Fixits.swift | 18 ++++++++ .../Request/QueryInterfaceRequest.swift | 44 ++++++++++--------- GRDB/QueryInterface/SQL/Table.swift | 22 ++++++++-- .../TableRecord+QueryInterfaceRequest.swift | 26 +++++++---- README.md | 28 ++++++------ ...imalNonOptionalPrimaryKeySingleTests.swift | 22 ++++------ .../RecordMinimalPrimaryKeyRowIDTests.swift | 22 ++++------ .../RecordMinimalPrimaryKeySingleTests.swift | 24 +++++----- Tests/GRDBTests/TableTests.swift | 5 ++- 13 files changed, 138 insertions(+), 92 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6502c6b20..5da6aa9bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ are required. - **Breaking**: Removed deprecated methods - **Breaking**: The in-memory `DatabaseQueue()` initializer can now throw errors. +- **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`. - **New**: Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md). ## 5.26.0 diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift index fd50726ad..2d0dd4ef8 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift @@ -61,7 +61,7 @@ class AppDatabaseTests: XCTestCase { _ = try Player(id: nil, name: "Barbara", score: 200).inserted(db) _ = try Player(id: nil, name: "Craig", score: 150).inserted(db) _ = try Player(id: nil, name: "David", score: 120).inserted(db) - return try Player.selectID().fetchAll(db) + return try Player.selectPrimaryKey().fetchAll(db) } // When we delete two players diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 27d97f938..be65e86f3 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -50,3 +50,13 @@ The `Cursor` protocol has also gained a primary associated type (the type of its -let dbQueue = DatabaseQueue() +let dbQueue = try DatabaseQueue() ``` + +- The `selectID()` method is removed. You can provide your own implementation, based on the new `selectPrimaryKey(as:)` method: + + ```swift + extension QueryInterfaceRequest { + func selectID() -> QueryInterfaceRequest { + selectPrimaryKey() + } + } + ``` diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index e708cc4f7..8eef81786 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -371,13 +371,13 @@ Extensions to the `DerivableRequest` protocol can not change the type of request // Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ extension QueryInterfaceRequest where RowDecoder == Author { // Selects author ids - func id() -> QueryInterfaceRequest { - select(Author.Columns.id) + func selectId() -> QueryInterfaceRequest { + selectPrimaryKey(as: Int64.self) } } // IDs of French authors -let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db) +let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db) ``` ## Compose Records diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 2e48aa6ac..b61dda4b7 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -52,12 +52,30 @@ typealias FastNullableDatabaseValueCursor has been replaced with DatabaseValueCursor") typealias NullableDatabaseValueCursor = DatabaseValueCursor +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { + @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") + public func selectID() -> QueryInterfaceRequest { preconditionFailure() } +} + @available(*, unavailable, renamed: "Statement") public typealias SelectStatement = Statement @available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { + @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") + public func selectID() -> QueryInterfaceRequest { preconditionFailure() } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { + @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") + public static func selectID() -> QueryInterfaceRequest { preconditionFailure() } +} + @available(*, unavailable, renamed: "Statement") public typealias UpdateStatement = Statement diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 84a7b5caf..1f69d446d 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -149,6 +149,30 @@ extension QueryInterfaceRequest: SelectionRequest { select(sqlLiteral, as: type) } + /// Creates a request which selects the primary key. + /// + /// All primary keys are supported: + /// + /// // SELECT id FROM player WHERE ... + /// let request = try Player.filter(...).selectPrimaryKey(as: Int64.self) + /// + /// // SELECT code FROM country WHERE ... + /// let request = try Country.filter(...).selectPrimaryKey(as: String.self) + /// + /// // SELECT citizenId, countryCode FROM citizenship WHERE ... + /// let request = try Citizenship.filter(...).selectPrimaryKey(as: Row.self) + public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + with { request in + let tableName = request.relation.source.tableName + request.relation = request.relation.select { db in + try db.primaryKey(tableName).columns.map { Column($0).sqlSelection } + } + } + .asRequest(of: PrimaryKey.self) + } + /// Creates a request which appends *selection promise*. /// /// // SELECT id, email, name FROM player @@ -165,26 +189,6 @@ extension QueryInterfaceRequest: SelectionRequest { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension QueryInterfaceRequest -where RowDecoder: Identifiable, - RowDecoder.ID: DatabaseValueConvertible -{ - /// Creates a request which selects the primary key. - /// - /// // SELECT id FROM player WHERE ... - /// let request = try Player.filter(...).selectID() - public func selectID() -> QueryInterfaceRequest { - select { db in - let primaryKey = try db.primaryKey(self.databaseTableName) - GRDBPrecondition( - primaryKey.columns.count == 1, - "selectID requires a single-column primary key in the table \(self.databaseTableName)") - return [Column(primaryKey.columns[0])] - }.asRequest(of: RowDecoder.ID.self) - } -} - extension QueryInterfaceRequest: FilteredRequest { /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 3945e9ab6..f91af0a7e 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -393,14 +393,28 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv public func filter(ids: some Collection) -> QueryInterfaceRequest { all().filter(ids: ids) } - +} + +extension Table { /// Creates a request which selects the primary key. /// + /// All primary keys are supported: + /// /// // SELECT id FROM player /// let table = Table("player") - /// let request = try table.selectID() - public func selectID() -> QueryInterfaceRequest { - all().selectID() + /// let request = try table.selectPrimaryKey(as: Int64.self) + /// + /// // SELECT code FROM country + /// let table = Table("country") + /// let request = try table.selectPrimaryKey(as: String.self) + /// + /// // SELECT citizenId, countryCode FROM citizenship + /// let table = Table("citizenship") + /// let request = try table.selectPrimaryKey(as: Row.self) + public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + all().selectPrimaryKey(as: type) } } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 08584faf7..35b5c1d55 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -130,6 +130,24 @@ extension TableRecord { all().select(sqlLiteral, as: type) } + /// Creates a request which selects the primary key. + /// + /// All primary keys are supported: + /// + /// // SELECT id FROM player + /// let request = try Player.selectPrimaryKey(as: Int64.self) + /// + /// // SELECT code FROM country + /// let request = try Country.selectPrimaryKey(as: String.self) + /// + /// // SELECT citizenId, countryCode FROM citizenship + /// let request = try Citizenship.selectPrimaryKey(as: Row.self) + public static func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + all().selectPrimaryKey(as: type) + } + /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player @@ -364,12 +382,4 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { public static func filter(ids: some Collection) -> QueryInterfaceRequest { all().filter(ids: ids) } - - /// Creates a request which selects the primary key. - /// - /// // SELECT id FROM player - /// let request = try Player.selectID() - public static func selectID() -> QueryInterfaceRequest { - all().selectID() - } } diff --git a/README.md b/README.md index 253fdfdb5..cd778ba04 100644 --- a/README.md +++ b/README.md @@ -3016,9 +3016,6 @@ let players = try Player.fetchSet(db, ids: [1, 2, 3]) let request = Player.filter(id: 1) let request = Player.filter(ids: [1, 2, 3]) -let ids = try Player.selectID().fetchAll(db) -let ids = try Player.filter(...).selectID().fetchSet(db) - try Player.deleteOne(db, id: 1) try Player.deleteAll(db, ids: [1, 2, 3]) ``` @@ -4076,7 +4073,7 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.none()` | [TableRecord] | ² | | `Type.select(...)` | [TableRecord] | ² | | `Type.select(..., as:...)` | [TableRecord] | ² | -| `Type.selectID()` | [TableRecord] & Identifiable | [*](#identifiable-records) | +| `Type.selectPrimaryKey(as:...)` | [TableRecord] | ² | | `Type.annotated(with:...)` | [TableRecord] | ² | | `Type.filter(...)` | [TableRecord] | ² | | `Type.filter(id:)` | [TableRecord] & Identifiable | [*](#identifiable-records) | @@ -4491,16 +4488,6 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.select(nameColumn, as: String.self) ``` -- `selectID()` is available on [Identifiable Records]. It supports all tables that have a single-column primary key: - - ```swift - // SELECT id FROM player - Player.selectID() - - // SELECT id FROM player WHERE name IS NOT NULL - Player.filter(nameColumn != nil).selectID() - ``` - - `annotated(with: expression...)` extends the selection. ```swift @@ -4677,6 +4664,19 @@ You can now build requests with the following methods: `all`, `none`, `select`, - Other requests that involve the primary key: + - `selectPrimaryKey(as:)` selects the primary key. + + ```swift + // SELECT id FROM player + Player.selectPrimaryKey(as: Int64.self) // QueryInterfaceRequest + + // SELECT code FROM country + Country.selectPrimaryKey(as: String.self) // QueryInterfaceRequest + + // SELECT citizenId, countryCode FROM citizenship + Citizenship.selectPrimaryKey(as: Row.self) // QueryInterfaceRequest + ``` + - `orderByPrimaryKey()` sorts by primary key. ```swift diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 97bdbddd7..17a1fefd1 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -747,33 +747,29 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { } } - // MARK: Select ID + // MARK: Select PrimaryKey - func test_static_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_static_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID") try record.insert(db) - let ids = try MinimalSingle.selectID().fetchAll(db) + let ids: [String] = try MinimalSingle.selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": "theUUID"]]) } } - func test_request_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID") try record.insert(db) - let ids = try MinimalSingle.all().selectID().fetchAll(db) + let ids: [String] = try MinimalSingle.all().selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.all().selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": "theUUID"]]) } } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 98a557ac6..688eabd2f 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -787,33 +787,29 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } - // MARK: Select ID + // MARK: Select PrimaryKey - func test_static_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_static_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalRowID() try record.insert(db) - let ids = try MinimalRowID.selectID().fetchAll(db) + let ids: [Int64] = try MinimalRowID.selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, [1]) + let rows = try MinimalRowID.selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": 1]]) } } - func test_request_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalRowID() try record.insert(db) - let ids = try MinimalRowID.all().selectID().fetchAll(db) + let ids: [Int64] = try MinimalRowID.all().selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, [1]) + let rows = try MinimalRowID.all().selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["id": 1]]) } } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 8fba71a17..27d635e89 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -819,35 +819,31 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } - // MARK: Select ID - - func test_static_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + // MARK: Select PrimaryKey + + func test_static_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) - let ids = try MinimalSingle.selectID().fetchAll(db) + let ids: [String] = try MinimalSingle.selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["UUID": "theUUID"]]) } } - func test_request_selectID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = MinimalSingle() record.UUID = "theUUID" try record.insert(db) - let ids = try MinimalSingle.all().selectID().fetchAll(db) + let ids: [String] = try MinimalSingle.all().selectPrimaryKey().fetchAll(db) XCTAssertEqual(ids, ["theUUID"]) + let rows = try MinimalSingle.all().selectPrimaryKey(as: Row.self).fetchAll(db) + XCTAssertEqual(rows, [["UUID": "theUUID"]]) } } } diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index 7645b584d..375649d4d 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -52,6 +52,9 @@ class TableTests: GRDBTestCase { """) try XCTAssertEqual(t.select(Column("id"), as: Int64.self).fetchOne(db), 1) try XCTAssertEqual(t.select(Column("id")).fetchOne(db), 1) + try XCTAssertEqual(t.selectPrimaryKey().fetchOne(db), 1) + try XCTAssertEqual(t.selectPrimaryKey(as: Int64.self).fetchOne(db), 1) + try XCTAssertEqual(t.selectPrimaryKey(as: Row.self).fetchOne(db), ["id": 1]) try XCTAssertEqual(t.select([Column("name")], as: String.self).fetchOne(db), "Alice") try XCTAssertEqual(t.select([Column("name")]).fetchOne(db), "Alice") try XCTAssertEqual(t.select(sql: "id", as: Int64.self).fetchOne(db), 1) @@ -124,7 +127,6 @@ class TableTests: GRDBTestCase { try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ SELECT * FROM "player" WHERE "id" IN (1, 2, 3) """) - try XCTAssertEqual(t.selectID().fetchOne(db), 1) } if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { @@ -140,7 +142,6 @@ class TableTests: GRDBTestCase { try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ SELECT * FROM "player" WHERE "id" IN (1, 2, 3) """) - try XCTAssertEqual(t.selectID().fetchOne(db), 1) } } }