mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
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:
1 parent
a9fcf1b9c1
commit
7ffc332327
13 files changed
+138
-92
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Player> {
|
||||
func selectID() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey()
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -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<Int64> {
|
||||
select(Author.Columns.id)
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
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
|
||||
|
||||
@@ -52,12 +52,30 @@ typealias FastNullableDatabaseValueCursor<T: DatabaseValueConvertible & Statemen
|
||||
@available(*, unavailable, message: "NullableDatabaseValueCursor<T> has been replaced with DatabaseValueCursor<T?>")
|
||||
typealias NullableDatabaseValueCursor<T: DatabaseValueConvertible> = DatabaseValueCursor<T?>
|
||||
|
||||
@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<RowDecoder.ID> { 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<RowDecoder.ID> { 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<ID> { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, renamed: "Statement")
|
||||
public typealias UpdateStatement = Statement
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -393,14 +393,28 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv
|
||||
public func filter(ids: some Collection<RowDecoder.ID>) -> QueryInterfaceRequest<RowDecoder> {
|
||||
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<RowDecoder.ID> {
|
||||
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<PrimaryKey>(as type: PrimaryKey.Type = PrimaryKey.self)
|
||||
-> QueryInterfaceRequest<PrimaryKey>
|
||||
{
|
||||
all().selectPrimaryKey(as: type)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<PrimaryKey>(as type: PrimaryKey.Type = PrimaryKey.self)
|
||||
-> QueryInterfaceRequest<PrimaryKey>
|
||||
{
|
||||
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<ID>) -> QueryInterfaceRequest<Self> {
|
||||
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<ID> {
|
||||
all().selectID()
|
||||
}
|
||||
}
|
||||
@@ -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] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.select(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.select(..., as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.selectID()` | [TableRecord] & Identifiable | [*](#identifiable-records) |
|
||||
| `Type.selectPrimaryKey(as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.annotated(with:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.filter(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `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<Int64>
|
||||
|
||||
// SELECT code FROM country
|
||||
Country.selectPrimaryKey(as: String.self) // QueryInterfaceRequest<String>
|
||||
|
||||
// SELECT citizenId, countryCode FROM citizenship
|
||||
Citizenship.selectPrimaryKey(as: Row.self) // QueryInterfaceRequest<Row>
|
||||
```
|
||||
|
||||
- `orderByPrimaryKey()` sorts by primary key.
|
||||
|
||||
```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"]])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"]])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user