Record types with an auto-incremented id should avoid the Identifiable protocol.

This commit is contained in:
Gwendal Roué committed 2023-10-04 22:02:18 +02:00
1 parent cbcc057222
commit 0eb973b6db
5 files changed
+50 -15

No files matched your search

+2 -1
View File
@@ -119,10 +119,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/v6.18.0/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
@@ -165,11 +165,6 @@ struct Player: Codable {
var score: Int
}
extension Player: Identifiable {
// Required because the primary key column is not 'id'
var id: Int64? { rowid }
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
@@ -61,16 +61,16 @@ Thanks to this database schema, the application will always process *consistent
**Define one record type per database table.** This record type will be responsible for writing in this table.
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
**Let's start from regular structs** whose properties match the columns in their database table. They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
```swift
struct Author: Codable, Identifiable {
struct Author: Codable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable, Identifiable {
struct Book: Codable {
var id: Int64?
var authorId: Int64
var title: String
@@ -129,7 +129,7 @@ let books = try dbQueue.read { db in
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable, Identifiable {
> struct Author: Codable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
@@ -150,6 +150,25 @@ let books = try dbQueue.read { db in
> try Author.find(db, id: authorID)
> }
> ```
>
> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
>
> ```swift
> struct Player: Codable {
> var id: Int64? // Optional ids are not suitable for Identifiable
> var name: String
> var score: Int
> }
>
> extension Player: FetchableRecord, MutablePersistableRecord {
> // Update auto-incremented id upon successful insertion
> mutating func didInsert(_ inserted: InsertionSuccess) {
> id = inserted.rowID
> }
> }
> ```
>
> For more details about auto-incremented ids and `Identifiable`, see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
### Record Types Hide Intimate Database Details
+4 -4
View File
@@ -25,7 +25,7 @@ try db.create(table: "player") { t in
t.column("score", .integer).notNull()
}
struct Player: Identifiable {
struct Player {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
@@ -156,7 +156,7 @@ When you fetch timestamped records from the database, it may be inconvenient to
```swift
let player = try dbQueue.read { db
try Player.find(db, id: 1)
try Player.find(db, key: 1)
}
player.creationDate // optional 😕
player.modificationDate // optional 😕
@@ -166,7 +166,7 @@ A possible technique is to define two record types: one that deals with players
```swift
/// `Player` deals with unsaved players
struct Player: Identifiable {
struct Player {
var id: Int64? // optional
var creationDate: Date? // optional
var modificationDate: Date? // optional
@@ -244,7 +244,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
```swift
// The base Player type
struct Player: Identifiable {
struct Player {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
+21 -1
View File
@@ -2502,7 +2502,7 @@ try Player.deleteAll(db, ids: [1, 2, 3])
> **Note**: `Identifiable` is not available on all application targets, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments:
>
> ```swift
> // Those methods are not type-checked
> // Available on non-Identifiable types
> try Player.fetchOne(db, key: 1)
> try Player.fetchOne(db, key: ["email": "arthur@example.com"])
> try Country.fetchAll(db, keys: ["FR", "US"])
@@ -2515,6 +2515,26 @@ try Player.deleteAll(db, ids: [1, 2, 3])
> try Player.deleteAll(db, keys: [1, 2, 3])
> ```
> **Note**: It is not recommended to use `Identifiable` on record types that use an auto-incremented primary key:
>
> ```swift
> // AVOID declaring Identifiable conformance when key is auto-incremented
> struct Player {
> var id: Int64? // Not an id suitable for Identifiable
> var name: String
> var score: Int
> }
>
> extension Player: FetchableRecord, MutablePersistableRecord {
> // Update auto-incremented id upon successful insertion
> mutating func didInsert(_ inserted: InsertionSuccess) {
> id = inserted.rowID
> }
> }
> ```
>
> For a detailed rationale, please see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
Some database tables have a single-column primary key which is not called "id":
```swift