From 87b236dfe0d6441c19dc46829ba7ec7200a78c0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 11 Feb 2025 20:41:48 +0100 Subject: [PATCH] selectID This reverts 7ffc332327d6ebe1a61d139de24e413e83d80cd9 At the time, selectID was replaced with selectPrimaryKey(as:) because: > 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??. This problem is reintroduced, but we now recommend against optional ids in https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices. And record with optional ids can use selectPrimaryKey(as:). --- .../RecordRecommendedPractices.md | 12 ++++---- .../Request/QueryInterfaceRequest.swift | 23 +++++++++++++- GRDB/QueryInterface/SQL/Table.swift | 17 +++++++++++ .../TableRecord+QueryInterfaceRequest.swift | 14 +++++++++ GRDB/Record/TableRecord.swift | 1 + README.md | 10 +++++++ ...imalNonOptionalPrimaryKeySingleTests.swift | 20 +++++++++++++ .../RecordMinimalPrimaryKeyRowIDTests.swift | 20 +++++++++++++ .../RecordMinimalPrimaryKeySingleTests.swift | 30 ++++++++++++++++--- Tests/GRDBTests/TableTests.swift | 4 +++ 10 files changed, 140 insertions(+), 11 deletions(-) diff --git a/GRDB/Documentation.docc/RecordRecommendedPractices.md b/GRDB/Documentation.docc/RecordRecommendedPractices.md index 222080a29..44a0d345e 100644 --- a/GRDB/Documentation.docc/RecordRecommendedPractices.md +++ b/GRDB/Documentation.docc/RecordRecommendedPractices.md @@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request ```swift extension QueryInterfaceRequest { - // Selects author ids - func selectId() -> QueryInterfaceRequest { - selectPrimaryKey(as: Int64.self) + // Selects authors' name + func selectName() -> QueryInterfaceRequest { + select(Author.Columns.name) } } -// The ids of Japanese authors -let ids: Set = try Author.all() +// The names of Japanese authors +let names: Set = try Author.all() .filter(countryCode: "JP") - .selectId() + .selectName() .fetchSet(db) ``` diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 56451b438..4a21a3cde 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -56,6 +56,7 @@ /// - ``select(_:as:)-3o8qw`` /// - ``select(literal:as:)`` /// - ``select(sql:arguments:as:)`` +/// - ``selectID()`` /// - ``selectPrimaryKey(as:)`` /// /// ### Batch Delete @@ -237,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest { select(sqlLiteral, as: type) } - /// Selects the primary key. + /// Returns a request that selects the primary key. /// /// All primary keys are supported: /// @@ -281,6 +282,26 @@ extension QueryInterfaceRequest: SelectionRequest { .asRequest(of: PrimaryKey.self) } + /// Returns a request that selects the primary key. + /// + /// For example: + /// + /// ```swift + /// // SELECT id FROM player WHERE ... + /// let request = try Player.filter(...).selectID() + /// ``` + public func selectID() -> QueryInterfaceRequest + where RowDecoder: Identifiable + { + selectWhenConnected { 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) + } + public func annotatedWhenConnected( with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index a96714bc1..24ec37db4 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -94,6 +94,7 @@ /// - ``select(literal:as:)`` /// - ``select(sql:arguments:)`` /// - ``select(sql:arguments:as:)`` +/// - ``selectID()`` /// - ``selectPrimaryKey(as:)`` /// - ``with(_:)`` /// @@ -424,6 +425,22 @@ extension Table { all().selectPrimaryKey(as: type) } + /// Returns a request that selects the primary key. + /// + /// For example: + /// + /// ```swift + /// let table = Table("player") + /// + /// // SELECT id FROM player + /// let request = try table.selectID() + /// ``` + public func selectID() -> QueryInterfaceRequest + where RowDecoder: Identifiable + { + all().selectID() + } + /// Returns a request with the provided result columns appended to the /// table columns. /// diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index e86156f24..780865308 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -251,6 +251,20 @@ extension TableRecord { all().selectPrimaryKey(as: type) } + /// Returns a request that selects the primary key. + /// + /// For example: + /// + /// ```swift + /// // SELECT id FROM player + /// let request = try Player.selectID() + /// ``` + public static func selectID() -> QueryInterfaceRequest + where Self: Identifiable + { + all().selectID() + } + /// Returns a request with the provided result columns appended to the /// record selection. /// diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 68da21851..9cc22dd88 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -98,6 +98,7 @@ import Foundation /// - ``select(literal:as:)`` /// - ``select(sql:arguments:)`` /// - ``select(sql:arguments:as:)`` +/// - ``selectID()`` /// - ``selectPrimaryKey(as:)`` /// - ``with(_:)`` /// diff --git a/README.md b/README.md index fe43721f7..23fd9f519 100644 --- a/README.md +++ b/README.md @@ -3341,6 +3341,16 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.select(nameColumn, as: String.self) ``` +- [`selectID()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/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...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection. ```swift diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 11bd3e428..069f0e4f3 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -800,6 +800,16 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { } } + func test_static_selectID() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID") + try record.insert(db) + let ids: [String] = try MinimalSingle.selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -811,4 +821,14 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(rows, [["id": "theUUID"]]) } } + + func test_request_selectID() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID") + try record.insert(db) + let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 91f38ad01..7102057a5 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -844,6 +844,16 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } + func test_static_selectID() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalRowID() + try record.insert(db) + let ids: [Int64?] = try MinimalRowID.selectID().fetchAll(db) + XCTAssertEqual(ids, [1]) + } + } + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -855,4 +865,14 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(rows, [["id": 1]]) } } + + func test_request_selectID() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalRowID() + try record.insert(db) + let ids: [Int64?] = try MinimalRowID.all().selectID().fetchAll(db) + XCTAssertEqual(ids, [1]) + } + } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index cd2b83829..2216058f9 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -375,7 +375,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } } - + // MARK: - Fetch With Key Request @@ -661,7 +661,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { _ = try MinimalSingle.find(db, key: id) XCTFail("Expected RecordError") } catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["UUID": .null]) { } - + do { let fetchedRecord = try MinimalSingle.find(db, key: record.UUID) XCTAssertTrue(fetchedRecord.UUID == record.UUID) @@ -680,7 +680,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -861,7 +861,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } // MARK: Select PrimaryKey - + func test_static_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -875,6 +875,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } + func test_static_selectID() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalSingle() + record.UUID = "theUUID" + try record.insert(db) + let ids: [String] = try MinimalSingle.selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } + func test_request_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -887,4 +898,15 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(rows, [["UUID": "theUUID"]]) } } + + func test_request_selectID() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = MinimalSingle() + record.UUID = "theUUID" + try record.insert(db) + let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db) + XCTAssertEqual(ids, ["theUUID"]) + } + } } diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index a41b80b03..3cb56acd4 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -133,6 +133,8 @@ 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) } do { @@ -148,6 +150,8 @@ 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) } } }