BREAKING: persistence callbacks, and support for RETURNING

- Replace performInsert, performUpdate, etc with callbacks: willInsert, aroundInsert, didInsert, etc.
- Always call didInsert, even with INSERT OR IGNORE
- Explicit conflict resolution in persistence methods
- Add ...AndFetch... methods
This commit is contained in:
Gwendal Roué committed 2022-08-21 21:22:34 +02:00
1 parent 0ed9367b26
commit a702fe6bc9
50 files changed
+6819 -1667

No files matched your search

+4
View File
@@ -107,10 +107,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
- **Breaking**: The `DatabaseRegionObservation.extent` property was removed.
- **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`.
- **Breaking**: Record types can no longer override persistence methods. You use persistence callbacks instead.
- **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).
- **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`.
- **New**: `ValueObservation.map` now accepts a throwing closure argument.
- **New**: Value requests now throw an error when they find unexpected database values (they used to crash in GRDB 5).
- **New**: Persistence callbacks allow record types to customize persistence methods.
- **New**: All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc.
- **New**: Support for the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html) (available from iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a custom SQLite build): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc.
## 5.26.0
@@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -59,8 +59,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
+128
View File
@@ -110,7 +110,135 @@ The record protocols have been refactored. We tried to keep the amount of modifi
</details>
- **The signature of the `didInsert` method has changed**.
You have to update all the `didInsert` methods in your application:
```diff
struct Player: MutablePersistableRecord {
var id: Int64?
// Update auto-incremented id upon successful insertion
- mutating func didInsert(with rowID: Int64, for column: String?) {
- id = rowID
+ mutating func didInsert(_ inserted: InsertionSuccess) {
+ id = inserted.rowID
}
}
```
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
```diff
class Player: Record {
var id: Int64?
// Update auto-incremented id upon successful insertion
- override func didInsert(with rowID: Int64, for column: String?) {
- id = rowID
+ override func didInsert(_ inserted: InsertionSuccess) {
+ super.didInsert(inserted)
+ id = inserted.rowID
}
}
```
- **PersistableRecord types now customize persistence methods with "persistence callbacks"**.
It is no longer possible to override persistence methods such as `insert` or `update`. Customizing the persistence methods is now possible with callbacks such as `willSave`, `willInsert`, or `didDelete` (see [Persistence Callbacks](../README.md#persistence-callbacks) for the full list of callbacks).
For example, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
```swift
// GRDB 5
struct Link: PersistableRecord {
var url: URL
func insert(_ db: Database) throws {
try validate()
try performInsert(db)
}
func update(_ db: Database, columns: Set<String>) throws {
try validate()
try performUpdate(db, columns: columns)
}
func validate() throws {
if url.host == nil {
throw ValidationError("url must be absolute.")
}
}
}
```
With GRDB 6, record validation can be implemented with the `willSave` callback:
```swift
// GRDB 6
struct Link: PersistableRecord {
var url: URL
func willSave(_ db: Database) throws {
if url.host == nil {
throw ValidationError("url must be absolute.")
}
}
}
try link.insert(db) // Calls the willSave callback
try link.update(db) // Calls the willSave callback
try link.save(db) // Calls the willSave callback
try link.upsert(db) // Calls the willSave callback
```
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
```swift
// GRDB 6
class Link: Record {
var url: URL
override func willSave(_ db: Database) throws {
try super.willSave(db)
if url.host == nil {
throw ValidationError("url must be absolute.")
}
}
}
```
- **Handling of the `IGNORE` conflict policy**
The SQLite [IGNORE](https://www.sqlite.org/lang_conflict.html) conflict policy has SQLite skip insertions and updates that violate a schema constraint, without reporting any error. You can skip this paragraph if you do not use this policy.
GRDB 6 has slightly changed the handling of the `IGNORE` policy.
The `didInsert` callback is now always called on `INSERT OR IGNORE` insertions. In GRDB 5, `didInsert` was not called for record types that specify the `.ignore` conflict policy on inserts:
```swift
// Given a record with ignore conflict policy for inserts...
struct Player: TableRecord, FetchableRecord {
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .ignore)
}
// GRDB 5: Does not call didInsert
// GRDB 6: Calls didInsert
try player.insert(db)
```
Since `INSERT OR IGNORE` may silently fail, the `didInsert` method will be called with some random rowid in case of failed insert. You can detect failed insertions with the new method `insertAndFetch`:
```swift
// How to detect failed `INSERT OR IGNORE`:
// INSERT OR IGNORE INTO player ... RETURNING *
if let insertedPlayer = try player.insertAndFetch(db) {
// Succesful insertion
} else {
// Ignored failure
}
```
## Other Changes
- The initializer of in-memory databases can now throw errors:
@@ -109,29 +109,33 @@ struct Book: Codable, Identifiable {
var authorId: Int64
var title: String
}
```
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information.
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
>
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method:
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method:
>
> ```swift
> try dbQueue.write { db in
@@ -234,7 +238,7 @@ Let's look at three examples:
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database.
## Singleton Records
@@ -44,8 +44,8 @@ struct Author: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64?
var name: String
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -54,8 +54,8 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord {
var authorId: Int64
var title: String
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -13,8 +13,8 @@ struct Player: Codable, FetchableRecord, MutablePersistableRecord {
var name: String
var score: Int
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -100,8 +100,8 @@ extension Place : MutablePersistableRecord {
container["longitude"] = coordinate.longitude
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
+90 -10
View File
@@ -70,8 +70,8 @@
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; };
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
560D92481C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
@@ -397,7 +397,7 @@
565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
565490E11D5AE252005622CB /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
@@ -791,6 +791,38 @@
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
56D110C028AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
56D110C128AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
56D110C228AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
56D110C528AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
56D110C628AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
56D110C728AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
56D110CA28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
56D110CC28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
56D110CF28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
56D110D028AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
56D110D128AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
56D110D328AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
56D110D428AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
56D110D528AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
56D110D628AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
56D110D928AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
56D110DA28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
56D110DB28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
56D110DE28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
56D110DF28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
56D110E028AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
56D110FB28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
56D110FC28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
56D110FD28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
@@ -1037,7 +1069,7 @@
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; };
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
AAA4DCDF230F1E0600C74B15 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
@@ -1314,7 +1346,7 @@
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = "<group>"; };
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = "<group>"; };
560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = "<group>"; };
5611620725757583007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = "<group>"; };
5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
@@ -1627,6 +1659,14 @@
56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = "<group>"; };
56CEB5401EAA359A00BFAF62 /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = "<group>"; };
56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = "<group>"; };
56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = "<group>"; };
56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = "<group>"; };
56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = "<group>"; };
56D110D228AFC81400E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = "<group>"; };
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = "<group>"; };
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
@@ -2405,7 +2445,15 @@
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */,
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */,
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */,
560D92441C672C4B00F4F92B /* PersistableRecord.swift */,
560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */,
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */,
56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */,
56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */,
56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */,
56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */,
56D110D228AFC81400E64463 /* PersistableRecord.swift */,
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */,
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
560D92461C672C4B00F4F92B /* TableRecord.swift */,
);
@@ -2935,6 +2983,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56D110DF28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
56256ED225D1ACD0008C2BDD /* Table.swift in Sources */,
56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
@@ -2951,6 +3000,7 @@
565490E21D5AE252005622CB /* Record.swift in Sources */,
565490C11D5AE236005622CB /* FetchRequest.swift in Sources */,
568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */,
56D110D028AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
@@ -2958,8 +3008,10 @@
5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
56D110C128AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */,
56D110D528AFC81400E64463 /* PersistableRecord.swift in Sources */,
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
56894FD12606589C00268F4D /* Decimal.swift in Sources */,
@@ -3010,6 +3062,7 @@
56DDDDF6242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
5659F49E1EA8D989004A4992 /* Pool.swift in Sources */,
5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
56D110DA28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */,
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */,
@@ -3037,10 +3090,11 @@
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
565490D41D5AE252005622CB /* (null) in Sources */,
56D110FC28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
565490E11D5AE252005622CB /* MutablePersistableRecord.swift in Sources */,
569BBA50229170FA00478429 /* Inflections+English.swift in Sources */,
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
@@ -3048,6 +3102,7 @@
56F5ABDC1D814330001F60CB /* URL.swift in Sources */,
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
5695962B222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */,
56D110C628AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
565490D31D5AE252005622CB /* (null) in Sources */,
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56AACAAA22ACED7100A40F2A /* Fetch.swift in Sources */,
@@ -3070,6 +3125,7 @@
565490CD1D5AE252005622CB /* Date.swift in Sources */,
5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */,
56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -3111,6 +3167,7 @@
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */,
56256ED125D1ACD0008C2BDD /* Table.swift in Sources */,
5653EB0A20944C7C00F46237 /* Association.swift in Sources */,
56D110FB28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
56A2387E1B9C75030082EB20 /* Database.swift in Sources */,
56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */,
@@ -3118,11 +3175,13 @@
5605F1641C672E4000235C62 /* Date.swift in Sources */,
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
56D110D928AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */,
56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */,
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
56D110CF28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
5659F49B1EA8D989004A4992 /* Pool.swift in Sources */,
5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */,
563082E52430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
@@ -3142,6 +3201,7 @@
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
56D110DE28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
56A8C2331D1914540096E9D4 /* UUID.swift in Sources */,
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
56A238A51B9C753B0082EB20 /* Record.swift in Sources */,
@@ -3159,10 +3219,12 @@
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */,
5657AB121D10899D006283EF /* URL.swift in Sources */,
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
56D110CA28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */,
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */,
56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */,
560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */,
56D110D428AFC81400E64463 /* PersistableRecord.swift in Sources */,
56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */,
5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
@@ -3180,6 +3242,7 @@
5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
5695962A222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */,
563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */,
56D110C528AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
5605F1661C672E4000235C62 /* NSNull.swift in Sources */,
5656A8AE2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
@@ -3206,9 +3269,10 @@
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
56D110C028AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */,
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
560D92481C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
@@ -3719,6 +3783,7 @@
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */,
56256ED325D1ACD0008C2BDD /* Table.swift in Sources */,
AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */,
56D110FD28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */,
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */,
AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */,
@@ -3726,11 +3791,13 @@
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */,
56D110DB28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */,
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */,
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */,
AAA4DC8E230F1E0600C74B15 /* SQLFunctions.swift in Sources */,
56D110D128AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
AAA4DC8F230F1E0600C74B15 /* Pool.swift in Sources */,
AAA4DC90230F1E0600C74B15 /* HasOneAssociation.swift in Sources */,
563082E72430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
@@ -3750,6 +3817,7 @@
AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */,
AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */,
AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */,
56D110E028AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */,
AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */,
AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */,
@@ -3767,10 +3835,12 @@
AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */,
AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */,
AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */,
56D110CC28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
AAA4DCAF230F1E0600C74B15 /* Utils.swift in Sources */,
AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */,
AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */,
AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */,
56D110D628AFC81400E64463 /* PersistableRecord.swift in Sources */,
56256EDC25D1B316008C2BDD /* ForeignKey.swift in Sources */,
AAA4DCB3230F1E0600C74B15 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */,
@@ -3788,6 +3858,7 @@
AAA4DCC4230F1E0600C74B15 /* DatabaseDateComponents.swift in Sources */,
AAA4DCC5230F1E0600C74B15 /* HasManyThroughAssociation.swift in Sources */,
AAA4DCC6230F1E0600C74B15 /* DatabaseReader.swift in Sources */,
56D110C728AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
AAA4DCC8230F1E0600C74B15 /* FTS5Pattern.swift in Sources */,
AAA4DCC9230F1E0600C74B15 /* NSNull.swift in Sources */,
AAA4DCCA230F1E0600C74B15 /* TableRecord+Association.swift in Sources */,
@@ -3814,9 +3885,10 @@
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
56D110C228AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */,
566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */,
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */,
AAA4DCDF230F1E0600C74B15 /* MutablePersistableRecord.swift in Sources */,
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */,
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */,
56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
@@ -4092,6 +4164,7 @@
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */,
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */,
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
@@ -4099,11 +4172,13 @@
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */,
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */,
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */,
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
@@ -4123,6 +4198,7 @@
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
@@ -4140,10 +4216,12 @@
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
56D110D328AFC81400E64463 /* PersistableRecord.swift in Sources */,
5653EB0920944C7C00F46237 /* Association.swift in Sources */,
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
@@ -4161,6 +4239,7 @@
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */,
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
@@ -4187,6 +4266,7 @@
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
@@ -4199,7 +4279,7 @@
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */,
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */,
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
+28
View File
@@ -67,9 +67,37 @@ extension DatabaseUUIDEncodingStrategy {
@available(*, unavailable, message: "FastNullableDatabaseValueCursor<T> has been replaced with FastDatabaseValueCursor<T?>")
typealias FastNullableDatabaseValueCursor<T: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<T?>
extension MutablePersistableRecord {
@available(*, unavailable, message: "Use persistence callbacks instead.")
public mutating func performInsert(_ db: Database) throws { preconditionFailure() }
@available(*, unavailable, message: "Use persistence callbacks instead.")
public func performUpdate(_ db: Database, columns: Set<String>) throws { preconditionFailure() }
@available(*, unavailable, message: "Use persistence callbacks instead.")
public mutating func performSave(_ db: Database) throws { preconditionFailure() }
@available(*, unavailable, message: "Use persistence callbacks instead.")
public func performDelete(_ db: Database) throws -> Bool { preconditionFailure() }
@available(*, unavailable, message: "performExists(_:) was removed without any replacement.")
public func performExists(_ db: Database) throws -> Bool { preconditionFailure() }
@available(*, unavailable, renamed: "updateChanges(_:modify:)")
public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { preconditionFailure() }
}
@available(*, unavailable, message: "NullableDatabaseValueCursor<T> has been replaced with DatabaseValueCursor<T?>")
typealias NullableDatabaseValueCursor<T: DatabaseValueConvertible> = DatabaseValueCursor<T?>
extension PersistableRecord {
@available(*, unavailable, message: "Use persistence callbacks instead.")
public func performInsert(_ db: Database) throws { preconditionFailure() }
@available(*, unavailable, message: "Use persistence callbacks instead.")
public func performSave(_ db: Database) throws { preconditionFailure() }
}
@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.")
@@ -410,18 +410,231 @@ extension QueryInterfaceRequest {
// MARK: - Batch Delete
extension QueryInterfaceRequest {
/// Deletes matching rows; returns the number of deleted rows.
/// Deletes matching rows, and returns the number of deleted rows.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute()
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
try statement.execute()
return db.changesCount
}
}
// MARK: - Batch Delete and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE
/// Returns a `DELETE ... RETURNING ...` prepared statement.
///
/// For example:
///
/// // Delete all players and return their names
/// // DELETE FROM player RETURNING name
/// let request = Player.all()
/// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")])
/// let deletedNames = try String.fetchSet(statement)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
/// - returns: A prepared statement.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
/// Returns a cursor over a `DELETE ... RETURNING ...` statement.
///
/// For example:
///
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let cursor = try request.deleteAndFetchCursor(db)
/// let deletedPlayers = try Array(cursor) // [Player]
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - returns: A cursor over the deleted records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func deleteAndFetchCursor(_ db: Database)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
let statement = try deleteAndFetchStatement(db, selection: RowDecoder.databaseSelection)
return try RowDecoder.fetchCursor(statement)
}
/// Executes a `DELETE ... RETURNING ...` statement and returns the
/// deleted records.
///
/// For example:
///
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let deletedPlayers = try request.deleteAndFetchAll(db)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func deleteAndFetchAll(_ db: Database)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try Array(deleteAndFetchCursor(db))
}
/// Executes a `DELETE ... RETURNING ...` statement and returns the
/// deleted records.
///
/// For example:
///
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let deletedPlayers = try request.deleteAndFetchSet(db)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func deleteAndFetchSet(_ db: Database)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try Set(deleteAndFetchCursor(db))
}
#else
/// Returns a `DELETE ... RETURNING ...` prepared statement.
///
/// For example:
///
/// // Delete all players and return their names
/// // DELETE FROM player RETURNING name
/// let request = Player.all()
/// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")])
/// let deletedNames = try String.fetchSet(statement)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
/// - returns: A prepared statement.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
/// Returns a cursor over a `DELETE ... RETURNING ...` statement.
///
/// For example:
///
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let cursor = try request.deleteAndFetchCursor(db)
/// let deletedPlayers = try Array(cursor) // [Player]
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - returns: A cursor over the deleted records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func deleteAndFetchCursor(_ db: Database)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
let statement = try deleteAndFetchStatement(db, selection: RowDecoder.databaseSelection)
return try RowDecoder.fetchCursor(statement)
}
/// Executes a `DELETE ... RETURNING ...` statement and returns the
/// deleted records.
///
/// For example:
///
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let deletedPlayers = try request.deleteAndFetchAll(db)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func deleteAndFetchAll(_ db: Database)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try Array(deleteAndFetchCursor(db))
}
/// Executes a `DELETE ... RETURNING ...` statement and returns the
/// deleted records.
///
/// For example:
///
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let deletedPlayers = try request.deleteAndFetchSet(db)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func deleteAndFetchSet(_ db: Database)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try Set(deleteAndFetchCursor(db))
}
#endif
}
// MARK: - Batch Update
extension QueryInterfaceRequest {
@@ -438,13 +651,14 @@ extension QueryInterfaceRequest {
}
}
/// Updates matching rows; returns the number of updated rows.
/// Updates matching rows, and returns the number of updated rows.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.all().updateAll(db, [Column("score").set(to: 0)])
/// let request = Player.all()
/// try request.updateAll(db, [Column("score").set(to: 0)])
/// }
///
/// - parameter db: A database connection.
@@ -460,9 +674,9 @@ extension QueryInterfaceRequest {
{
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments) else
db,
conflictResolution: conflictResolution,
assignments: assignments) else
{
// database not hit
return 0
@@ -471,33 +685,324 @@ extension QueryInterfaceRequest {
return db.changesCount
}
/// Updates matching rows; returns the number of updated rows.
/// Updates matching rows, and returns the number of updated rows.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.all().updateAll(db, Column("score").set(to: 0))
/// let request = Player.all()
/// try request.updateAll(db, Column("score").set(to: 0))
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignment: A column assignment.
/// - parameter otherAssignments: Eventual other column assignments.
/// - parameter assignments: Column assignments.
/// - returns: The number of updated rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignment: ColumnAssignment,
_ otherAssignments: ColumnAssignment...)
_ assignments: ColumnAssignment...)
throws -> Int
{
try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
try updateAll(db, onConflict: conflictResolution, assignments)
}
}
// MARK: - Batch Update and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE
/// Returns an `UPDATE ... RETURNING ...` prepared statement.
///
/// For example:
///
/// // Fetch all updated scores
/// // UPDATE player SET score = score + 10 RETURNING score
/// let request = Player.all()
/// let statement = try request.updateAndFetchStatement(
/// db, [Column("score") += 10],
/// select: [Column("score")])
/// let updatedScores = try Int.fetchAll(statement)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments
/// (must not be empty).
/// - parameter selection: The returned columns (must not be empty).
/// - returns: A prepared statement.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `selection` and `assignments` are not empty.
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments,
selection: selection)
else {
fatalError("Invalid empty assignments")
}
return updateStatement
}
/// Returns a cursor over an `UPDATE ... RETURNING ...` statement.
///
/// For example:
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let cursor = try request.updateAndFetchCursor(db, [Column("score") += 10])
/// let updatedPlayers = try Array(cursor) // [Player]
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: A cursor over the updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
let statement = try updateAndFetchStatement(
db,
onConflict: conflictResolution,
assignments,
selection: RowDecoder.databaseSelection)
return try RowDecoder.fetchCursor(statement)
}
/// Execute an `UPDATE ... RETURNING ...` statement and returns the
/// updated records.
///
/// For example:
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10])
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: An array of updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
/// Execute an `UPDATE ... RETURNING ...` statement and returns the
/// updated records.
///
/// For example:
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10])
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: A set of updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
#else
/// Returns an `UPDATE ... RETURNING ...` prepared statement.
///
/// For example:
///
/// // Fetch all updated scores
/// // UPDATE player SET score = score + 10 RETURNING score
/// let request = Player.all()
/// let statement = try request.updateAndFetchStatement(
/// db, [Column("score") += 10],
/// select: [Column("score")])
/// let updatedScores = try Int.fetchAll(statement)
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments
/// (must not be empty).
/// - parameter selection: The returned columns (must not be empty).
/// - returns: A prepared statement.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `selection` and `assignments` are not empty.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments,
selection: selection)
else {
fatalError("Invalid empty assignments")
}
return updateStatement
}
/// Returns a cursor over an `UPDATE ... RETURNING ...` statement.
///
/// For example:
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let cursor = try request.updateAndFetchCursor(db, [Column("score") += 10])
/// let updatedPlayers = try Array(cursor) // [Player]
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: A cursor over the updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
let statement = try updateAndFetchStatement(
db,
onConflict: conflictResolution,
assignments,
selection: RowDecoder.databaseSelection)
return try RowDecoder.fetchCursor(statement)
}
/// Execute an `UPDATE ... RETURNING ...` statement and returns the
/// updated records.
///
/// For example:
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10])
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: An array of updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
/// Execute an `UPDATE ... RETURNING ...` statement and returns the
/// updated records.
///
/// For example:
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10])
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: A set of updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
#endif
}
// MARK: - ColumnAssignment
/// A ColumnAssignment can update rows in the database.
+14 -14
View File
@@ -1139,7 +1139,7 @@ extension Table {
// MARK: - Batch Delete
extension Table {
/// Deletes all rows; returns the number of deleted rows.
/// Deletes all rows, and returns the number of deleted rows.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
@@ -1220,7 +1220,7 @@ extension Table {
// MARK: - Deleting by Single-Column Primary Key
extension Table {
/// Delete rows identified by their primary keys; returns the number of
/// Delete rows identified by their primary keys, and returns the number of
/// deleted rows.
///
/// // DELETE FROM player WHERE id IN (1, 2, 3)
@@ -1251,7 +1251,7 @@ extension Table {
return try filter(keys: keys).deleteAll(db)
}
/// Delete a row, identified by its primary key; returns whether a
/// Delete a row, identified by its primary key, and returns whether a
/// database row was deleted.
///
/// // DELETE FROM player WHERE id = 123
@@ -1285,7 +1285,7 @@ extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
{
/// Delete rows identified by their primary keys; returns the number of
/// Delete rows identified by their primary keys, and returns the number of
/// deleted rows.
///
/// // DELETE FROM player WHERE id IN (1, 2, 3)
@@ -1313,7 +1313,7 @@ where RowDecoder: Identifiable,
return try filter(ids: ids).deleteAll(db)
}
/// Delete a row, identified by its primary key; returns whether a
/// Delete a row, identified by its primary key, and returns whether a
/// database row was deleted.
///
/// // DELETE FROM player WHERE id = 123
@@ -1346,7 +1346,8 @@ where RowDecoder: Identifiable,
extension Table {
/// Delete rows identified by the provided unique keys (primary key or
/// any key with a unique index on it); returns the number of deleted rows.
/// any key with a unique index on it), and returns the number of
/// deleted rows.
///
/// try Table("player").deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
///
@@ -1364,7 +1365,8 @@ extension Table {
}
/// Delete a row, identified by a unique key (the primary key or any key
/// with a unique index on it); returns whether a database row was deleted.
/// with a unique index on it), and returns whether a database row
/// was deleted.
///
/// Table("player").deleteOne(db, key: ["name": Arthur"])
///
@@ -1381,7 +1383,7 @@ extension Table {
// MARK: - Batch Update
extension Table {
/// Updates all rows; returns the number of updated rows.
/// Updates all rows, and returns the number of updated rows..
///
/// For example:
///
@@ -1405,7 +1407,7 @@ extension Table {
try all().updateAll(db, onConflict: conflictResolution, assignments)
}
/// Updates all rows; returns the number of updated rows.
/// Updates all rows, and returns the number of updated rows..
///
/// For example:
///
@@ -1416,18 +1418,16 @@ extension Table {
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignment: A column assignment.
/// - parameter otherAssignments: Eventual other column assignments.
/// - parameter assignments: Column assignments.
/// - returns: The number of updated rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignment: ColumnAssignment,
_ otherAssignments: ColumnAssignment...)
_ assignments: ColumnAssignment...)
throws -> Int
{
try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
try updateAll(db, onConflict: conflictResolution, assignments)
}
}
@@ -205,11 +205,13 @@ struct SQLQueryGenerator: Refinable {
return false
}
func makeDeleteStatement(_ db: Database) throws -> Statement {
/// Returns a `DELETE` statement, with `RETURNING` clause if `selection`
/// is not empty.
func makeDeleteStatement(_ db: Database, selection: [any SQLSelectable] = []) throws -> Statement {
switch try grouping(db) {
case .none:
guard relation.joins.isEmpty else {
return try makeTrivialDeleteStatement(db)
return try makeTrivialDeleteStatement(db, selection: selection)
}
let context = SQLGenerationContext(db, aliases: relation.allAliases, ctes: relation.ctes)
@@ -233,12 +235,10 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
let statement = try db.makeStatement(sql: sql)
statement.arguments = context.arguments
return statement
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
case .unique:
return try makeTrivialDeleteStatement(db)
return try makeTrivialDeleteStatement(db, selection: selection)
case .nonUnique:
// Programmer error
@@ -247,7 +247,8 @@ struct SQLQueryGenerator: Refinable {
}
/// DELETE FROM table WHERE id IN (SELECT id FROM table ...)
private func makeTrivialDeleteStatement(_ db: Database) throws -> Statement {
/// DELETE FROM table WHERE id IN (SELECT id FROM table ...) RETURNING ...
private func makeTrivialDeleteStatement(_ db: Database, selection: [any SQLSelectable]) throws -> Statement {
let tableName = relation.source.tableName
let alias = TableAlias(tableName: tableName)
let context = SQLGenerationContext(db, aliases: [alias])
@@ -263,16 +264,18 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
let statement = try db.makeStatement(sql: sql)
statement.arguments = context.arguments
return statement
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
}
/// Returns nil if assignments is empty
/// Returns an `UPDATE` statement, with `RETURNING` clause if `selection`
/// is not empty.
///
/// Returns nil if assignments is empty.
func makeUpdateStatement(
_ db: Database,
conflictResolution: Database.ConflictResolution,
assignments: [ColumnAssignment])
assignments: [ColumnAssignment],
selection: [any SQLSelectable] = [])
throws -> Statement?
{
switch try grouping(db) {
@@ -281,7 +284,8 @@ struct SQLQueryGenerator: Refinable {
return try makeTrivialUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments)
assignments: assignments,
selection: selection)
}
// Check for empty assignments after all programmer errors have
@@ -322,12 +326,14 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
let statement = try db.makeStatement(sql: sql)
statement.arguments = context.arguments
return statement
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
case .unique:
return try makeTrivialUpdateStatement(db, conflictResolution: conflictResolution, assignments: assignments)
return try makeTrivialUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments,
selection: selection)
case .nonUnique:
// Programmer error
@@ -336,11 +342,13 @@ struct SQLQueryGenerator: Refinable {
}
/// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...)
/// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...) RETURNING ...
/// Returns nil if assignments is empty
private func makeTrivialUpdateStatement(
_ db: Database,
conflictResolution: Database.ConflictResolution,
assignments: [ColumnAssignment])
assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement?
{
// Check for empty assignments after all programmer errors have
@@ -378,9 +386,35 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
let statement = try db.makeStatement(sql: sql)
statement.arguments = context.arguments
return statement
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
}
// Support for the RETURNING clause
private func makeStatement(
_ db: Database,
sql: String,
arguments: StatementArguments,
returning selection: [any SQLSelectable])
throws -> Statement
{
if selection.isEmpty {
let statement = try db.makeStatement(sql: sql)
statement.arguments = arguments
return statement
} else {
assert(sqlite3_libversion_number() >= 3035000)
let context = SQLGenerationContext(db)
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.makeStatement(sql: sql)
statement.arguments = arguments
return statement
}
}
private func commonTableExpressionsPrefix(_ context: SQLGenerationContext) throws -> String {
+11 -1
View File
@@ -220,7 +220,7 @@ public struct PersistenceContainer {
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
public subscript(_ column: String) -> (any DatabaseValueConvertible)? {
get { storage[column] ?? nil }
get { self[caseInsensitive: column] }
set { storage.updateValue(newValue, forKey: column) }
}
@@ -248,6 +248,15 @@ public struct PersistenceContainer {
record.encode(to: &self)
}
/// Convenience initializer from a database connection and a record
@usableFromInline
init(_ db: Database, _ record: some EncodableRecord & TableRecord) throws {
let databaseTableName = type(of: record).databaseTableName
let columnCount = try db.columns(in: databaseTableName).count
self.init(minimumCapacity: columnCount) // Optimization
record.encode(to: &self)
}
/// Columns stored in the container, ordered like values.
var columns: [String] { Array(storage.keys) }
@@ -300,6 +309,7 @@ public struct PersistenceContainer {
storage.makeIterator()
}
@usableFromInline
func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> {
var newValueIterator = makeIterator()
return AnyIterator {
@@ -0,0 +1,273 @@
/// DAO takes care of MutablePersistableRecord CRUD
final class DAO<Record: MutablePersistableRecord> {
/// The database
let db: Database
/// DAO keeps a copy the record's persistenceContainer, so that this
/// dictionary is built once whatever the database operation. It is
/// guaranteed to have at least one (key, value) pair.
let persistenceContainer: PersistenceContainer
/// The table name
let databaseTableName: String
/// The table primary key info
let primaryKey: PrimaryKeyInfo
init(_ db: Database, _ record: Record) throws {
self.db = db
databaseTableName = type(of: record).databaseTableName
primaryKey = try db.primaryKey(databaseTableName)
persistenceContainer = try PersistenceContainer(db, record)
GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container")
}
func insertStatement(
_ db: Database,
onConflict: Database.ConflictResolution,
returning selection: [any SQLSelectable])
throws -> Statement
{
let query = InsertQuery(
onConflict: onConflict,
tableName: databaseTableName,
insertedColumns: persistenceContainer.columns)
return try makeStatement(
sql: query.sql,
checkedArguments: StatementArguments(persistenceContainer.values),
returning: selection)
}
/// Returns nil if and only if primary key is nil
func updateStatement(
columns: Set<String>,
onConflict: Database.ConflictResolution,
returning selection: [any SQLSelectable])
throws -> Statement?
{
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
}
// Don't update columns not present in columns
// Don't update columns not present in the persistenceContainer
// Don't update primary key columns
let lowercaseUpdatedColumns = Set(columns.map { $0.lowercased() })
.intersection(persistenceContainer.columns.map { $0.lowercased() })
.subtracting(primaryKeyColumns.map { $0.lowercased() })
var updatedColumns: [String] = try db
.columns(in: databaseTableName)
.map(\.name)
.filter { lowercaseUpdatedColumns.contains($0.lowercased()) }
if updatedColumns.isEmpty {
// IMPLEMENTATION NOTE
//
// It is important to update something, so that
// TransactionObserver can observe a change even though this
// change is useless.
//
// The goal is to be able to write tests with minimal tables,
// including tables made of a single primary key column.
updatedColumns = primaryKeyColumns
}
let updatedValues = updatedColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
let query = UpdateQuery(
onConflict: onConflict,
tableName: databaseTableName,
updatedColumns: updatedColumns,
conditionColumns: primaryKeyColumns)
return try makeStatement(
sql: query.sql,
checkedArguments: StatementArguments(updatedValues + primaryKeyValues),
returning: selection)
}
/// Returns nil if and only if primary key is nil
func deleteStatement() throws -> Statement? {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
}
let query = DeleteQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedStatement(sql: query.sql)
statement.setUncheckedArguments(StatementArguments(primaryKeyValues))
return statement
}
/// Returns nil if and only if primary key is nil
func existsStatement() throws -> Statement? {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
}
let query = ExistsQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedStatement(sql: query.sql)
statement.setUncheckedArguments(StatementArguments(primaryKeyValues))
return statement
}
/// Throws a PersistenceError.recordNotFound error
func makeRecordNotFoundError() -> Error {
let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map {
($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null)
})
return PersistenceError.recordNotFound(
databaseTableName: databaseTableName,
key: key)
}
// Support for the RETURNING clause
private func makeStatement(
sql: String,
checkedArguments arguments: StatementArguments,
returning selection: [any SQLSelectable])
throws -> Statement
{
if selection.isEmpty {
let statement = try db.internalCachedStatement(sql: sql)
// We have built valid arguments: don't check
statement.setUncheckedArguments(arguments)
return statement
} else {
assert(sqlite3_libversion_number() >= 3035000)
let context = SQLGenerationContext(db)
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.internalCachedStatement(sql: sql)
statement.arguments = arguments
return statement
}
}
}
// MARK: - InsertQuery
private struct InsertQuery: Hashable {
let onConflict: Database.ConflictResolution
let tableName: String
let insertedColumns: [String]
}
extension InsertQuery {
@ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:]
var sql: String {
if let sql = Self.sqlCache[self] {
return sql
}
let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")
let valuesSQL = databaseQuestionMarks(count: insertedColumns.count)
let sql: String
switch onConflict {
case .abort:
sql = """
INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \
VALUES (\(valuesSQL))
"""
default:
sql = """
INSERT OR \(onConflict.rawValue) \
INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \
VALUES (\(valuesSQL))
"""
}
Self.sqlCache[self] = sql
return sql
}
}
// MARK: - UpdateQuery
private struct UpdateQuery: Hashable {
let onConflict: Database.ConflictResolution
let tableName: String
let updatedColumns: [String]
let conditionColumns: [String]
}
extension UpdateQuery {
@ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:]
var sql: String {
if let sql = Self.sqlCache[self] {
return sql
}
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ")
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
let sql: String
switch onConflict {
case .abort:
sql = """
UPDATE \(tableName.quotedDatabaseIdentifier) \
SET \(updateSQL) \
WHERE \(whereSQL)
"""
default:
sql = """
UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \
SET \(updateSQL) \
WHERE \(whereSQL)
"""
}
Self.sqlCache[self] = sql
return sql
}
}
// MARK: - DeleteQuery
private struct DeleteQuery {
let tableName: String
let conditionColumns: [String]
}
extension DeleteQuery {
var sql: String {
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)"
}
}
// MARK: - ExistsQuery
private struct ExistsQuery {
let tableName: String
let conditionColumns: [String]
}
extension ExistsQuery {
var sql: String {
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
return "SELECT EXISTS (SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL))"
}
}
@@ -0,0 +1,56 @@
// MARK: - Delete Callbacks
extension MutablePersistableRecord {
@inline(__always)
@inlinable
public func willDelete(_ db: Database) throws { }
@inline(__always)
@inlinable
public func aroundDelete(_ db: Database, delete: () throws -> Bool) throws {
_ = try delete()
}
@inline(__always)
@inlinable
public func didDelete(deleted: Bool) { }
}
// MARK: - Delete
extension MutablePersistableRecord {
/// Executes a DELETE statement.
///
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
@inlinable // allow specialization so that empty callbacks are removed
public func delete(_ db: Database) throws -> Bool {
try willDelete(db)
var deleted = false
try aroundDelete(db) {
deleted = try deleteWithoutCallbacks(db)
return deleted
}
didDelete(deleted: deleted)
return deleted
}
}
// MARK: - Internals
extension MutablePersistableRecord {
/// Executes an `DELETE` statement, and DOES NOT run deletion callbacks.
@usableFromInline
func deleteWithoutCallbacks(_ db: Database) throws -> Bool {
guard let statement = try DAO(db, self).deleteStatement() else {
// Nil primary key
return false
}
try statement.execute()
return db.changesCount > 0
}
}
@@ -0,0 +1,473 @@
// MARK: - Insert Callbacks
extension MutablePersistableRecord {
@inline(__always)
@inlinable
public mutating func willInsert(_ db: Database) throws { }
@inline(__always)
@inlinable
public func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
_ = try insert()
}
@inline(__always)
@inlinable
public mutating func didInsert(_ inserted: InsertionSuccess) { }
}
// MARK: - Insert
extension MutablePersistableRecord {
/// Executes an `INSERT` statement.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insert(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws
{
try willSave(db)
var saved: PersistenceSuccess!
try aroundSave(db) {
let inserted = try insertWithCallbacks(db, onConflict: conflictResolution)
saved = PersistenceSuccess(inserted)
return saved
}
didSave(saved)
}
/// Executes an `INSERT` statement, and returns the inserted record.
///
/// Usage:
///
/// let player = Player(id: nil, name: "Arthur")
/// let insertedPlayer = try dbQueue.write { db in
/// try player.inserted(db)
/// }
/// print(player.id) // nil
/// print(insertedPlayer.id) // some id
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The inserted record.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func inserted(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self
{
var result = self
try result.insert(db, onConflict: conflictResolution)
return result
}
}
// MARK: - Insert and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE
/// Executes an `INSERT ... RETURNING ...` statement, and returns the
/// inserted record.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let insertedPlayer = player.insertAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT ... RETURNING ...` statement, and returns a new
/// record built from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a base player, get a full one
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Executes an `INSERT ... RETURNING ...` statement, and returns the
/// selected columns from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a base player, get the inserted score
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var inserted: InsertionSuccess!
var returned: T!
try aroundSave(db) {
(inserted, returned) = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(inserted)
}
didSave(PersistenceSuccess(inserted))
return returned
}
#else
/// Executes an `INSERT ... RETURNING ...` statement, and returns the
/// inserted record.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let insertedPlayer = player.insertAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT ... RETURNING ...` statement, and returns a new
/// record built from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a base player, get a full one
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Executes an `INSERT ... RETURNING ...` statement, and returns the
/// selected columns from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a base player, get the inserted score
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var inserted: InsertionSuccess!
var returned: T!
try aroundSave(db) {
(inserted, returned) = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(inserted)
}
didSave(PersistenceSuccess(inserted))
return returned
}
#endif
}
// MARK: - Internals
extension MutablePersistableRecord {
/// Executes an `INSERT` statement, and runs insertion callbacks.
@inlinable // allow specialization so that empty callbacks are removed
mutating func insertWithCallbacks(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?)
throws -> InsertionSuccess
{
let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) {
// Nothing to fetch
try $0.execute()
}
return inserted
}
/// Executes an `INSERT` statement, with `RETURNING` clause if `selection`
/// is not empty, and runs insertion callbacks.
@inlinable // allow specialization so that empty callbacks are removed
mutating func insertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (InsertionSuccess, T)
{
try willInsert(db)
var inserted: InsertionSuccess!
var returned: T!
try aroundInsert(db) {
(inserted, returned) = try insertAndFetchWithoutCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return inserted
}
didInsert(inserted)
return (inserted, returned)
}
/// Executes an `INSERT` statement, with `RETURNING` clause if `selection`
/// is not empty, and DOES NOT run insertion callbacks.
@usableFromInline
func insertAndFetchWithoutCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (InsertionSuccess, T)
{
let conflictResolution = conflictResolution ?? type(of: self)
.persistenceConflictPolicy
.conflictResolutionForInsert
let dao = try DAO(db, self)
let statement = try dao.insertStatement(
db,
onConflict: conflictResolution,
returning: selection)
let returned = try fetch(statement)
let rowIDColumn = dao.primaryKey.rowIDColumn
let rowid = db.lastInsertedRowID
// Update the persistenceContainer with the inserted rowid.
// This allows the Record class to set its `hasDatabaseChanges` property
// to false in its `aroundInsert` callback.
var persistenceContainer = dao.persistenceContainer
if let rowIDColumn = rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowid
}
let inserted = InsertionSuccess(
rowID: rowid,
rowIDColumn: rowIDColumn,
persistenceContainer: persistenceContainer)
return (inserted, returned)
}
}
@@ -0,0 +1,372 @@
// MARK: - Save Callbacks
extension MutablePersistableRecord {
@inline(__always)
@inlinable
public func willSave(_ db: Database) throws { }
@inline(__always)
@inlinable
public func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws {
_ = try save()
}
@inline(__always)
@inlinable
public func didSave(_ saved: PersistenceSuccess) { }
}
// MARK: - Save
extension MutablePersistableRecord {
/// Executes an `INSERT` or `UPDATE` statement.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func save(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws
{
try willSave(db)
var saved: PersistenceSuccess!
try aroundSave(db) {
saved = try updateOrInsertWithCallbacks(db, onConflict: conflictResolution)
return saved
}
didSave(saved)
}
/// Executes an `INSERT` or `UPDATE` statement, and returns the
/// saved record.
///
/// Usage:
///
/// let player = Player(id: nil, name: "Arthur")
/// let savedPlayer = try dbQueue.write { db in
/// try player.saved(db)
/// }
/// print(player.id) // nil
/// print(savedPlayer.id) // some id
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The saved record.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func saved(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self
{
var result = self
try result.save(db, onConflict: conflictResolution)
return result
}
}
// MARK: - Save and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let savedPlayer = player.saveAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try willSave(db)
var saved: PersistenceSuccess!
var returned: T?
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
})
return saved
}
didSave(saved)
return returned
}
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns the selected columns from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func saveAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var saved: PersistenceSuccess!
var returned: T!
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return saved
}
didSave(saved)
return returned
}
#else
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let savedPlayer = player.saveAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The saved record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try willSave(db)
var saved: PersistenceSuccess!
var returned: T?
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
})
return saved
}
didSave(saved)
return returned
}
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns the selected columns from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func saveAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var saved: PersistenceSuccess!
var returned: T!
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return saved
}
didSave(saved)
return returned
}
#endif
}
// MARK: - Internal
extension MutablePersistableRecord {
/// Executes an `UPDATE` or `INSERT` statement, and runs insertion or
/// update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
mutating func updateOrInsertWithCallbacks(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?)
throws -> PersistenceSuccess
{
let (saved, _) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: [],
fetch: {
// Nothing to fetch
try $0.execute()
})
return saved
}
/// Executes an `UPDATE` or `INSERT` statement, with `RETURNING` clause
/// if `selection` is not empty, and runs insertion or update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
mutating func updateOrInsertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (PersistenceSuccess, T)
{
// Attempt at updating if the record has a primary key
if let key = try primaryKey(db) {
do {
let databaseTableName = type(of: self).databaseTableName
let columns = try Set(db.columns(in: databaseTableName).map(\.name))
return try updateAndFetchWithCallbacks(
db, onConflict: conflictResolution,
columns: columns,
selection: selection,
fetch: fetch)
} catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) {
// No row was updated: fallback on insert.
}
}
// Insert
let (inserted, returned) = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return (PersistenceSuccess(inserted), returned)
}
/// Return a non-nil dictionary if record has a non-null primary key
@usableFromInline
func primaryKey(_ db: Database) throws -> [String: DatabaseValue]? {
let databaseTableName = type(of: self).databaseTableName
let primaryKeyInfo = try db.primaryKey(databaseTableName)
let container = try PersistenceContainer(db, self)
let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map {
($0, container[caseInsensitive: $0]?.databaseValue ?? .null)
})
if primaryKey.allSatisfy({ $0.value.isNull }) {
return nil
}
return primaryKey
}
}
@@ -0,0 +1,842 @@
// MARK: - Update Callbacks
extension MutablePersistableRecord {
@inline(__always)
@inlinable
public func willUpdate(_ db: Database, columns: Set<String>) throws { }
@inline(__always)
@inlinable
public func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
_ = try update()
}
@inline(__always)
@inlinable
public func didUpdate(_ updated: PersistenceSuccess) { }
}
// MARK: - Update
extension MutablePersistableRecord {
/// Executes an `UPDATE` statement on the provided columns.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
@inlinable // allow specialization so that empty callbacks are removed
public func update(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Sequence<String>)
throws
{
try willSave(db)
var updated: PersistenceSuccess!
try aroundSave(db) {
updated = try updateWithCallbacks(db, onConflict: conflictResolution, columns: Set(columns))
return updated
}
didSave(updated)
}
/// Executes an `UPDATE` statement on the provided columns.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
@inlinable // allow specialization so that empty callbacks are removed
public func update(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Sequence<some ColumnExpression>)
throws
{
try update(db, onConflict: conflictResolution, columns: columns.map(\.name))
}
/// Executes an `UPDATE` statement on all columns.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
@inlinable // allow specialization so that empty callbacks are removed
public func update(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws
{
let databaseTableName = type(of: self).databaseTableName
let columns = try db.columns(in: databaseTableName).map(\.name)
try update(db, onConflict: conflictResolution, columns: columns)
}
/// If the record has any difference from the other record, executes an
/// `UPDATE` statement so that those differences and only those differences
/// are saved in the database.
///
/// For example:
///
/// if let oldPlayer = try Player.fetchOne(db, key: 42) {
/// var newPlayer = oldPlayer
/// newPlayer.score += 10
/// newPlayer.hasAward = true
/// try newPlayer.updateChanges(db, from: oldRecord)
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter record: The comparison record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
/// - SeeAlso: updateChanges(_:with:)
@discardableResult
@inlinable // allow specialization so that empty callbacks are removed
public func updateChanges<Record: MutablePersistableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
from record: Record)
throws -> Bool
{
try updateChanges(db, onConflict: conflictResolution, from: PersistenceContainer(db, record))
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE` statement that updates the modified columns, if and
/// only the record was modified.
///
/// For example:
///
/// if var player = try Player.fetchOne(db, key: 42) {
/// try player.updateChanges(db) {
/// $0.score += 10
/// $0.hasAward = true
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter modify: A closure that modifies the record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@discardableResult
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChanges(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
modify: (inout Self) throws -> Void)
throws -> Bool
{
let container = try PersistenceContainer(db, self)
try modify(&self)
return try updateChanges(db, onConflict: conflictResolution, from: container)
}
}
// MARK: - Update and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE
/// Executes an `UPDATE ... RETURNING ...` statement, and returns the
/// updated record.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let updatedPlayer = player.updateAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `UPDATE ... RETURNING ...` statement on all columns, and
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE ... RETURNING ...` statement that updates the
/// modified columns, if and only the record was modified. The method
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change, or
/// in case of a failed update due to the `IGNORE` conflict policy.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
modify: (inout Self) throws -> Void)
throws -> Self?
where Self: FetchableRecord
{
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE ... RETURNING ...` statement that updates the
/// modified columns, if and only the record was modified. The method
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type,
modify: (inout Self) throws -> Void)
throws -> T?
{
try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: { try T.fetchOne($0) },
modify: modify)
}
/// Executes an `UPDATE ... RETURNING ...` statement on the provided
/// columns, and returns the selected columns from the updated row.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(
/// db, columns: ["Score"],
/// selection: [Column("totalScore")],
/// fetch: { statement in
/// try Int.fetchOne(statement)
/// })
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter columns: The columns to update.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Sequence<String>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var updated: PersistenceSuccess!
var returned: T!
try aroundSave(db) {
(updated, returned) = try updateAndFetchWithCallbacks(
db, onConflict: conflictResolution,
columns: Set(columns),
selection: selection,
fetch: fetch)
return updated
}
didSave(updated)
return returned
}
/// Executes an `UPDATE ... RETURNING ...` statement on the provided
/// columns, and returns the selected columns from the updated row.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(
/// db, columns: [Column("Score")],
/// selection: [Column("totalScore")],
/// fetch: { statement in
/// try Int.fetchOne(statement)
/// })
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter columns: The columns to update.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Sequence<some ColumnExpression>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
try updateAndFetch(
db, onConflict: conflictResolution,
columns: columns.map(\.name),
selection: selection,
fetch: fetch)
}
/// Executes an `UPDATE ... RETURNING ...` statement on all columns, and
/// returns the selected columns from the updated row.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
let databaseTableName = type(of: self).databaseTableName
let columns = try db.columns(in: databaseTableName).map(\.name)
return try updateAndFetch(
db, onConflict: conflictResolution,
columns: columns,
selection: selection,
fetch: fetch)
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE ... RETURNING ...` statement that updates the
/// modified columns, if and only the record was modified. The method
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func updateChangesAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?,
modify: (inout Self) throws -> Void)
throws -> T?
{
let container = try PersistenceContainer(db, self)
try modify(&self)
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
from: container,
selection: selection,
fetch: fetch)
}
#else
/// Executes an `UPDATE ... RETURNING ...` statement, and returns the
/// updated record.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let updatedPlayer = player.updateAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - returns: The updated record. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `UPDATE ... RETURNING ...` statement on all columns, and
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE ... RETURNING ...` statement that updates the
/// modified columns, if and only the record was modified. The method
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change, or
/// in case of a failed update due to the `IGNORE` conflict policy.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
modify: (inout Self) throws -> Void)
throws -> Self?
where Self: FetchableRecord
{
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE ... RETURNING ...` statement that updates the
/// modified columns, if and only the record was modified. The method
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change, or in case of a failed update due to the `IGNORE`
/// conflict policy.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type,
modify: (inout Self) throws -> Void)
throws -> T?
{
try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: { try T.fetchOne($0) },
modify: modify)
}
/// Executes an `UPDATE ... RETURNING ...` statement on the provided
/// columns, and returns the selected columns from the updated row.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(
/// db, columns: ["Score"],
/// selection: [Column("totalScore")],
/// fetch: { statement in
/// try Int.fetchOne(statement)
/// })
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter columns: The columns to update.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Sequence<String>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var updated: PersistenceSuccess!
var returned: T!
try aroundSave(db) {
(updated, returned) = try updateAndFetchWithCallbacks(
db, onConflict: conflictResolution,
columns: Set(columns),
selection: selection,
fetch: fetch)
return updated
}
didSave(updated)
return returned
}
/// Executes an `UPDATE ... RETURNING ...` statement on the provided
/// columns, and returns the selected columns from the updated row.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(
/// db, columns: [Column("Score")],
/// selection: [Column("totalScore")],
/// fetch: { statement in
/// try Int.fetchOne(statement)
/// })
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter columns: The columns to update.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Sequence<some ColumnExpression>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
try updateAndFetch(
db, onConflict: conflictResolution,
columns: columns.map(\.name),
selection: selection,
fetch: fetch)
}
/// Executes an `UPDATE ... RETURNING ...` statement on all columns, and
/// returns the selected columns from the updated row.
///
/// For example:
///
/// try dbQueue.write { db in
/// // UPDATE player SET ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
let databaseTableName = type(of: self).databaseTableName
let columns = try db.columns(in: databaseTableName).map(\.name)
return try updateAndFetch(
db, onConflict: conflictResolution,
columns: columns,
selection: selection,
fetch: fetch)
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE ... RETURNING ...` statement that updates the
/// modified columns, if and only the record was modified. The method
/// returns a new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?,
modify: (inout Self) throws -> Void)
throws -> T?
{
let container = try PersistenceContainer(db, self)
try modify(&self)
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
from: container,
selection: selection,
fetch: fetch)
}
#endif
}
// MARK: - Internals
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE
@inlinable // allow specialization so that empty callbacks are removed
func updateChangesAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return nil
}
return try updateAndFetch(
db, onConflict: conflictResolution,
columns: changedColumns,
selection: selection,
fetch: fetch)
}
#else
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
func updateChangesAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T?)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return nil
}
return try updateAndFetch(
db, onConflict: conflictResolution,
columns: changedColumns,
selection: selection,
fetch: fetch)
}
#endif
/// Executes an `UPDATE` statement, and runs update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
func updateWithCallbacks(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
columns: Set<String>)
throws -> PersistenceSuccess
{
let (updated, _) = try updateAndFetchWithCallbacks(
db, onConflict: conflictResolution,
columns: columns,
selection: [],
fetch: {
// Nothing to fetch
try $0.execute()
})
return updated
}
/// Executes an `UPDATE` statement, with `RETURNING` clause if `selection`
/// is not empty, and runs update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
func updateAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
columns: Set<String>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (PersistenceSuccess, T)
{
try willUpdate(db, columns: columns)
var updated: PersistenceSuccess!
var returned: T!
try aroundUpdate(db, columns: columns) {
(updated, returned) = try updateAndFetchWithoutCallbacks(
db, onConflict: conflictResolution,
columns: columns,
selection: selection,
fetch: fetch)
return updated
}
didUpdate(updated)
return (updated, returned)
}
/// Executes an `UPDATE` statement, with `RETURNING` clause if `selection`
/// is not empty, and DOES NOT run update callbacks.
@usableFromInline
func updateAndFetchWithoutCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
columns: Set<String>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (PersistenceSuccess, T)
{
let conflictResolution = conflictResolution ?? type(of: self)
.persistenceConflictPolicy
.conflictResolutionForUpdate
let dao = try DAO(db, self)
guard let statement = try dao.updateStatement(
columns: columns,
onConflict: conflictResolution,
returning: selection)
else {
// Nil primary key
throw dao.makeRecordNotFoundError()
}
let returned = try fetch(statement)
if db.changesCount == 0 {
// No row was updated
throw dao.makeRecordNotFoundError()
}
let updated = PersistenceSuccess(persistenceContainer: dao.persistenceContainer)
return (updated, returned)
}
@inlinable // allow specialization so that empty callbacks are removed
func updateChanges(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer)
throws -> Bool
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return false
}
try update(db, onConflict: conflictResolution, columns: changedColumns)
return true
}
}
+303
View File
@@ -0,0 +1,303 @@
/// Types that adopt `MutablePersistableRecord` can be inserted, updated,
/// and deleted.
public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
/// The policy that handles SQLite conflicts when records are inserted
/// or updated.
///
/// The default implementation uses the ABORT policy for both insertions and
/// updates, and has GRDB generate regular INSERT and UPDATE queries.
///
/// See <https://www.sqlite.org/lang_conflict.html>
static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
// MARK: Insertion Callbacks
/// Persistence callback called before the record is inserted.
///
/// Default implementation does nothing.
///
/// - parameter db: A database connection.
mutating func willInsert(_ db: Database) throws
/// Persistence callback called around the record insertion.
///
/// If you provide a custom implementation of this method, you must call
/// the `insert` parameter at some point in your implementation.
///
/// For example:
///
/// struct Player: MutablePersistableRecord {
/// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
/// print("Player will insert")
/// _ = try insert()
/// print("Player did insert")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter insert: A function that inserts the record, and returns
/// information about the inserted row.
func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws
/// Persistence callback called upon successful insertion.
///
/// The default implementation does nothing.
///
/// You can provide a custom implementation in order to grab the
/// auto-incremented id:
///
/// struct Player: MutablePersistableRecord {
/// var id: Int64?
/// var name: String
///
/// mutating func didInsert(_ inserted: InsertionSuccess) {
/// id = inserted.rowID
/// }
/// }
///
/// - parameter inserted: Information about the inserted row.
mutating func didInsert(_ inserted: InsertionSuccess)
// MARK: Update Callbacks
/// Persistence callback called before the record is updated.
///
/// Default implementation does nothing.
///
/// - parameter db: A database connection.
func willUpdate(_ db: Database, columns: Set<String>) throws
// swiftlint:disable line_length
/// Persistence callback called around the record update.
///
/// If you provide a custom implementation of this method, you must call
/// the `update` parameter at some point in your implementation.
///
/// For example:
///
/// struct Player: MutablePersistableRecord {
/// func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
/// print("Player will update")
/// _ = try update()
/// print("Player did update")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter columns: The updated columns.
/// - parameter update: A function that updates the record. Its result is
/// reserved for GRDB usage.
func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws
// swiftlint:enable line_length
/// Persistence callback called upon successful update.
///
/// Default implementation does nothing.
///
/// - parameter updated: Reserved for GRDB usage.
func didUpdate(_ updated: PersistenceSuccess)
// MARK: Save Callbacks
/// Persistence callback called before the record is updated or inserted.
///
/// Default implementation does nothing.
///
/// - parameter db: A database connection.
func willSave(_ db: Database) throws
/// Persistence callback called around the record update or insertion.
///
/// If you provide a custom implementation of this method, you must call
/// the `save` parameter at some point in your implementation.
///
/// For example:
///
/// struct Player: MutablePersistableRecord {
/// func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws {
/// print("Player will save")
/// _ = try save()
/// print("Player did save")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter update: A function that updates the record. Its result is
/// reserved for GRDB usage.
func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws
/// Persistence callback called upon successful update or insertion.
///
/// Default implementation does nothing.
///
/// - parameter saved: Reserved for GRDB usage.
func didSave(_ saved: PersistenceSuccess)
// MARK: Deletion Callbacks
/// Persistence callback called before the record is deleted.
///
/// Default implementation does nothing.
///
/// - parameter db: A database connection.
func willDelete(_ db: Database) throws
/// Persistence callback called around the destruction of the record.
///
/// If you provide a custom implementation of this method, you must call
/// the `delete` parameter at some point in your implementation.
///
/// For example:
///
/// struct Player: MutablePersistableRecord {
/// func aroundDelete(_ db: Database, delete: () throws -> Bool) throws {
/// print("Player will delete")
/// _ = try delete()
/// print("Player did delete")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter delete: A function that deletes the record and returns
/// whether a row was deleted in the database.
func aroundDelete(_ db: Database, delete: () throws -> Bool) throws
/// Persistence callback called upon successful deletion.
///
/// Default implementation does nothing.
///
/// - parameter deleted: Whether a row was deleted in the database.
func didDelete(deleted: Bool)
}
extension MutablePersistableRecord {
public static var persistenceConflictPolicy: PersistenceConflictPolicy {
PersistenceConflictPolicy(insert: .abort, update: .abort)
}
}
// MARK: - Existence Check
extension MutablePersistableRecord {
/// Returns true if and only if the primary key matches a row in
/// the database.
///
/// - parameter db: A database connection.
/// - returns: Whether the primary key matches a row in the database.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func exists(_ db: Database) throws -> Bool {
guard let statement = try DAO(db, self).existsStatement() else {
// Nil primary key
return false
}
return try Bool.fetchOne(statement)!
}
}
/// An error thrown by a type that adopts `MutablePersistableRecord`.
public enum PersistenceError: Error {
/// Thrown by `MutablePersistableRecord.update(_:)` methods when no matching
/// row could be found in the database.
///
/// - `databaseTableName`: the table of the unfound record
/// - `key`: the key of the unfound record (column and values)
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
}
extension PersistenceError: CustomStringConvertible {
/// :nodoc:
public var description: String {
switch self {
case let .recordNotFound(databaseTableName: databaseTableName, key: key):
let row = Row(key) // For nice output
return "Key not found in table \(databaseTableName): \(row.description)"
}
}
}
/// The `MutablePersistableRecord` protocol uses this type in order to handle
/// SQLite conflicts when records are inserted or updated.
///
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
///
/// See <https://www.sqlite.org/lang_conflict.html>
public struct PersistenceConflictPolicy {
/// The conflict resolution algorithm for insertions
public let conflictResolutionForInsert: Database.ConflictResolution
/// The conflict resolution algorithm for updates
public let conflictResolutionForUpdate: Database.ConflictResolution
/// Creates a policy
public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) {
self.conflictResolutionForInsert = insert
self.conflictResolutionForUpdate = update
}
}
/// The result of a successful record insertion.
///
/// `InsertionSuccess` gives the auto-incremented id after a successful
/// record insertion:
///
/// struct Player: Encodable, MutablePersistableRecord {
/// var id: Int64?
/// var name: String
///
/// mutating func didInsert(_ inserted: InsertionSuccess) {
/// id = inserted.rowID
/// }
/// }
///
/// try dbQueue.write { db in
/// var player = Player(id: nil, name: "Alice")
/// try player.insert(db)
/// print(player.id) // The inserted id
/// }
public struct InsertionSuccess {
/// The rowid of the inserted record.
///
/// For example:
///
/// struct Player: Encodable, MutablePersistableRecord {
/// var id: Int64?
/// var name: String
///
/// mutating func didInsert(_ inserted: InsertionSuccess) {
/// id = inserted.rowID
/// }
/// }
///
/// To learn about rowids, see <https://www.sqlite.org/lang_createtable.html#rowids_and_the_integer_primary_key>.
public var rowID: Int64
/// The name of the eventual INTEGER PRIMARY KEY column.
public var rowIDColumn: String?
// Used by the Record class in order to manage its `hasDatabaseChanges` flag.
/// The persistence container that was inserted.
///
/// If the database table has a rowid column, the persistence container
/// contains the rowid of the inserted record.
public var persistenceContainer: PersistenceContainer
}
/// The result of a successful record persistence (insert or update).
public struct PersistenceSuccess {
// Used by the Record class in order to manage its `hasDatabaseChanges` flag.
/// The persistence container that was saved.
///
/// After an insert, and if the database table has a rowid column, the
/// persistence container contains the rowid of the inserted record.
public var persistenceContainer: PersistenceContainer
init(persistenceContainer: PersistenceContainer) {
self.persistenceContainer = persistenceContainer
}
@usableFromInline
init(_ inserted: InsertionSuccess) {
self.init(persistenceContainer: inserted.persistenceContainer)
}
}
+344
View File
@@ -0,0 +1,344 @@
// MARK: - Insert Callbacks
extension PersistableRecord {
public func willInsert(_ db: Database) throws { }
public func didInsert(_ inserted: InsertionSuccess) { }
}
// MARK: - Insert
extension PersistableRecord {
/// Executes an `INSERT` statement.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func insert(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws
{
try willSave(db)
var saved: PersistenceSuccess!
try aroundSave(db) {
let inserted = try insertWithCallbacks(db, onConflict: conflictResolution)
saved = PersistenceSuccess(inserted)
return saved
}
didSave(saved)
}
}
// MARK: - Insert and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE
/// Executes an `INSERT ... RETURNING ...` statement, and returns a new
/// record built from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a base player, get a full one
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Executes an `INSERT ... RETURNING ...` statement, and returns the
/// selected columns from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a base player, get the inserted score
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var inserted: InsertionSuccess!
var returned: T!
try aroundSave(db) {
(inserted, returned) = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(inserted)
}
didSave(PersistenceSuccess(inserted))
return returned
}
#else
/// Executes an `INSERT ... RETURNING ...` statement, and returns a new
/// record built from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a base player, get a full one
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Executes an `INSERT ... RETURNING ...` statement, and returns the
/// selected columns from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a base player, get the inserted score
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var inserted: InsertionSuccess!
var returned: T!
try aroundSave(db) {
(inserted, returned) = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(inserted)
}
didSave(PersistenceSuccess(inserted))
return returned
}
#endif
}
// MARK: - Internals
extension PersistableRecord {
/// Executes an `INSERT` statement, and runs insertion callbacks.
@inlinable // allow specialization so that empty callbacks are removed
func insertWithCallbacks(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?)
throws -> InsertionSuccess
{
let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) {
// Nothing to fetch
try $0.execute()
}
return inserted
}
/// Executes an `INSERT` statement, with `RETURNING` clause if `selection`
/// is not empty, and runs insertion callbacks.
@inlinable // allow specialization so that empty callbacks are removed
func insertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (InsertionSuccess, T)
{
try willInsert(db)
var inserted: InsertionSuccess!
var returned: T!
try aroundInsert(db) {
(inserted, returned) = try insertAndFetchWithoutCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return inserted
}
didInsert(inserted)
return (inserted, returned)
}
}
+249
View File
@@ -0,0 +1,249 @@
// MARK: - Save
extension PersistableRecord {
/// Executes an `INSERT` or `UPDATE` statement.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func save(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws
{
try willSave(db)
var saved: PersistenceSuccess!
try aroundSave(db) {
saved = try updateOrInsertWithCallbacks(db, onConflict: conflictResolution)
return saved
}
didSave(saved)
}
}
// MARK: - Save and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try willSave(db)
var saved: PersistenceSuccess!
var returned: T?
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
})
return saved
}
didSave(saved)
return returned
}
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns the selected columns from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public func saveAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var saved: PersistenceSuccess!
var returned: T!
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return saved
}
didSave(saved)
return returned
}
#else
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`. The result can be nil when
/// the conflict policy is `IGNORE`.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try willSave(db)
var saved: PersistenceSuccess!
var returned: T?
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
try T.fetchOne($0)
})
return saved
}
didSave(saved)
return returned
}
/// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...`
/// statement, and returns the selected columns from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes it ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func saveAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var saved: PersistenceSuccess!
var returned: T!
try aroundSave(db) {
(saved, returned) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return saved
}
didSave(saved)
return returned
}
#endif
}
// MARK: - Internals
extension PersistableRecord {
/// Executes an `UPDATE` or `INSERT` statement, and runs insertion or
/// update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
func updateOrInsertWithCallbacks(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?)
throws -> PersistenceSuccess
{
let (saved, _) = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: [],
fetch: {
// Nothing to fetch
try $0.execute()
})
return saved
}
/// Executes an `UPDATE` or `INSERT` statement, with `RETURNING` clause
/// if `selection` is not empty, and runs insertion or update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
func updateOrInsertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (PersistenceSuccess, T)
{
// Attempt at updating if the record has a primary key
if let key = try primaryKey(db) {
do {
let databaseTableName = type(of: self).databaseTableName
let columns = try Set(db.columns(in: databaseTableName).map(\.name))
return try updateAndFetchWithCallbacks(
db, onConflict: conflictResolution,
columns: columns,
selection: selection,
fetch: fetch)
} catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) {
// No row was updated: fallback on insert.
}
}
// Insert
let (inserted, returned) = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return (PersistenceSuccess(inserted), returned)
}
}
+21 -890
View File
@@ -1,907 +1,38 @@
extension Database.ConflictResolution {
var invalidatesLastInsertedRowID: Bool {
switch self {
case .abort, .fail, .rollback, .replace:
return false
case .ignore:
// Statement may have succeeded without inserting any row
return true
}
}
}
/// An error thrown by a type that adopts `MutablePersistableRecord`.
public enum PersistenceError: Error, CustomStringConvertible {
/// Thrown by `MutablePersistableRecord.update(_:)` methods when no matching
/// row could be found in the database.
///
/// - `databaseTableName`: the table of the unfound record
/// - `key`: the key of the unfound record (column and values)
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
}
// CustomStringConvertible
extension PersistenceError {
/// :nodoc:
public var description: String {
switch self {
case let .recordNotFound(databaseTableName: databaseTableName, key: key):
let row = Row(key) // For nice output
return "Key not found in table \(databaseTableName): \(row.description)"
}
}
}
/// The `MutablePersistableRecord` protocol uses this type in order to handle
/// SQLite conflicts when records are inserted or updated.
/// Types that adopt `PersistableRecord` can be inserted, updated, and deleted.
///
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
///
/// See <https://www.sqlite.org/lang_conflict.html>
public struct PersistenceConflictPolicy {
/// The conflict resolution algorithm for insertions
public let conflictResolutionForInsert: Database.ConflictResolution
/// `PersistableRecord` has non-mutating variants of
/// `MutablePersistableRecord` methods.
public protocol PersistableRecord: MutablePersistableRecord {
/// The conflict resolution algorithm for updates
public let conflictResolutionForUpdate: Database.ConflictResolution
// MARK: Insertion Callbacks
/// Creates a policy
public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) {
self.conflictResolutionForInsert = insert
self.conflictResolutionForUpdate = update
}
}
/// Types that adopt `MutablePersistableRecord` can be inserted, updated,
/// and deleted.
public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
/// The policy that handles SQLite conflicts when records are inserted
/// or updated.
/// Persistence callback called before the record is inserted.
///
/// This property is optional: its default value uses the ABORT policy
/// for both insertions and updates, and has GRDB generate regular
/// INSERT and UPDATE queries.
/// Default implementation does nothing.
///
/// If insertions are resolved with .ignore policy, the
/// `didInsert(with:for:)` method is not called upon successful insertion,
/// even if a row was actually inserted without any conflict.
///
/// See <https://www.sqlite.org/lang_conflict.html>
static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
/// - note: If you need a mutating variant of this method, adopt the
/// ``MutablePersistableRecord`` protocol instead.
func willInsert(_ db: Database) throws
/// Notifies the record that it was successfully inserted.
/// Persistence callback called upon successful insertion.
///
/// Do not call this method directly: it is called for you, in a protected
/// dispatch queue, with the inserted RowID and the eventual
/// INTEGER PRIMARY KEY column name.
/// The default implementation does nothing.
///
/// This method is optional: the default implementation does nothing.
/// You can provide a custom implementation in order to grab the
/// auto-incremented id:
///
/// struct Player : MutablePersistableRecord {
/// class Player: PersistableRecord {
/// var id: Int64?
/// var name: String?
///
/// mutating func didInsert(with rowID: Int64, for column: String?) {
/// self.id = rowID
/// func didInsert(_ inserted: InsertionSuccess) {
/// id = inserted.rowID
/// }
/// }
///
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
mutating func didInsert(with rowID: Int64, for column: String?)
// MARK: - CRUD
/// Executes an INSERT statement.
/// - note: If you need a mutating variant of this method, adopt the
/// ``MutablePersistableRecord`` protocol instead.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Upon successful insertion, the didInsert(with:for:) method
/// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY
/// column name.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of insert(). In their implementation, it is recommended
/// that they invoke the performInsert() method.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
mutating func insert(_ db: Database) throws
/// Executes an UPDATE statement.
///
/// This method is guaranteed to have updated a row in the database if it
/// returns without error.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of update(). In their implementation, it is recommended
/// that they invoke the performUpdate() method.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
func update(_ db: Database, columns: Set<String>) throws
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// This method is guaranteed to have inserted or updated a row in the
/// database if it returns without error.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of save(). In their implementation, it is recommended
/// that they invoke the performSave() method.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
mutating func save(_ db: Database) throws
/// Executes a DELETE statement.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of delete(). In their implementation, it is recommended
/// that they invoke the performDelete() method.
///
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
func delete(_ db: Database) throws -> Bool
/// Returns true if and only if the primary key matches a row in
/// the database.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of exists(). In their implementation, it is recommended
/// that they invoke the performExists() method.
///
/// - parameter db: A database connection.
/// - returns: Whether the primary key matches a row in the database.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
func exists(_ db: Database) throws -> Bool
}
extension MutablePersistableRecord {
/// Describes the conflict policy for insertions and updates.
///
/// The default value specifies ABORT policy for both insertions and
/// updates, which has GRDB generate regular INSERT and UPDATE queries.
public static var persistenceConflictPolicy: PersistenceConflictPolicy {
PersistenceConflictPolicy(insert: .abort, update: .abort)
}
/// Notifies the record that it was successfully inserted.
///
/// The default implementation does nothing.
public mutating func didInsert(with rowID: Int64, for column: String?) {
}
// MARK: - CRUD
/// Executes an INSERT statement.
///
/// The default implementation for insert() invokes performInsert().
public mutating func insert(_ db: Database) throws {
try performInsert(db)
}
/// Executes an INSERT statement so that `self` is saved in the database,
/// and return the inserted record.
///
/// Usage:
///
/// let player = Player(id: nil, name: "Arthur")
/// let insertedPlayer = try dbQueue.write { db in
/// try player.inserted(db)
/// }
/// print(player.id) // nil
/// print(insertedPlayer.id) // some id
public func inserted(_ db: Database) throws -> Self {
var result = self
try result.insert(db)
return result
}
/// Executes an UPDATE statement.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func update(_ db: Database, columns: Set<String>) throws {
try performUpdate(db, columns: columns)
}
/// Executes an UPDATE statement.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func update(_ db: Database, columns: some Sequence<some ColumnExpression>) throws {
try update(db, columns: Set(columns.map(\.name)))
}
/// Executes an UPDATE statement.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func update(_ db: Database, columns: some Sequence<String>) throws {
try update(db, columns: Set(columns))
}
/// Executes an UPDATE statement that updates all table columns.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func update(_ db: Database) throws {
let databaseTableName = type(of: self).databaseTableName
let columns = try db.columns(in: databaseTableName)
try update(db, columns: Set(columns.map(\.name)))
}
/// If the record has any difference from the other record, executes an
/// UPDATE statement so that those differences and only those difference are
/// saved in the database.
///
/// This method is guaranteed to have saved the eventual differences in the
/// database if it returns without error.
///
/// For example:
///
/// if let oldPlayer = try Player.fetchOne(db, key: 42) {
/// var newPlayer = oldPlayer
/// newPlayer.score += 10
/// newPlayer.hasAward = true
/// try newPlayer.updateChanges(db, from: oldRecord)
/// }
///
/// - parameter db: A database connection.
/// - parameter record: The comparison record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
/// - SeeAlso: updateChanges(_:with:)
@discardableResult
public func updateChanges<Record: MutablePersistableRecord>(_ db: Database, from record: Record) throws -> Bool {
try updateChanges(db, from: PersistenceContainer(db, record))
}
/// Mutates the record according to the provided closure, and then, if the
/// record has any difference from its previous version, executes an
/// UPDATE statement so that those differences and only those difference are
/// saved in the database.
///
/// This method is guaranteed to have saved the eventual differences in the
/// database if it returns without error.
///
/// For example:
///
/// if var player = try Player.fetchOne(db, key: 42) {
/// try player.updateChanges(db) {
/// $0.score += 10
/// $0.hasAward = true
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter change: A closure that modifies the record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@discardableResult
public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool {
let container = try PersistenceContainer(db, self)
try change(&self)
return try updateChanges(db, from: container)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// The default implementation for save() invokes performSave().
public mutating func save(_ db: Database) throws {
try performSave(db)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database, and return the saved record.
///
/// Usage:
///
/// let player = Player(id: nil, name: "Arthur")
/// let savedPlayer = try dbQueue.write { db in
/// try player.saved(db)
/// }
/// print(player.id) // nil
/// print(savedPlayer.id) // some id
public func saved(_ db: Database) throws -> Self {
var result = self
try result.save(db)
return result
}
/// Executes a DELETE statement.
///
/// The default implementation for delete() invokes performDelete().
@discardableResult
public func delete(_ db: Database) throws -> Bool {
try performDelete(db)
}
/// Returns true if and only if the primary key matches a row in
/// the database.
///
/// The default implementation for exists() invokes performExists().
public func exists(_ db: Database) throws -> Bool {
try performExists(db)
}
// MARK: - Record Comparison
@discardableResult
fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool {
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return false
}
try update(db, columns: changedColumns)
return true
}
// MARK: - CRUD Internals
/// Return a non-nil dictionary if record has a non-null primary key
func primaryKey(_ db: Database) throws -> [String: DatabaseValue]? {
let databaseTableName = type(of: self).databaseTableName
let primaryKeyInfo = try db.primaryKey(databaseTableName)
let container = try PersistenceContainer(db, self)
let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map {
($0, container[caseInsensitive: $0]?.databaseValue ?? .null)
})
if primaryKey.allSatisfy({ $0.value.isNull }) {
return nil
}
return primaryKey
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutablePersistableRecord.
///
/// performInsert() provides the default implementation for insert(). Types
/// that adopt MutablePersistableRecord can invoke performInsert() in their
/// implementation of insert(). They should not provide their own
/// implementation of performInsert().
public mutating func performInsert(_ db: Database) throws {
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
let dao = try DAO(db, self)
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
if !conflictResolutionForInsert.invalidatesLastInsertedRowID {
didInsert(with: db.lastInsertedRowID, for: dao.primaryKey.rowIDColumn)
}
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutablePersistableRecord.
///
/// performUpdate() provides the default implementation for update(). Types
/// that adopt MutablePersistableRecord can invoke performUpdate() in their
/// implementation of update(). They should not provide their own
/// implementation of performUpdate().
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func performUpdate(_ db: Database, columns: Set<String>) throws {
let dao = try DAO(db, self)
guard let statement = try dao.updateStatement(
columns: columns,
onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate)
else {
// Nil primary key
throw dao.makeRecordNotFoundError()
}
try statement.execute()
if db.changesCount == 0 {
throw dao.makeRecordNotFoundError()
}
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutablePersistableRecord.
///
/// performSave() provides the default implementation for save(). Types
/// that adopt MutablePersistableRecord can invoke performSave() in their
/// implementation of save(). They should not provide their own
/// implementation of performSave().
///
/// This default implementation forwards the job to `update` or `insert`.
public mutating func performSave(_ db: Database) throws {
// Call self.insert and self.update so that we support classes that
// override those methods.
if let key = try primaryKey(db) {
do {
try update(db)
} catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) {
try insert(db)
}
} else {
try insert(db)
}
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutablePersistableRecord.
///
/// performDelete() provides the default implementation for delete(). Types
/// that adopt MutablePersistableRecord can invoke performDelete() in
/// their implementation of delete(). They should not provide their own
/// implementation of performDelete().
public func performDelete(_ db: Database) throws -> Bool {
guard let statement = try DAO(db, self).deleteStatement() else {
// Nil primary key
return false
}
try statement.execute()
return db.changesCount > 0
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutablePersistableRecord.
///
/// performExists() provides the default implementation for exists(). Types
/// that adopt MutablePersistableRecord can invoke performExists() in
/// their implementation of exists(). They should not provide their own
/// implementation of performExists().
public func performExists(_ db: Database) throws -> Bool {
guard let statement = try DAO(db, self).existsStatement() else {
// Nil primary key
return false
}
return try Row.fetchOne(statement) != nil
}
}
extension MutablePersistableRecord where Self: AnyObject {
// MARK: - Record Comparison
/// Mutates the record according to the provided closure, and then, if the
/// record has any difference from its previous version, executes an
/// UPDATE statement so that those differences and only those difference are
/// saved in the database.
///
/// This method is guaranteed to have saved the eventual differences in the
/// database if it returns without error.
///
/// For example:
///
/// if let player = try Player.fetchOne(db, key: 42) {
/// try player.updateChanges(db) {
/// $0.score += 10
/// $0.hasAward = true
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter change: A closure that modifies the record.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@discardableResult
public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool {
let container = try PersistenceContainer(db, self)
try change(self)
return try updateChanges(db, from: container)
}
}
// MARK: - PersistableRecord
/// Types that adopt `PersistableRecord` can be inserted, updated, and deleted.
///
/// Unlike `MutablePersistableRecord`, the `insert(_:)` and `save(_:)` methods
/// are not mutating methods.
public protocol PersistableRecord: MutablePersistableRecord {
/// Notifies the record that it was successfully inserted.
///
/// Do not call this method directly: it is called for you, in a protected
/// dispatch queue, with the inserted RowID and the eventual
/// INTEGER PRIMARY KEY column name.
///
/// This method is optional: the default implementation does nothing.
///
/// If you need a mutating variant of this method, adopt the
/// MutablePersistableRecord protocol instead.
///
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
func didInsert(with rowID: Int64, for column: String?)
/// Executes an INSERT statement.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Upon successful insertion, the didInsert(with:for:) method
/// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY
/// column name.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of insert(). In their implementation, it is recommended
/// that they invoke the performInsert() method.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
func insert(_ db: Database) throws
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// This method is guaranteed to have inserted or updated a row in the
/// database if it returns without error.
///
/// This method has a default implementation, so your adopting types don't
/// have to implement it. Yet your types can provide their own
/// implementation of save(). In their implementation, it is recommended
/// that they invoke the performSave() method.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
func save(_ db: Database) throws
}
extension PersistableRecord {
/// Notifies the record that it was successfully inserted.
///
/// The default implementation does nothing.
public func didInsert(with rowID: Int64, for column: String?) {
}
// MARK: - Immutable CRUD
/// Executes an INSERT statement.
///
/// The default implementation for insert() invokes performInsert().
public func insert(_ db: Database) throws {
try performInsert(db)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// The default implementation for save() invokes performSave().
public func save(_ db: Database) throws {
try performSave(db)
}
// MARK: - Immutable CRUD Internals
/// Don't invoke this method directly: it is an internal method for types
/// that adopt PersistableRecord.
///
/// performInsert() provides the default implementation for insert(). Types
/// that adopt PersistableRecord can invoke performInsert() in their
/// implementation of insert(). They should not provide their own
/// implementation of performInsert().
public func performInsert(_ db: Database) throws {
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
let dao = try DAO(db, self)
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
if !conflictResolutionForInsert.invalidatesLastInsertedRowID {
didInsert(with: db.lastInsertedRowID, for: dao.primaryKey.rowIDColumn)
}
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt PersistableRecord.
///
/// performSave() provides the default implementation for save(). Types
/// that adopt PersistableRecord can invoke performSave() in their
/// implementation of save(). They should not provide their own
/// implementation of performSave().
///
/// This default implementation forwards the job to `update` or `insert`.
public func performSave(_ db: Database) throws {
// Call self.insert and self.update so that we support classes that
// override those methods.
if let key = try primaryKey(db) {
do {
try update(db)
} catch PersistenceError.recordNotFound(databaseTableName: type(of: self).databaseTableName, key: key) {
try insert(db)
}
} else {
try insert(db)
}
}
}
// MARK: - DAO
extension PersistenceContainer {
/// Convenience initializer from a database connection and a record
init(_ db: Database, _ record: some EncodableRecord & TableRecord) throws {
let databaseTableName = type(of: record).databaseTableName
let columnCount = try db.columns(in: databaseTableName).count
self.init(minimumCapacity: columnCount)
record.encode(to: &self)
}
}
/// DAO takes care of PersistableRecord CRUD
final class DAO<Record: MutablePersistableRecord> {
/// The database
let db: Database
/// DAO keeps a copy the record's persistenceContainer, so that this
/// dictionary is built once whatever the database operation. It is
/// guaranteed to have at least one (key, value) pair.
let persistenceContainer: PersistenceContainer
/// The table name
let databaseTableName: String
/// The table primary key info
let primaryKey: PrimaryKeyInfo
init(_ db: Database, _ record: Record) throws {
self.db = db
databaseTableName = type(of: record).databaseTableName
primaryKey = try db.primaryKey(databaseTableName)
persistenceContainer = try PersistenceContainer(db, record)
GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container")
}
func insertStatement(onConflict: Database.ConflictResolution) throws -> Statement {
let query = InsertQuery(
onConflict: onConflict,
tableName: databaseTableName,
insertedColumns: persistenceContainer.columns)
let statement = try db.internalCachedStatement(sql: query.sql)
statement.setUncheckedArguments(StatementArguments(persistenceContainer.values))
return statement
}
/// Returns nil if and only if primary key is nil
func updateStatement(columns: Set<String>, onConflict: Database.ConflictResolution) throws -> Statement? {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
}
// Don't update columns not present in columns
// Don't update columns not present in the persistenceContainer
// Don't update primary key columns
let lowercaseUpdatedColumns = Set(columns.map { $0.lowercased() })
.intersection(persistenceContainer.columns.map { $0.lowercased() })
.subtracting(primaryKeyColumns.map { $0.lowercased() })
var updatedColumns: [String] = try db
.columns(in: databaseTableName)
.map(\.name)
.filter { lowercaseUpdatedColumns.contains($0.lowercased()) }
if updatedColumns.isEmpty {
// IMPLEMENTATION NOTE
//
// It is important to update something, so that
// TransactionObserver can observe a change even though this
// change is useless.
//
// The goal is to be able to write tests with minimal tables,
// including tables made of a single primary key column.
updatedColumns = primaryKeyColumns
}
let updatedValues = updatedColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
let query = UpdateQuery(
onConflict: onConflict,
tableName: databaseTableName,
updatedColumns: updatedColumns,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedStatement(sql: query.sql)
statement.setUncheckedArguments(StatementArguments(updatedValues + primaryKeyValues))
return statement
}
/// Returns nil if and only if primary key is nil
func deleteStatement() throws -> Statement? {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
}
let query = DeleteQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedStatement(sql: query.sql)
statement.setUncheckedArguments(StatementArguments(primaryKeyValues))
return statement
}
/// Returns nil if and only if primary key is nil
func existsStatement() throws -> Statement? {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey.columns
let primaryKeyValues = primaryKeyColumns.map {
persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null
}
if primaryKeyValues.allSatisfy({ $0.isNull }) {
return nil
}
let query = ExistsQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedStatement(sql: query.sql)
statement.setUncheckedArguments(StatementArguments(primaryKeyValues))
return statement
}
/// Throws a PersistenceError.recordNotFound error
func makeRecordNotFoundError() -> Error {
let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map {
($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null)
})
return PersistenceError.recordNotFound(
databaseTableName: databaseTableName,
key: key)
}
}
// MARK: - InsertQuery
private struct InsertQuery: Hashable {
let onConflict: Database.ConflictResolution
let tableName: String
let insertedColumns: [String]
}
extension InsertQuery {
@ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:]
var sql: String {
if let sql = Self.sqlCache[self] {
return sql
}
let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")
let valuesSQL = databaseQuestionMarks(count: insertedColumns.count)
let sql: String
switch onConflict {
case .abort:
sql = """
INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \
VALUES (\(valuesSQL))
"""
default:
sql = """
INSERT OR \(onConflict.rawValue) \
INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \
VALUES (\(valuesSQL))
"""
}
Self.sqlCache[self] = sql
return sql
}
}
// MARK: - UpdateQuery
private struct UpdateQuery: Hashable {
let onConflict: Database.ConflictResolution
let tableName: String
let updatedColumns: [String]
let conditionColumns: [String]
}
extension UpdateQuery {
@ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:]
var sql: String {
if let sql = Self.sqlCache[self] {
return sql
}
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ")
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
let sql: String
switch onConflict {
case .abort:
sql = """
UPDATE \(tableName.quotedDatabaseIdentifier) \
SET \(updateSQL) \
WHERE \(whereSQL)
"""
default:
sql = """
UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \
SET \(updateSQL) \
WHERE \(whereSQL)
"""
}
Self.sqlCache[self] = sql
return sql
}
}
// MARK: - DeleteQuery
private struct DeleteQuery {
let tableName: String
let conditionColumns: [String]
}
extension DeleteQuery {
var sql: String {
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)"
}
}
// MARK: - ExistsQuery
private struct ExistsQuery {
let tableName: String
let conditionColumns: [String]
}
extension ExistsQuery {
var sql: String {
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)"
}
/// - parameter inserted: Information about the inserted row.
func didInsert(_ inserted: InsertionSuccess)
}
+179 -145
View File
@@ -47,13 +47,8 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
/// The policy that handles SQLite conflicts when records are inserted
/// or updated.
///
/// This property is optional: its default value uses the ABORT policy
/// for both insertions and updates, and has GRDB generate regular
/// INSERT and UPDATE queries.
///
/// If insertions are resolved with .ignore policy, the
/// `didInsert(with:for:)` method is not called upon successful insertion,
/// even if a row was actually inserted without any conflict.
/// The default implementation uses the ABORT policy for both insertions and
/// updates, and has GRDB generate regular INSERT and UPDATE queries.
///
/// See <https://www.sqlite.org/lang_conflict.html>
open class var persistenceConflictPolicy: PersistenceConflictPolicy {
@@ -96,7 +91,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
/// Defines the values persisted in the database.
///
/// Store in the *container* argument all values that should be stored in
/// Store in the *container* parameter all values that should be stored in
/// the columns of the database table (see Record.databaseTableName()).
///
/// Primary key columns, if any, must be included.
@@ -113,31 +108,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
///
/// The implementation of the base class Record does not store any value in
/// the container.
open func encode(to container: inout PersistenceContainer) {
}
/// Notifies the record that it was successfully inserted.
///
/// Do not call this method directly: it is called for you, in a protected
/// dispatch queue, with the inserted RowID and the eventual
/// INTEGER PRIMARY KEY column name.
///
/// The implementation of the base Record class does nothing.
///
/// class Player : Record {
/// var id: Int64?
/// var name: String?
///
/// func didInsert(with rowID: Int64, for column: String?) {
/// id = rowID
/// }
/// }
///
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
open func didInsert(with rowID: Int64, for column: String?) {
}
open func encode(to container: inout PersistenceContainer) { }
// MARK: - Compare with Previous Versions
@@ -199,80 +170,184 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
/// Reference row for the *hasDatabaseChanges* property.
var referenceRow: Row?
// MARK: Persistence Callbacks
/// Called before the record is inserted.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter db: A database connection.
open func willInsert(_ db: Database) throws { }
/// Called around the record insertion.
///
/// If you override this method, you must call `super` at some point in
/// your implementation (this calls the `insert` parameter).
///
/// For example:
///
/// class Player: Record {
/// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
/// print("Player will insert")
/// try super.aroundInsert(db, insert: insert)
/// print("Player did insert")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter insert: A function that inserts the record, and returns
/// information about the inserted row.
open func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
let inserted = try insert()
// Set hasDatabaseChanges to false
referenceRow = Row(inserted.persistenceContainer)
}
/// Called upon successful insertion.
///
/// You can override this method in order to grab the auto-incremented id:
///
/// class Player: Record {
/// var id: Int64?
/// var name: String
///
/// override func didInsert(_ inserted: InsertionSuccess) {
/// super.didInsert(inserted)
/// id = inserted.rowID
/// }
/// }
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter inserted: Information about the inserted row.
open func didInsert(_ inserted: InsertionSuccess) { }
/// Called before the record is updated.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter db: A database connection.
open func willUpdate(_ db: Database, columns: Set<String>) throws { }
// swiftlint:disable line_length
/// Called around the record update.
///
/// If you override this method, you must call `super` at some point in
/// your implementation (this calls the `update` parameter).
///
/// For example:
///
/// class Player: Record {
/// override func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
/// print("Player will update")
/// try super.aroundUpdate(db, columns: columns, update: update)
/// print("Player did update")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter columns: The updated columns.
/// - parameter update: A function that updates the record. Its result is
/// reserved for GRDB usage.
open func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
let updated = try update()
// Set hasDatabaseChanges to false
referenceRow = Row(updated.persistenceContainer)
}
// swiftlint:enable line_length
/// Called upon successful update.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter updated: Reserved for GRDB usage.
open func didUpdate(_ updated: PersistenceSuccess) { }
/// Called before the record is updated or inserted.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter db: A database connection.
open func willSave(_ db: Database) throws { }
/// Called around the record update or insertion.
///
/// If you override this method, you must call `super` at some point in
/// your implementation (this calls the `update` parameter).
///
/// For example:
///
/// class Player: Record {
/// override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws {
/// print("Player will save")
/// try super.aroundSave(db, save: save)
/// print("Player did save")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter update: A function that updates the record. Its result is
/// reserved for GRDB usage.
open func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws {
_ = try save()
}
/// Called upon successful update or insertion.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter saved: Reserved for GRDB usage.
open func didSave(_ saved: PersistenceSuccess) { }
/// Called before the record is deleted.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter db: A database connection.
open func willDelete(_ db: Database) throws { }
/// Called around the destruction of the record.
///
/// If you override this method, you must call `super` at some point in
/// your implementation (this calls the `delete` parameter).
///
/// For example:
///
/// class Player: Record {
/// override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws {
/// print("Player will delete")
/// try super.aroundDelete(db, delete: delete)
/// print("Player did delete")
/// }
/// }
///
/// - parameter db: A database connection.
/// - parameter delete: A function that deletes the record and returns
/// whether a row was deleted in the database.
open func aroundDelete(_ db: Database, delete: () throws -> Bool) throws {
_ = try delete()
hasDatabaseChanges = true
}
/// Called upon successful deletion.
///
/// If you override this method, you must call `super` at some point in
/// your implementation.
///
/// - parameter deleted: Whether a row was deleted in the database.
open func didDelete(deleted: Bool) { }
// MARK: - CRUD
/// Executes an INSERT statement.
///
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Records whose primary key is declared as "INTEGER PRIMARY KEY" have
/// their id automatically set after successful insertion, if it was nil
/// before the insertion.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
open func insert(_ db: Database) throws {
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
let dao = try DAO(db, self)
var persistenceContainer = dao.persistenceContainer
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
if !conflictResolutionForInsert.invalidatesLastInsertedRowID {
let rowID = db.lastInsertedRowID
let rowIDColumn = dao.primaryKey.rowIDColumn
didInsert(with: rowID, for: rowIDColumn)
// Update persistenceContainer with inserted id, so that we can
// set hasDatabaseChanges to false:
if let rowIDColumn = rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowID
}
}
// Set hasDatabaseChanges to false
referenceRow = Row(persistenceContainer)
}
/// Executes an UPDATE statement.
///
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have updated a row in the database if it
/// returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
open func update(_ db: Database, columns: Set<String>) throws {
// The simplest code would be:
//
// try performUpdate(db, columns: columns)
// hasDatabaseChanges = false
//
// But this would trigger two calls to `encode(to:)`.
let dao = try DAO(db, self)
guard let statement = try dao.updateStatement(
columns: columns,
onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate)
else {
// Nil primary key
throw dao.makeRecordNotFoundError()
}
try statement.execute()
if db.changesCount == 0 {
throw dao.makeRecordNotFoundError()
}
// Set hasDatabaseChanges to false
referenceRow = Row(dao.persistenceContainer)
}
/// If the record has been changed, executes an UPDATE statement so that
/// those changes and only those changes are saved in the database.
///
@@ -297,45 +372,4 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
return true
}
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// If the record has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have inserted or updated a row in the
/// database if it returns without error.
///
/// You can't override this method. Instead, override `insert(_:)`
/// or `update(_:columns:)`.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
public final func save(_ db: Database) throws {
try performSave(db)
}
/// Executes a DELETE statement.
///
/// On success, this method sets the *hasDatabaseChanges* flag to true.
///
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
open func delete(_ db: Database) throws -> Bool {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
// hasDatabaseChanges flag:
hasDatabaseChanges = true
}
return try performDelete(db)
}
}
+34 -34
View File
@@ -144,10 +144,10 @@ extension TableRecord {
extension TableRecord {
/// Deletes all records; returns the number of deleted rows.
/// Deletes all records, and returns the number of deleted records.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
/// - returns: The number of deleted records
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public static func deleteAll(_ db: Database) throws -> Int {
@@ -158,7 +158,7 @@ extension TableRecord {
// MARK: - Check Existence by Single-Column Primary Key
extension TableRecord {
/// Returns whether a row exists for this primary key.
/// Returns whether a record exists for this primary key.
///
/// try Player.exists(db, key: 123)
/// try Country.exists(db, key: "FR")
@@ -171,7 +171,7 @@ extension TableRecord {
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a row exists for this primary key.
/// - returns: Whether a record exists for this primary key.
public static func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool {
try !filter(key: key).isEmpty(db)
}
@@ -179,7 +179,7 @@ extension TableRecord {
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns whether a row exists for this primary key.
/// Returns whether a record exists for this primary key.
///
/// try Player.deleteOne(db, id: 123)
/// try Country.deleteOne(db, id: "FR")
@@ -192,7 +192,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - id: A primary key value.
/// - returns: Whether a row exists for this primary key.
/// - returns: Whether a record exists for this primary key.
public static func exists(_ db: Database, id: ID) throws -> Bool {
if id.databaseValue.isNull {
// Don't hit the database
@@ -205,15 +205,15 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
// MARK: - Check Existence by Key
extension TableRecord {
/// Returns whether a row exists for this unique key (primary key or any key
/// with a unique index on it).
/// Returns whether a record exists for this unique key (primary key or any
/// key with a unique index on it).
///
/// try Player.exists(db, key: ["name": Arthur"])
///
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a row exists for this key.
/// - returns: Whether a record exists for this key.
public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
try !filter(key: key).isEmpty(db)
}
@@ -223,8 +223,8 @@ extension TableRecord {
extension TableRecord {
/// Delete records identified by their primary keys; returns the number of
/// deleted rows.
/// Delete records identified by their primary keys, and returns the number
/// of deleted records.
///
/// // DELETE FROM player WHERE id IN (1, 2, 3)
/// try Player.deleteAll(db, keys: [1, 2, 3])
@@ -241,7 +241,7 @@ extension TableRecord {
/// - parameters:
/// - db: A database connection.
/// - keys: A sequence of primary keys.
/// - returns: The number of deleted rows
/// - returns: The number of deleted records
@discardableResult
public static func deleteAll(_ db: Database, keys: some Sequence<some DatabaseValueConvertible>)
throws -> Int
@@ -254,8 +254,8 @@ extension TableRecord {
return try filter(keys: keys).deleteAll(db)
}
/// Delete a record, identified by its primary key; returns whether a
/// database row was deleted.
/// Delete a record, identified by its primary key, and returns whether a
/// record was deleted.
///
/// // DELETE FROM player WHERE id = 123
/// try Player.deleteOne(db, key: 123)
@@ -272,7 +272,7 @@ extension TableRecord {
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a database row was deleted.
/// - returns: Whether a record was deleted.
@discardableResult
public static func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool {
if key.databaseValue.isNull {
@@ -285,8 +285,8 @@ extension TableRecord {
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Delete records identified by their primary keys; returns the number of
/// deleted rows.
/// Delete records identified by their primary keys, and returns the number
/// of deleted records.
///
/// // DELETE FROM player WHERE id IN (1, 2, 3)
/// try Player.deleteAll(db, ids: [1, 2, 3])
@@ -303,7 +303,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - ids: A collection of primary keys.
/// - returns: The number of deleted rows
/// - returns: The number of deleted records
@discardableResult
public static func deleteAll(_ db: Database, ids: some Collection<ID>) throws -> Int {
if ids.isEmpty {
@@ -313,8 +313,8 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
return try filter(ids: ids).deleteAll(db)
}
/// Delete a record, identified by its primary key; returns whether a
/// database row was deleted.
/// Delete a record, identified by its primary key, and returns whether a
/// record was deleted.
///
/// // DELETE FROM player WHERE id = 123
/// try Player.deleteOne(db, id: 123)
@@ -331,7 +331,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - id: A primary key value.
/// - returns: Whether a database row was deleted.
/// - returns: Whether a record was deleted.
@discardableResult
public static func deleteOne(_ db: Database, id: ID) throws -> Bool {
try deleteAll(db, ids: [id]) > 0
@@ -342,14 +342,15 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
extension TableRecord {
/// Delete records identified by the provided unique keys (primary key or
/// any key with a unique index on it); returns the number of deleted rows.
/// any key with a unique index on it), and returns the number of
/// deleted records.
///
/// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - returns: The number of deleted rows
/// - returns: The number of deleted records
@discardableResult
public static func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int {
if keys.isEmpty {
@@ -360,14 +361,15 @@ extension TableRecord {
}
/// Delete a record, identified by a unique key (the primary key or any key
/// with a unique index on it); returns whether a database row was deleted.
/// with a unique index on it), and returns whether a database record
/// was deleted.
///
/// Player.deleteOne(db, key: ["name": Arthur"])
///
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a database row was deleted.
/// - returns: Whether a record was deleted.
@discardableResult
public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
try deleteAll(db, keys: [key]) > 0
@@ -378,7 +380,7 @@ extension TableRecord {
extension TableRecord {
/// Updates all records; returns the number of updated records.
/// Updates all records, and returns the number of updated records.
///
/// For example:
///
@@ -391,7 +393,7 @@ extension TableRecord {
/// - parameter conflictResolution: A policy for conflict resolution,
/// defaulting to the record's persistenceConflictPolicy.
/// - parameter assignments: An array of column assignments.
/// - returns: The number of updated rows.
/// - returns: The number of updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public static func updateAll(
@@ -403,7 +405,7 @@ extension TableRecord {
try all().updateAll(db, onConflict: conflictResolution, assignments)
}
/// Updates all records; returns the number of updated records.
/// Updates all records, and returns the number of updated records.
///
/// For example:
///
@@ -415,19 +417,17 @@ extension TableRecord {
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution,
/// defaulting to the record's persistenceConflictPolicy.
/// - parameter assignment: A column assignment.
/// - parameter otherAssignments: Eventual other column assignments.
/// - returns: The number of updated rows.
/// - parameter assignments: Column assignments.
/// - returns: The number of updated records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public static func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignment: ColumnAssignment,
_ otherAssignments: ColumnAssignment...)
_ assignments: ColumnAssignment...)
throws -> Int
{
try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
try updateAll(db, onConflict: conflictResolution, assignments)
}
}
+54 -6
View File
@@ -509,6 +509,24 @@
56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; };
56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; };
56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; };
56D110E928AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */; };
56D110EA28AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */; };
56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */; };
56D110EC28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */; };
56D110ED28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */; };
56D110EE28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */; };
56D110EF28AFC90800E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */; };
56D110F028AFC90800E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */; };
56D110F128AFC90800E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E528AFC90800E64463 /* PersistableRecord.swift */; };
56D110F228AFC90800E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E528AFC90800E64463 /* PersistableRecord.swift */; };
56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */; };
56D110F428AFC90800E64463 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */; };
56D110F528AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */; };
56D110F628AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */; };
56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */; };
56D110F828AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */; };
56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */; };
56D1110028AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */; };
56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; };
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; };
56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
@@ -580,7 +598,6 @@
F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
F3BA80381CFB2932003DC1BA /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -619,7 +636,6 @@
F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -810,7 +826,6 @@
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = "<group>"; };
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = "<group>"; };
561162692576BF9C007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = "<group>"; };
5613ED5921A95E6100DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = "<group>"; };
@@ -1116,6 +1131,15 @@
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = "<group>"; };
56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = "<group>"; };
56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = "<group>"; };
56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = "<group>"; };
56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = "<group>"; };
56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = "<group>"; };
56D110E528AFC90800E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = "<group>"; };
56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = "<group>"; };
56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = "<group>"; };
56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
@@ -1849,7 +1873,15 @@
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */,
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */,
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */,
560D92441C672C4B00F4F92B /* PersistableRecord.swift */,
56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */,
56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */,
56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */,
56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */,
56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */,
56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */,
56D110E528AFC90800E64463 /* PersistableRecord.swift */,
56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */,
56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
560D92461C672C4B00F4F92B /* TableRecord.swift */,
);
@@ -2321,6 +2353,7 @@
5656A8602295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */,
56012B81257404A400B4925B /* CommonTableExpression.swift in Sources */,
5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */,
56D1110028AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
@@ -2353,8 +2386,11 @@
563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */,
5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
56D110EA28AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */,
569BBA4C229170B300478429 /* Inflections+English.swift in Sources */,
56D110F628AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */,
56D110F028AFC90800E64463 /* PersistableRecord+Save.swift in Sources */,
56A6EB2526076F6A00C27594 /* SQL.swift in Sources */,
5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */,
568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */,
@@ -2407,7 +2443,6 @@
566BE7162342541F00A8254B /* LockedBox.swift in Sources */,
F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */,
F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */,
F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */,
5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
@@ -2415,9 +2450,13 @@
564CE43D21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
56D110EC28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
56D110F828AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
56D110EE28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */,
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
564D4F94261E1D3400F55856 /* CaseInsensitiveIdentifier.swift in Sources */,
56D110F228AFC90800E64463 /* PersistableRecord.swift in Sources */,
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
@@ -2428,6 +2467,7 @@
5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */,
F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */,
567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
56D110F428AFC90800E64463 /* MutablePersistableRecord.swift in Sources */,
F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
5657AABE1D107001006283EF /* NSData.swift in Sources */,
5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -2693,6 +2733,7 @@
5656A85F2295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */,
56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */,
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */,
56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
@@ -2725,8 +2766,11 @@
563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */,
5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
56D110E928AFC90800E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */,
569BBA4D229170B300478429 /* Inflections+English.swift in Sources */,
56D110F528AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */,
56D110EF28AFC90800E64463 /* PersistableRecord+Save.swift in Sources */,
56A6EB2426076F6A00C27594 /* SQL.swift in Sources */,
5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */,
568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */,
@@ -2779,7 +2823,6 @@
566BE7152342541F00A8254B /* LockedBox.swift in Sources */,
F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */,
F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */,
F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */,
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
@@ -2787,9 +2830,13 @@
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
56D110ED28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */,
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
564D4F93261E1D3300F55856 /* CaseInsensitiveIdentifier.swift in Sources */,
56D110F128AFC90800E64463 /* PersistableRecord.swift in Sources */,
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
@@ -2800,6 +2847,7 @@
5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */,
F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */,
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */,
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
5657AABB1D107001006283EF /* NSData.swift in Sources */,
5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
+250 -63
View File
@@ -2473,8 +2473,9 @@ Extending structs with record protocols is more "swifty". Subclassing the Record
- [FetchableRecord Protocol](#fetchablerecord-protocol)
- [TableRecord Protocol](#tablerecord-protocol)
- [PersistableRecord Protocol](#persistablerecord-protocol)
- [Persistence Methods](#persistence-methods)
- [Customizing the Persistence Methods]
- [Persistence Methods]
- [Persistence Methods and the `RETURNING` clause](#persistence-methods-and-the-returning-clause)
- [Persistence Callbacks]
- [Identifiable Records]
- [Codable Records]
- [Record Class](#record-class)
@@ -2807,23 +2808,23 @@ protocol EncodableRecord {
protocol MutablePersistableRecord: TableRecord, EncodableRecord {
/// Optional method that lets your adopting type store its rowID upon
/// successful insertion. Don't call it directly: it is called for you.
mutating func didInsert(with rowID: Int64, for column: String?)
mutating func didInsert(_ inserted: InsertionSuccess)
}
// Adds immutability
protocol PersistableRecord: MutablePersistableRecord {
/// Non-mutating version of the optional didInsert(with:for:)
func didInsert(with rowID: Int64, for column: String?)
/// Non-mutating version of the optional didInsert(_:)
func didInsert(_ inserted: InsertionSuccess)
}
```
Yes, three protocols instead of one. Here is how you pick one or the other:
- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(with:for:)` if the database table has an auto-incremented primary key.
- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(_:)` if the database table has an auto-incremented primary key.
- **If your type is a struct, and the database table has an auto-incremented primary key**, choose `MutablePersistableRecord`, and implement `didInsert(with:for:)`.
- **If your type is a struct, and the database table has an auto-incremented primary key**, choose `MutablePersistableRecord`, and implement `didInsert(_:)`.
- **Otherwise**, choose `PersistableRecord`, and ignore `didInsert(with:for:)`.
- **Otherwise**, choose `PersistableRecord`, and ignore `didInsert(_:)`.
The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns.
@@ -2842,8 +2843,8 @@ extension Place : MutablePersistableRecord {
}
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -2883,8 +2884,8 @@ struct Player: Encodable, MutablePersistableRecord {
var score: Int
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
@@ -2892,7 +2893,7 @@ struct Player: Encodable, MutablePersistableRecord {
### Persistence Methods
[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given default implementations for methods that insert, update, and delete:
[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given methods that insert, update, and delete:
```swift
// INSERT
@@ -2919,7 +2920,7 @@ try place.delete(db)
let exists = try place.exists(db)
```
The [TableRecord] protocol comes with batch operations:
**The [TableRecord] protocol comes with batch operations**:
```swift
// UPDATE
@@ -2943,56 +2944,203 @@ try Place.deleteOne(db, key:...)
**All primary keys are supported**, including composite primary keys that span several columns, and the [implicit rowid primary key](#the-implicit-rowid-primary-key).
**To customize persistence methods**, you provide [Persistence Callbacks], described below. Do not attempt at overriding the ready-made persistence methods.
### Customizing the Persistence Methods
### Persistence Methods and the `RETURNING` clause
Your custom type may want to perform extra work when the persistence methods are invoked.
SQLite 3.35.0+ is able to return values from a inserted or updated row, with the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html) (available from iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build]).
For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving.
The `RETURNING` clause helps dealing with database features such as auto-incremented ids, default values, and [generated columns](https://sqlite.org/gencol.html). You can, for example, insert a few columns and fetch the default or generated ones in one step.
When you subclass [Record](#record-class), you simply have to override the customized method, and call `super`:
GRDB uses the `RETURNING` clause in all persistence methods that contain `AndFetch` in their name.
For example, given a database table with an auto-incremented primary key and a default score:
```swift
class Player : Record {
var uuid: UUID?
try dbQueue.write { db in
try db.execute(sql: """
CREATE TABLE player(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
score INTEGER NOT NULL DEFAULT 1000)
""")
}
```
You can define a record type with full database information, and another partial record type that deals with a subset of columns:
```swift
// A player with full database information
struct Player: Codable, PersistableRecord, FetchableRecord {
var id: Int64
var name: String
var score: Int
}
// A partial player
struct PartialPlayer: Encodable, PersistableRecord {
static let databaseTableName = "player"
var name: String
}
```
And now you can get a full player by inserting a partial one:
```swift
try dbQueue.write { db in
let partialPlayer = PartialPlayer(name: "Alice")
override func insert(_ db: Database) throws {
if uuid == nil {
uuid = UUID()
}
try super.insert(db)
// INSERT INTO player (name) VALUES ('Alice') RETURNING *
if let player = try partialPlayer.insertAndFetch(db, as: Player.self) {
print(player.id) // The inserted id
print(player.name) // The inserted name
print(player.score) // The default score
}
}
```
If you use the raw [PersistableRecord] protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`:
For extra precision, you can select only the columns you need, and fetch the desired value from the provided [prepared statement](#prepared-statements):
```swift
struct Link : PersistableRecord {
try dbQueue.write { db in
let partialPlayer = PartialPlayer(name: "Alice")
// INSERT INTO player (name) VALUES ('Alice') RETURNING score
let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
try Int.fetchOne(statement)
}
print(score) // Prints 1000, the default score
}
```
There are other similar persistence methods, such as `saveAndFetch`, `updateAndFetch`, `updateChangesAndFetch`, etc. They all behave like `save`, `update`, `updateChanges` (see [Persistence Methods] and the [`updateChanges` methods](#the-updatechanges-methods)), except that they return saved values. For example:
```swift
// Save and return the saved player
let savedPlayer = try player.saveAndFetch(db)
```
**Batch operations** can return updated or deleted values:
> :warning: **Warning**: Make sure you check the [documentation of the `RETURNING` clause](https://www.sqlite.org/lang_returning.html), which describes important limitations and caveats for batch operations.
```swift
let request = Player.filter(...)...
// Fetch all deleted players
// DELETE FROM player RETURNING *
let deletedPlayers = try request.deleteAndFetchAll(db) // [Player]
// Fetch a selection of columns from the deleted rows
// DELETE FROM player RETURNING name
let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")])
let deletedNames = try String.fetchSet(statement)
// Fetch all updated players
// UPDATE player SET score = score + 10 RETURNING *
let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) // [Player]
// Fetch a selection of columns from the updated rows
// UPDATE player SET score = score + 10 RETURNING score
let statement = try request.updateAndFetchStatement(
db, [Column("score") += 10],
select: [Column("score")])
let updatedScores = try Int.fetchAll(statement)
```
### Persistence Callbacks
Your custom type may want to perform extra work when the persistence methods are invoked.
To this end, your record type can implement **persistence callbacks**. Callbacks are methods that get called at certain moments of a record's life cycle. With callbacks it is possible to write code that will run whenever an record is inserted, updated, or deleted.
In order to use a callback method, you need to provide its implementation. For example, a frequently used callback is `didInsert`, in the case of auto-incremented database ids:
```swift
struct Player: MutablePersistableRecord {
var id: Int64?
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
try dbQueue.write { db in
var player = Player(id: nil, ...)
try player.insert(db)
print(player.id) // didInsert was called: prints some non-nil id
}
```
When you subclass the [Record](#record-class) class, override the callback, and make sure you call `super` at some point of your implementation:
```swift
class Player: Record {
var id: Int64?
// Update auto-incremented id upon successful insertion
func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
```
Callbacks can also help implementing record validation:
```swift
struct Link: PersistableRecord {
var url: URL
func insert(_ db: Database) throws {
try validate()
try performInsert(db)
}
func update(_ db: Database, columns: Set<String>) throws {
try validate()
try performUpdate(db, columns: columns)
}
func validate() throws {
func willSave(_ db: Database) throws {
if url.host == nil {
throw ValidationError("url must be absolute.")
}
}
}
try link.insert(db) // Calls the willSave callback
try link.update(db) // Calls the willSave callback
try link.save(db) // Calls the willSave callback
try link.upsert(db) // Calls the willSave callback
```
> :point_up: **Note**: the special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods.
>
> :point_up: **Note**: it is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`.
#### Available Callbacks
Here is a list with all the available callbacks, listed in the same order in which they will get called during the respective operations:
- Inserting a record (all `record.insert` methods)
- `willSave`
- `aroundSave`
- `willInsert`
- `aroundInsert`
- `didInsert`
- `didSave`
- Updating a record (all `record.update` methods)
- `willSave`
- `aroundSave`
- `willUpdate`
- `aroundUpdate`
- `didUpdate`
- `didSave`
- Deleting a record (only the `record.delete(_:)` method)
- `willDelete`
- `aroundDelete`
- `didDelete`
Make sure you provide implementations that match the exact callback signatures. When in doubt, check the [reference](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/MutablePersistableRecord.html).
In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mutating methods. In `PersistableRecord`, they are not mutating.
> :point_up: **Note**: The `record.save(_:)` method performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly performs an INSERT if the record has no primary key, or a null primary key. It triggers update and/or insert callbacks accordingly.
>
> :warning: **Warning**: Callbacks are only invoked from persistence methods called on record instances. Callbacks are not invoked when you call a type method, perform a batch operations, or execute raw SQL.
>
> :warning: **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle committed changes, use the [After Commit Hook](#after-commit-hook).
## Identifiable Records
@@ -3354,8 +3502,9 @@ class Place: Record {
}
/// Update record ID after a successful insertion
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
```
@@ -3392,7 +3541,7 @@ The `updateChanges` methods perform a database update of the changed columns onl
}
```
- `updateChanges(_:with:)`
- `updateChanges(_:modify:)`
This method lets you update a record in place:
@@ -3501,7 +3650,7 @@ For an efficient algorithm which synchronizes the content of a database table wi
GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs:
- [Customizing the Persistence Methods]: define what happens when you call a persistence method such as `player.insert(db)`
- [Persistence Callbacks]: define what happens when you call a persistence method such as `player.insert(db)`
- [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index.
- [The Implicit RowID Primary Key]: all about the special `rowid` column.
- [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`.
@@ -3560,7 +3709,7 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab
try db.execute(sql: "INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"])
```
When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods):
When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods]:
```swift
protocol MutablePersistableRecord {
@@ -3583,10 +3732,17 @@ struct Player : MutablePersistableRecord {
try player.insert(db)
```
> :point_up: **Note**: the `ignore` policy does not play well at all with the `didInsert` method which notifies the rowID of inserted records. Choose your poison:
>
> - if you specify the `ignore` policy in the database table definition, don't implement the `didInsert` method: it will be called with some random id in case of failed insert.
> - if you specify the `ignore` policy at the query level, the `didInsert` method is never called.
> :point_up: **Note**: If you specify the `ignore` policy for inserts, the [`didInsert` callback](#persistence-callbacks) will be called with some random id in case of failed insert. You can detect failed insertions with `insertAndFetch`:
>
> ```swift
> // How to detect failed `INSERT OR IGNORE`:
> // INSERT OR IGNORE INTO player ... RETURNING *
> if let insertedPlayer = try player.insertAndFetch(db) {
> // Succesful insertion
> } else {
> // Ignored failure
> }
> ```
>
> :point_up: **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](#transactionobserver-protocol) (this might change in a future release of SQLite).
@@ -3672,7 +3828,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc
event.id // some value
```
3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols):
3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(_:)` callback (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols):
```swift
struct Event : MutablePersistableRecord {
@@ -3685,8 +3841,8 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc
}
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
@@ -3784,8 +3940,8 @@ extension Place: FetchableRecord { }
// Persistence methods
extension Place: MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
@@ -3838,8 +3994,8 @@ extension Place: MutablePersistableRecord {
}
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
@@ -3912,8 +4068,8 @@ extension Place: FetchableRecord {
// Persistence methods
extension Place: MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
@@ -3969,8 +4125,9 @@ class Place: Record {
}
// Update auto-incremented id upon successful insertion
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
```
@@ -3990,16 +4147,27 @@ This is the list of record methods, along with their required protocols. The [Re
| `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) |
| `Type.persistenceConflictPolicy` | [PersistableRecord] | [*](#conflict-resolution) |
| `record.encode(to:)` | [EncodableRecord] | |
| `record.didInsert(with:for:)` | [PersistableRecord] | |
| **Insert and Update Records** | | |
| `record.insert(db)` | [PersistableRecord] | |
| `record.insertAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | |
| `record.insertAndFetch(_:as:)` | [PersistableRecord] | |
| `record.insertAndFetch(_:selection:fetch:)` | [PersistableRecord] | |
| `record.inserted(db)` | [PersistableRecord] | |
| `record.save(db)` | [PersistableRecord] | |
| `record.saveAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | |
| `record.saveAndFetch(_:as:)` | [PersistableRecord] | |
| `record.saveAndFetch(_:selection:fetch:)` | [PersistableRecord] | |
| `record.saved(db)` | [PersistableRecord] | |
| `record.update(db)` | [PersistableRecord] | |
| `record.updateAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | |
| `record.updateAndFetch(_:as:)` | [PersistableRecord] | |
| `record.updateAndFetch(_:selection:fetch:)` | [PersistableRecord] | |
| `record.update(db, columns:...)` | [PersistableRecord] | |
| `record.updateAndFetch(_:columns:selection:fetch:)` | [PersistableRecord] | |
| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) |
| `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) |
| `record.updateChangesAndFetch(_:columns:as:modify:)` | [PersistableRecord] | |
| `record.updateChangesAndFetch(_:columns:selection:fetch:modify:)` | [PersistableRecord] | |
| `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) |
| `Type.updateAll(db, ...)` | [TableRecord] | |
| `Type.filter(...).updateAll(db, ...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
@@ -4011,6 +4179,19 @@ This is the list of record methods, along with their required protocols. The [Re
| `Type.deleteAll(db, keys:...)` | [TableRecord] | <a href="#list-of-record-methods-1">¹</a> |
| `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | <a href="#list-of-record-methods-1">¹</a> |
| `Type.filter(...).deleteAll(db)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| **Persistence Callbacks** | | |
| `record.willInsert(_:)` | [PersistableRecord] | |
| `record.aroundInsert(_:insert:)` | [PersistableRecord] | |
| `record.didInsert(_:)` | [PersistableRecord] | |
| `record.willUpdate(_:columns:)` | [PersistableRecord] | |
| `record.aroundUpdate(_:columns:update:)` | [PersistableRecord] | |
| `record.didUpdate(_:)` | [PersistableRecord] | |
| `record.willSave(_:)` | [PersistableRecord] | |
| `record.aroundSave(_:save:)` | [PersistableRecord] | |
| `record.didSave(_:)` | [PersistableRecord] | |
| `record.willDelete(_:)` | [PersistableRecord] | |
| `record.aroundDelete(_:delete:)` | [PersistableRecord] | |
| `record.didDelete(deleted:)` | [PersistableRecord] | |
| **Check Record Existence** | | |
| `record.exists(db)` | [PersistableRecord] | |
| `Type.exists(db, key: ...)` | [TableRecord] | <a href="#list-of-record-methods-1">¹</a> |
@@ -8432,6 +8613,10 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0.
This protocol has been renamed [TableRecord] in GRDB 3.0.
#### Customizing the Persistence Methods
This chapter was replaced with [Persistence Callbacks].
#### ValueObservation and DatabaseRegionObservation
This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation].
@@ -8480,7 +8665,6 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[common table expression]: Documentation/CommonTableExpressions.md
[Common Table Expressions]: Documentation/CommonTableExpressions.md
[Conflict Resolution]: #conflict-resolution
[Customizing the Persistence Methods]: #customizing-the-persistence-methods
[Column Names Coding Strategies]: #column-names-coding-strategies
[Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies
[Fetching from Requests]: #fetching-from-requests
@@ -8495,6 +8679,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[PersistableRecord]: #persistablerecord-protocol
[Record Comparison]: #record-comparison
[Record Customization Options]: #record-customization-options
[Persistence Callbacks]: #persistence-callbacks
[TableRecord]: #tablerecord-protocol
[ValueObservation]: #valueobservation
[DatabaseRegionObservation]: #databaseregionobservation
@@ -8516,3 +8701,5 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
[Database Configuration]: #database-configuration
[Persistence Methods]: #persistence-methods
[persistence methods]: #persistence-methods
+6 -3
View File
@@ -35,6 +35,9 @@
- [X] throwing Decodable FetchableRecord initializer SECOND
- [X] deal with as much value decoding error as possible
- [?] expose throwing row accessors
- [ ] GRDB 6: Batch insert & Batch insert RETURNING - https://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database
- [ ] GRDB 6: INSERT or UPDATE columns to their default value
- [ ] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:)
- [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`)
- [ ] throwing EncodableRecord.encode FIRST
- [?] GRDB 6: protocol-based record container? This could avoid computing & encoding values we do not need.
@@ -45,10 +48,10 @@
- [X] GRDB 6: primary associated types (cursor, requests, ...)
- [X] GRDB 6: remove existential/generic duplicated methods
- [ ] GRDB 6: remove useless AnyXXX Type erasers
- [ ] GRDB 6: conflict resolution in persistence methods
- [X] GRDB 6: conflict resolution in persistence methods
- [ ] GRDB 6: UPSERT
- [ ] GRDB 6: support for RETURNING
- [ ] Support for default values: `Player.insert(db, returning: FullPlayer.self)` ?
- [X] GRDB 6: support for RETURNING
- [X] Support for default values: `Player.insert(db, as: FullPlayer.self)`
- [?] GRDB 6: allow mutating `update` (for timestamps)
- [?] GRDB 6: let record choose persistence table (insert(into:) ?)
- [?] GRDB 6: Support opaque return types (macOS Catalina, iOS 13, tvOS 13, watchOS 6 and later: https://stackoverflow.com/questions/56518406)
+48 -4
View File
@@ -12,8 +12,52 @@ private class UserRecord : Record {
override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy }
override class var databaseSelection: [any SQLSelectable] { super.databaseSelection }
override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) }
override func didInsert(with rowID: Int64, for column: String?) { super.didInsert(with: rowID, for: column) }
override func insert(_ db: Database) throws { try super.insert(db) }
override func update(_ db: Database, columns: Set<String>) throws { try super.update(db, columns: columns) }
override func delete(_ db: Database) throws -> Bool { try super.delete(db) }
override func willInsert(_ db: Database) throws {
try super.willInsert(db)
}
override func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
try super.aroundInsert(db, insert: insert)
}
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
}
override func willUpdate(_ db: Database, columns: Set<String>) throws {
try super.willUpdate(db, columns: columns)
}
override func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
try super.aroundUpdate(db, columns: columns, update: update)
}
override func didUpdate(_ updated: PersistenceSuccess) {
super.didUpdate(updated)
}
override func willSave(_ db: Database) throws {
try super.willSave(db)
}
override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws {
try super.aroundSave(db, save: save)
}
override func didSave(_ saved: PersistenceSuccess) {
super.didSave(saved)
}
override func willDelete(_ db: Database) throws {
try super.willDelete(db)
}
override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws {
try super.aroundDelete(db, delete: delete)
}
override func didDelete(deleted: Bool) {
super.didDelete(deleted: deleted)
}
}
+2 -2
View File
@@ -128,8 +128,8 @@ class DatabaseCursorTests: GRDBTestCase {
self.isFlagged = isFlagged
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
+2 -2
View File
@@ -28,8 +28,8 @@ extension Book : MutablePersistableRecord {
container["body"] = body
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
+2 -2
View File
@@ -28,8 +28,8 @@ extension Book : MutablePersistableRecord {
container["body"] = body
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
+2 -2
View File
@@ -29,8 +29,8 @@ extension Book : MutablePersistableRecord {
container["body"] = body
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -24,8 +24,8 @@ extension Reader : MutablePersistableRecord {
container["age"] = age
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -16,15 +16,14 @@ private struct Player: FetchableRecord, MutablePersistableRecord, Codable {
self.creationDate = creationDate
}
mutating func insert(_ db: Database) throws {
mutating func willInsert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try performInsert(db)
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -302,8 +301,9 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
container[Columns.lastName] = lastName
}
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
@@ -315,8 +315,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
t.column("lastName", .text)
}
// This `let` is part of the test
let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith")
var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith")
try record.insert(db)
do {
@@ -375,8 +374,8 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
self.lastName = lastName
}
func didInsert(with rowID: Int64, for column: String?) {
id = rowID
func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -388,8 +387,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
t.column("lastName", .text)
}
// This `let` is part of the test
let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith")
var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith")
try record.insert(db)
do {
@@ -442,8 +440,8 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
var firstName: String?
var lastName: String?
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -10,8 +10,8 @@ private struct DefaultPolicy: MutablePersistableRecord {
container["id"] = id
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -25,8 +25,8 @@ private struct MixedPolicy: MutablePersistableRecord {
container["id"] = id
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -42,8 +42,8 @@ private struct ReplacePolicy: MutablePersistableRecord {
container["email"] = email
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -57,8 +57,8 @@ private struct IgnorePolicy: MutablePersistableRecord {
container["id"] = id
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -72,8 +72,8 @@ private struct FailPolicy: MutablePersistableRecord {
container["id"] = id
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -87,8 +87,8 @@ private struct AbortPolicy: MutablePersistableRecord {
container["id"] = id
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -102,8 +102,8 @@ private struct RollbackPolicy: MutablePersistableRecord {
container["id"] = id
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -134,6 +134,25 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE \"records\""))
}
}
func testPolicyOverride() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
t.column("id", .integer).primaryKey()
}
// Insert
var record = DefaultPolicy(id: nil)
try record.insert(db, onConflict: .ignore)
XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR IGNORE INTO \"records\""))
// Update
record = DefaultPolicy(id: 1)
try record.update(db, onConflict: .ignore)
XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR IGNORE \"records\""))
}
}
func testMixedPolicy() throws {
let dbQueue = try makeDatabaseQueue()
@@ -242,7 +261,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
var record = IgnorePolicy(id: nil)
try record.insert(db)
XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR IGNORE INTO \"records\""))
XCTAssertTrue(record.id == nil)
XCTAssertEqual(record.id, 1)
// Update
record = IgnorePolicy(id: 1)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -30,8 +30,9 @@ private class Reader : Record {
container["age"] = age
}
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
+11 -13
View File
@@ -46,17 +46,16 @@ private class Person : Record {
container["creationDate"] = creationDate
}
override func insert(_ db: Database) throws {
// This is implicitly tested with the NOT NULL constraint on creationDate
override func willInsert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try super.insert(db)
try super.willInsert(db)
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
@@ -115,17 +114,16 @@ private class PersonWithModifiedCaseColumns: Record {
container["CREATIONDATE"] = creationDate
}
override func insert(_ db: Database) throws {
// This is implicitly tested with the NOT NULL constraint on creationDate
override func willInsert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try super.insert(db)
try super.willInsert(db)
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
@@ -672,7 +670,7 @@ class RecordEditedTests: GRDBTestCase {
XCTAssertTrue(person.hasDatabaseChanges)
try person.updateChanges(db)
XCTFail("Expected PersistenceError")
} catch is PersistenceError { }
} catch PersistenceError.recordNotFound(databaseTableName: "persons", key: ["id": .null]) { }
try person.insert(db)
@@ -31,8 +31,9 @@ class MinimalRowID : Record, Hashable {
container["id"] = id
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
static func == (lhs: MinimalRowID, rhs: MinimalRowID) -> Bool {
@@ -50,17 +50,16 @@ private class Person : Record, Hashable {
container["creationDate"] = creationDate
}
override func insert(_ db: Database) throws {
// This is implicitly tested with the NOT NULL constraint on creationDate
override func willInsert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try super.insert(db)
try super.willInsert(db)
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
static func == (lhs: Person, rhs: Person) -> Bool {
@@ -39,8 +39,9 @@ private class Item : Record, Hashable {
container["email"] = email
}
override func didInsert(with rowID: Int64, for column: String?) {
insertedRowIDColumn = column
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
insertedRowIDColumn = inserted.rowIDColumn
}
static func == (lhs: Item, rhs: Item) -> Bool {
@@ -47,17 +47,16 @@ private class Person : Record, Hashable {
container["creationDate"] = creationDate
}
override func insert(_ db: Database) throws {
// This is implicitly tested with the NOT NULL constraint on creationDate
override func willInsert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try super.insert(db)
try super.willInsert(db)
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
static func == (lhs: Person, rhs: Person) -> Bool {
+9 -10
View File
@@ -46,17 +46,16 @@ private class Person : Record {
container["creationDate"] = creationDate
}
override func insert(_ db: Database) throws {
// This is implicitly tested with the NOT NULL constraint on creationDate
override func willInsert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try super.insert(db)
try super.willInsert(db)
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
@@ -91,14 +90,14 @@ private class PersonWithOverrides : Person {
try super.init(row: row)
}
override func insert(_ db: Database) throws {
override func willInsert(_ db: Database) throws {
lastSavingMethod = .insert
try super.insert(db)
try super.willInsert(db)
}
override func update(_ db: Database, columns: Set<String>) throws {
override func willUpdate(_ db: Database, columns: Set<String>) throws {
lastSavingMethod = .update
try super.update(db, columns: columns)
try super.willUpdate(db, columns: columns)
}
}
@@ -38,8 +38,9 @@ class BadlyMangledStuff : Record {
container["name"] = name
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
override func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
+293 -4
View File
@@ -9,9 +9,11 @@ private struct Hacker : TableRecord {
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension Hacker: Identifiable { }
private struct Person : TableRecord {
private struct Person : Codable, PersistableRecord, FetchableRecord, Hashable {
static let databaseTableName = "persons"
var id: Int64 // Non-optional
var name: String
var email: String
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
@@ -172,7 +174,7 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDelete() throws {
func testRequestDeleteAll() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -227,7 +229,118 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testJoinedRequestDelete() throws {
func testRequestDeleteAndFetchStatement() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Person.all()
let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING *")
XCTAssertEqual(statement.columnNames, ["id", "name", "email"])
}
}
func testRequestDeleteAndFetchCursor() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
_ = try Person.all().deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *")
_ = try Person.all().deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *")
_ = try Person.filter(Column("name") == "Arthur").deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"name\" = 'Arthur' RETURNING *")
_ = try Person.filter(key: 1).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *")
_ = try Person.filter(keys: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) {
_ = try Person.filter(id: 1).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *")
_ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
}
_ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *")
_ = try Person.filter(sql: "id = 1").filter(Column("name") == "Arthur").deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (id = 1) AND (\"name\" = 'Arthur') RETURNING *")
_ = try Person.select(Column("name")).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *")
_ = try Person.order(Column("name")).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *")
// No test for LIMIT ... RETURNING ... since this is not supported by SQLite
}
}
func testRequestDeleteAndFetchArray() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try Person(id: 1, name: "Arthur", email: "arthur@example.com").insert(db)
try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db)
try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db)
let request = Person.filter(Column("id") != 2)
let deletePersons = try request
.deleteAndFetchAll(db)
.sorted(by: { $0.id < $1.id })
XCTAssertEqual(deletePersons, [
Person(id: 1, name: "Arthur", email: "arthur@example.com"),
Person(id: 3, name: "Craig", email: "craig@example.com"),
])
}
}
func testRequestDeleteAndFetchSet() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try Person(id: 1, name: "Arthur", email: "arthur@example.com").insert(db)
try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db)
try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db)
let request = Person.filter(Column("id") != 2)
let deletePersons = try request.deleteAndFetchSet(db)
XCTAssertEqual(deletePersons, [
Person(id: 1, name: "Arthur", email: "arthur@example.com"),
Person(id: 3, name: "Craig", email: "craig@example.com"),
])
}
}
func testJoinedRequestDeleteAll() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
static let team = belongsTo(Team.self)
@@ -287,7 +400,105 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testGroupedRequestDelete() throws {
func testJoinedRequestDeleteAndFetch() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord, FetchableRecord {
static let team = belongsTo(Team.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
init(row: Row) { preconditionFailure("should not be called") }
}
struct Team: MutablePersistableRecord, FetchableRecord {
// Test RETURNING
static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")]
static let players = hasMany(Player.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
init(row: Row) { preconditionFailure("should not be called") }
}
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
}
do {
let request = Player.including(required: Player.team)
let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
XCTAssertEqual(statement.sql, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId") \
RETURNING *
""")
XCTAssertEqual(statement.columnNames, ["id", "teamId"])
_ = try request.deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId") \
RETURNING *
""")
}
do {
let alias = TableAlias(name: "p")
_ = try Player.aliased(alias).including(required: Player.team).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "p"."id" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId") \
RETURNING *
""")
}
do {
let request = Team.having(Team.players.isEmpty)
let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
XCTAssertEqual(statement.sql, """
DELETE FROM "team" WHERE "id" IN (\
SELECT "team"."id" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."id") = 0) \
RETURNING *
""")
XCTAssertEqual(statement.columnNames, ["id", "name"])
_ = try request.deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "team" WHERE "id" IN (\
SELECT "team"."id" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."id") = 0) \
RETURNING "id", "name"
""")
}
do {
_ = try Team.including(all: Team.players).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "team" RETURNING "id", "name"
""")
}
}
}
func testGroupedRequestDeleteAll() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
@@ -351,4 +562,82 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
}
func testGroupedRequestDeleteAndFetchCursor() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord, FetchableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
init(row: Row) { preconditionFailure("should not be called") }
}
struct Passport: MutablePersistableRecord, FetchableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
init(row: Row) { preconditionFailure("should not be called") }
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("score", .integer)
}
try db.create(table: "passport") { t in
t.column("countryCode", .text).notNull()
t.column("citizenId", .integer).notNull()
t.primaryKey(["countryCode", "citizenId"])
}
do {
_ = try Player.all().groupByPrimaryKey().deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "id") \
RETURNING *
""")
}
do {
_ = try Player.all().group(-Column("id")).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY -"id") \
RETURNING *
""")
}
do {
_ = try Player.all().group(Column.rowID).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "rowid") \
RETURNING *
""")
}
do {
_ = try Passport.all().groupByPrimaryKey().deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid") \
RETURNING *
""")
}
do {
_ = try Passport.all().group(Column.rowID).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid") \
RETURNING *
""")
}
}
}
}
+89 -1
View File
@@ -1,7 +1,7 @@
import XCTest
import GRDB
private struct Player: Codable, TableRecord, FetchableRecord {
private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable {
var id: Int64
var name: String
var score: Int
@@ -117,6 +117,94 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchStatement() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
let assignment = Columns.score.set(to: 0)
let request = Player.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [AllColumns()])
XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
}
}
func testRequestUpdateAndFetchCursor() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = Player.filter(Columns.id != 2)
let cursor = try request.updateAndFetchCursor(db, [Columns.score += 100])
let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
Player(id: 1, name: "Arthur", score: 110, bonus: 0),
Player(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchAll() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = Player.filter(Columns.id != 2)
let updatedPlayers = try request
.updateAndFetchAll(db, [Columns.score += 100])
.sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
Player(id: 1, name: "Arthur", score: 110, bonus: 0),
Player(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchSet() throws {
#if !GRDBCUSTOMSQLITE
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = Player.filter(Columns.id != 2)
let updatedPlayers = try request.updateAndFetchSet(db, [Columns.score += 100])
XCTAssertEqual(updatedPlayers, [
Player(id: 1, name: "Arthur", score: 110, bonus: 0),
Player(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testNilAssignment() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
@@ -96,8 +96,8 @@ private final class Artist: Codable {
extension Artist : FetchableRecord, PersistableRecord {
static let databaseTableName = "artists"
func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -115,8 +115,8 @@ private final class Artwork : Codable {
extension Artwork : FetchableRecord, PersistableRecord {
static let databaseTableName = "artworks"
func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}