This reverts 7ffc332327

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<Int64?>
>
> This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, 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:).
This commit is contained in:
Gwendal Roué committed 2025-02-11 20:47:49 +01:00
1 parent ea6d8e0123
commit 87b236dfe0
10 files changed
+140 -11

No files matched your search

@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
// Selects authors' name
func selectName() -> QueryInterfaceRequest<String> {
select(Author.Columns.name)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
// The names of Japanese authors
let names: Set<String> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.selectName()
.fetchSet(db)
```
@@ -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<RowDecoder.ID>
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
+17
View File
@@ -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>("player")
///
/// // SELECT id FROM player
/// let request = try table.selectID()
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// table columns.
///
@@ -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<Self.ID>
where Self: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// record selection.
///
+1
View File
@@ -98,6 +98,7 @@ import Foundation
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
+10
View File
@@ -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
@@ -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"])
}
}
}
@@ -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])
}
}
}
@@ -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"])
}
}
}
+4
View File
@@ -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)
}
}
}