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<Int64?>

This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.

Instead, we introduce selectPrimaryKey(as:), which allows the user to provide the desired type.

    Player.selectPrimaryKey(as: Int64.self) // QueryInterface<Int64>
This commit is contained in:
Gwendal Roué committed 2022-08-21 21:22:34 +02:00
1 parent a9fcf1b9c1
commit 7ffc332327
13 files changed
+138 -92

No files matched your search

@@ -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<PrimaryKey>(as type: PrimaryKey.Type = PrimaryKey.self)
-> QueryInterfaceRequest<PrimaryKey>
{
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<RowDecoder.ID> {
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.