diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1e4a0a5..c0903f780 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift index 609df14a0..8513cd480 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift @@ -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 } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 609df14a0..8513cd480 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift @@ -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 } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index cacb7112d..7c82fe2cf 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -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 } } diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 05bb3b87f..d303e66ca 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -110,7 +110,135 @@ The record protocols have been refactored. We tried to keep the amount of modifi +- **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) 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: diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 284ce79af..817c2c8ea 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -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 diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index 66be6ed96..61040d563 100644 --- a/Documentation/Playgrounds/Associations.playground/Contents.swift +++ b/Documentation/Playgrounds/Associations.playground/Contents.swift @@ -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 } } diff --git a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift index f815d8f1e..d02e45194 100644 --- a/Documentation/Playgrounds/MyPlayground.playground/Contents.swift +++ b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift @@ -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 } } diff --git a/Documentation/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift index c79f27742..e6f7e4f20 100644 --- a/Documentation/Playgrounds/Tour.playground/Contents.swift +++ b/Documentation/Playgrounds/Tour.playground/Contents.swift @@ -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 } } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f75ca7afa..c382a4aae 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 5611620725757583007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = ""; }; 5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; @@ -1627,6 +1659,14 @@ 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = ""; }; 56CEB5401EAA359A00BFAF62 /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = ""; }; 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = ""; }; + 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = ""; }; + 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = ""; }; + 56D110D228AFC81400E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; @@ -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 */, diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 71a09b25e..6753069ae 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -67,9 +67,37 @@ extension DatabaseUUIDEncodingStrategy { @available(*, unavailable, message: "FastNullableDatabaseValueCursor has been replaced with FastDatabaseValueCursor") typealias FastNullableDatabaseValueCursor = FastDatabaseValueCursor +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) 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 has been replaced with DatabaseValueCursor") typealias NullableDatabaseValueCursor = DatabaseValueCursor +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.") diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index e94aa77b4..65bf9c0b2 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + 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: + /// . + /// + /// - 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: + /// . + /// + /// - 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 + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) + } +#endif +} + // MARK: - ColumnAssignment /// A ColumnAssignment can update rows in the database. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 2169b7a17..b4b0b5518 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -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) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 289decc5d..7b62a139d 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -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 { diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index ab5fefb52..907510bf9 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -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 { diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift new file mode 100644 index 000000000..baca79221 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -0,0 +1,273 @@ +/// DAO takes care of MutablePersistableRecord CRUD +final class DAO { + /// 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, + 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))" + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Delete.swift b/GRDB/Record/MutablePersistableRecord+Delete.swift new file mode 100644 index 000000000..70fd722e6 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Delete.swift @@ -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 + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift new file mode 100644 index 000000000..13d3a67fe --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -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( + _ 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( + _ 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( + _ 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( + _ 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( + _ 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( + _ 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) + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift new file mode 100644 index 000000000..fc4435da7 --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -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( + _ 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( + _ 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( + _ 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( + _ 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( + _ 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 + } +} diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift new file mode 100644 index 000000000..bc272c3ce --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -0,0 +1,842 @@ +// MARK: - Update Callbacks + +extension MutablePersistableRecord { + @inline(__always) + @inlinable + public func willUpdate(_ db: Database, columns: Set) throws { } + + @inline(__always) + @inlinable + public func aroundUpdate(_ db: Database, columns: Set, 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) + 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) + 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( + _ 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( + _ 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( + _ 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( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + 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( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + 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( + _ 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( + _ 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( + _ 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( + _ 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( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + 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( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + columns: some Sequence, + 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( + _ 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( + _ 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( + _ 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 = 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( + _ 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 = 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) + 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( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + columns: Set, + 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( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution?, + columns: Set, + 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 = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return false + } + try update(db, onConflict: conflictResolution, columns: changedColumns) + return true + } +} diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift new file mode 100644 index 000000000..60a7822fa --- /dev/null +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -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 + 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) 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, 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, 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 +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 . + 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) + } +} diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift new file mode 100644 index 000000000..924a5aaa5 --- /dev/null +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -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( + _ 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( + _ 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( + _ 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( + _ 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( + _ 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) + } +} diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift new file mode 100644 index 000000000..b33599474 --- /dev/null +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -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( + _ 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( + _ 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( + _ 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( + _ 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( + _ 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) + } +} diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index df5408616..a5c6b3119 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -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 -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 - 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) 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) 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) 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) 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(_ 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 = 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) 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 { - /// 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, 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) } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index a0006c135..d60ef25f4 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -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 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) 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, 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, 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) 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) - } } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 944da1316..0ab4f951f 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -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) 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) 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) } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3eb4a0ee5..ebf65f587 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -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 = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561162692576BF9C007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = ""; }; 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; @@ -1116,6 +1131,15 @@ 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; + 56D110E128AFC90800E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = ""; }; + 56D110E228AFC90800E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110E328AFC90800E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = ""; }; + 56D110E428AFC90800E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110E528AFC90800E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; + 56D110E628AFC90800E64463 /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = ""; }; + 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = ""; }; + 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = ""; }; + 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; @@ -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 */, diff --git a/README.md b/README.md index cf7eccb9e..342e8f509 100644 --- a/README.md +++ b/README.md @@ -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) 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] | ² | @@ -4011,6 +4179,19 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.deleteAll(db, keys:...)` | [TableRecord] | ¹ | | `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | ¹ | | `Type.filter(...).deleteAll(db)` | [TableRecord] | ² | +| **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] | ¹ | @@ -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 diff --git a/TODO.md b/TODO.md index ce48515ae..2c939485a 100644 --- a/TODO.md +++ b/TODO.md @@ -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) diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 5e5a2a485..c722356a1 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -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) 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) throws { + try super.willUpdate(db, columns: columns) + } + + override func aroundUpdate(_ db: Database, columns: Set, 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) + } } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 4faf542cd..d18191488 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 6baea9ffd..036fb5da4 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index f23a989b7..f6c2eb6f0 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 8ebc2804a..eac65c0a2 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 4d19279bf..8fd39c92b 100644 --- a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index d1a4f6e74..e6f2a249e 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index ddf471bb2..1caa68b1c 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -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) diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index fd7e0708c..6660e8d83 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -15,8 +15,19 @@ private struct MutablePersistableRecordPerson : MutablePersistableRecord { container["aGe"] = age } - mutating func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + let inserted = try insert() + XCTAssertNotNil(inserted.rowID) + XCTAssertEqual(inserted.rowIDColumn, "id") + XCTAssertEqual(inserted.persistenceContainer["iD"]?.databaseValue, inserted.rowID.databaseValue) + XCTAssertEqual(inserted.persistenceContainer["id"]?.databaseValue, inserted.rowID.databaseValue) + } + + mutating func didInsert(_ inserted: InsertionSuccess) { + XCTAssertEqual(inserted.rowIDColumn, "id") + XCTAssertEqual(inserted.persistenceContainer["iD"]?.databaseValue, inserted.rowID.databaseValue) + XCTAssertEqual(inserted.persistenceContainer["id"]?.databaseValue, inserted.rowID.databaseValue) + id = inserted.rowID } } @@ -32,20 +43,39 @@ private struct MutablePersistableRecordCountry : MutablePersistableRecord { container["name"] = name } - mutating func didInsert(with rowID: Int64, for column: String?) { - self.rowID = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + XCTAssertNil(inserted.rowIDColumn) + rowID = inserted.rowID } } +private class Callbacks { + var willInsertCount = 0 + var aroundInsertEnterCount = 0 + var aroundInsertExitCount = 0 + var didInsertCount = 0 + + var willUpdateCount = 0 + var aroundUpdateEnterCount = 0 + var aroundUpdateExitCount = 0 + var didUpdateCount = 0 + + var willSaveCount = 0 + var aroundSaveEnterCount = 0 + var aroundSaveExitCount = 0 + var didSaveCount = 0 + + var willDeleteCount = 0 + var aroundDeleteEnterCount = 0 + var aroundDeleteExitCount = 0 + var didDeleteCount = 0 +} + private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRecord { var rowID: Int64? var isoCode: String var name: String - let willInsert: () -> Void - let willUpdate: () -> Void - let willSave: () -> Void - let willDelete: () -> Void - let willExists: () -> Void + let callbacks = Callbacks() static let databaseTableName = "countries" @@ -54,33 +84,219 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec container["name"] = name } - mutating func didInsert(with rowID: Int64, for column: String?) { - self.rowID = rowID + mutating func willInsert(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willInsertCount += 1 } - mutating func insert(_ db: Database) throws { - willInsert() - try performInsert(db) + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 } - func update(_ db: Database, columns: Set) throws { - willUpdate() - try performUpdate(db, columns: columns) + mutating func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 + rowID = inserted.rowID } - mutating func save(_ db: Database) throws { - willSave() - try performSave(db) + func willUpdate(_ db: Database, columns: Set) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willUpdateCount += 1 } - func delete(_ db: Database) throws -> Bool { - willDelete() - return try performDelete(db) + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 } - func exists(_ db: Database) throws -> Bool { - willExists() - return try performExists(db) + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + +private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord { + static let databaseTableName = "player" + let callbacks = Callbacks() + var id: Int64? + var name: String + + enum CodingKeys: String, CodingKey { + case id, name + } + + mutating func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + +private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { + static let databaseTableName = "player" + var id: Int64? + var name: String + var score: Int + + enum CodingKeys: String, CodingKey { + case id, name, score + } + + let callbacks = Callbacks() + + mutating func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 } } @@ -97,12 +313,15 @@ class MutablePersistableRecordTests: GRDBTestCase { CREATE TABLE countries ( isoCode TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL); + CREATE TABLE player( + id INTEGER PRIMARY KEY, + name NOT NULL, + score INTEGER NOT NULL DEFAULT 1000); """) } try migrator.migrate(dbWriter) } - // MARK: - MutablePersistableRecordPerson func testInsertMutablePersistableRecordPerson() throws { @@ -143,7 +362,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertTrue([ "UPDATE \"persons\" SET \"age\"=24, \"name\"='Craig' WHERE \"id\"=1", "UPDATE \"persons\" SET \"name\"='Craig', \"age\"=24 WHERE \"id\"=1" - ].contains(self.lastSQLQuery)) + ].contains(self.lastSQLQuery)) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) @@ -153,7 +372,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + func testPartialUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -209,7 +428,7 @@ class MutablePersistableRecordTests: GRDBTestCase { } } } - + func testSaveMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -301,7 +520,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Barbara") } } - + func testExistsMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -319,7 +538,7 @@ class MutablePersistableRecordTests: GRDBTestCase { let dict = person.databaseDictionary XCTAssertEqual(dict, ["iD": DatabaseValue.null, "NAme": "Arthur".databaseValue, "aGe": 24.databaseValue]) } - + // MARK: - MutablePersistableRecordCountry func testInsertMutablePersistableRecordCountry() throws { @@ -367,7 +586,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testSaveMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -458,7 +677,7 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -470,34 +689,37 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertFalse(try country.exists(db)) } } - - + // MARK: - MutablePersistableRecordCustomizedCountry func testInsertMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries") XCTAssertEqual(rows.count, 1) @@ -505,45 +727,44 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + func testUpdateMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 2) @@ -553,31 +774,70 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + + func testPersistenceErrorMutablePersistableRecordCustomizedCountry() throws { + let country = MutablePersistableRecordCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France") + + let dbQueue = try makeDatabaseQueue() + do { + try dbQueue.inDatabase { db in + try country.update(db) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "countries", key: ["isoCode": "FR".databaseValue]) { } + + XCTAssertEqual(country.callbacks.willInsertCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(country.callbacks.didInsertCount, 0) + + XCTAssertEqual(country.callbacks.willUpdateCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didSaveCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) + } + func testSaveMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 1) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) var rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries") XCTAssertEqual(rows.count, 1) @@ -587,22 +847,31 @@ class MutablePersistableRecordTests: GRDBTestCase { var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 2) - XCTAssertEqual(saveCount, 2) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 2) @@ -614,11 +883,25 @@ class MutablePersistableRecordTests: GRDBTestCase { _ = try country1.delete(db) try country1.save(db) - XCTAssertEqual(insertCount, 2) - XCTAssertEqual(updateCount, 3) - XCTAssertEqual(saveCount, 3) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 2) + XCTAssertEqual(country1.callbacks.didInsertCount, 2) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 3) + XCTAssertEqual(country1.callbacks.didSaveCount, 3) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country1.callbacks.didDeleteCount, 1) rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 2) @@ -628,34 +911,19 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "France Métropolitaine") } } - + func testDeleteMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -663,11 +931,25 @@ class MutablePersistableRecordTests: GRDBTestCase { deleted = try country1.delete(db) XCTAssertFalse(deleted) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 2) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 2) + XCTAssertEqual(country1.callbacks.didDeleteCount, 2) let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") XCTAssertEqual(rows.count, 1) @@ -675,41 +957,61 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 1) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) _ = try country.delete(db) XCTAssertFalse(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 2) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country.callbacks.didDeleteCount, 1) } } @@ -727,8 +1029,8 @@ class MutablePersistableRecordTests: GRDBTestCase { container["a"] = a } - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -806,9 +1108,9 @@ class MutablePersistableRecordTests: GRDBTestCase { } func testGeneratedColumnsInsertIsAnError() throws { - #if !GRDBCUSTOMSQLITE +#if !GRDBCUSTOMSQLITE throw XCTSkip("Generated columns are not available") - #else +#else struct T: MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container["a"] = 1 @@ -828,13 +1130,13 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(error.sql!, "INSERT INTO \"t\" (\"a\", \"b\") VALUES (?,?)") } } - #endif +#endif } func testGeneratedColumnsUpdateIsAnError() throws { - #if !GRDBCUSTOMSQLITE +#if !GRDBCUSTOMSQLITE throw XCTSkip("Generated columns are not available") - #else +#else struct T: MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container["id"] = 1 @@ -853,6 +1155,752 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(error.sql!, "UPDATE \"t\" SET \"a\"=? WHERE \"id\"=?") } } - #endif +#endif + } +} + +// MARK: - Insert and Fetch + +extension MutablePersistableRecordTests { + func test_insertAndFetch() 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 player = FullPlayer(id: nil, name: "Arthur", score: 1000) + let insertedPlayer = try XCTUnwrap(player.insertAndFetch(db)) + XCTAssertEqual(insertedPlayer.id, 1) + XCTAssertEqual(insertedPlayer.name, "Arthur") + XCTAssertEqual(insertedPlayer.score, 1000) + } + } + + func test_insertAndFetch_as() 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 + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_insertAndFetch_selection_fetch() 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 + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement)! + } + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Save and Fetch + +extension MutablePersistableRecordTests { + func test_saveAndFetch() 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 player = FullPlayer(id: nil, name: "Arthur", score: 1000) + let savedPlayer = try XCTUnwrap(player.saveAndFetch(db)) + XCTAssertEqual(savedPlayer.id, 1) + XCTAssertEqual(savedPlayer.name, "Arthur") + XCTAssertEqual(savedPlayer.score, 1000) + } + } + + func test_saveAndFetch_as() 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 + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_saveAndFetch_selection_fetch() 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 + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + var partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Update and Fetch + +extension MutablePersistableRecordTests { + func test_updateAndFetch() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db) + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + + do { + let updatedPlayer = try XCTUnwrap(player.updateAndFetch(db)) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Barbara") + XCTAssertEqual(updatedPlayer.score, 1000) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateAndFetch_as() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db, as: PartialPlayer.self) + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + + do { + let updatedPlayer = try XCTUnwrap(player.updateAndFetch(db, as: PartialPlayer.self)) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Barbara") + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateAndFetch_selection_fetch() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + player.score = 0 + + do { + let row = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTAssertEqual(row, ["id": 1, "name": "Barbara", "score": 0]) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateAndFetch_columns_selection_fetch() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + player.name = "Barbara" + player.score = 0 + + do { + let row = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in + try Row.fetchOne(statement) + } + XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 0]) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateChangesAndFetch_modify() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateChangesAndFetch(db) { + $0.name = "Barbara" + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + + do { + let updatedPlayer = try player.updateChangesAndFetch(db) { + $0.name = "Barbara" + } + XCTAssertNil(updatedPlayer) + } + + do { + let updatedPlayer = try XCTUnwrap(player.updateChangesAndFetch(db) { + $0.name = "Craig" + }) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Craig") + XCTAssertEqual(updatedPlayer.score, 1000) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateChangesAndFetch_as_modify() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateChangesAndFetch(db, as: PartialPlayer.self) { + $0.name = "Barbara" + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + + do { + let updatedPlayer = try player.updateChangesAndFetch(db, as: PartialPlayer.self) { + $0.name = "Barbara" + } + XCTAssertNil(updatedPlayer) + } + + do { + let updatedPlayer = try XCTUnwrap(player.updateChangesAndFetch(db, as: PartialPlayer.self) { + $0.name = "Craig" + }) + XCTAssertEqual(updatedPlayer.id, 1) + XCTAssertEqual(updatedPlayer.name, "Craig") + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + + func test_updateChangesAndFetch_selection_fetch_modify() 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 + var player = FullPlayer(id: 1, name: "Arthur", score: 1000) + do { + _ = try player.updateChangesAndFetch( + db, selection: [AllColumns()], + fetch: { statement in try Row.fetchOne(statement) }, + modify: { $0.name = "Barbara" }) + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "player", key: ["id": 1.databaseValue]) { } + + try player.insert(db) + + do { + let updatedRow = try player.updateChangesAndFetch( + db, selection: [AllColumns()], + fetch: { statement in try Row.fetchOne(statement) }, + modify: { $0.name = "Barbara" }) + XCTAssertNil(updatedRow) + } + + do { + let updatedRow = try player.updateChangesAndFetch( + db, selection: [AllColumns()], + fetch: { statement in try Row.fetchOne(statement) }, + modify: { $0.name = "Craig" }) + XCTAssertEqual(updatedRow, ["id": 1, "name": "Craig", "score": 1000]) + } + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(player.callbacks.didUpdateCount, 1) + + XCTAssertEqual(player.callbacks.willSaveCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(player.callbacks.didSaveCount, 2) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } } } diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index deb80f7ef..f1dbc73c3 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -33,8 +33,8 @@ private class PersistableRecordPersonClass : PersistableRecord { container["Age"] = age } - func didInsert(with rowID: Int64, for column: String?) { - self.id = rowID + func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID } } @@ -50,14 +50,32 @@ private struct PersistableRecordCountry : PersistableRecord { } } +private class Callbacks { + var willInsertCount = 0 + var aroundInsertEnterCount = 0 + var aroundInsertExitCount = 0 + var didInsertCount = 0 + + var willUpdateCount = 0 + var aroundUpdateEnterCount = 0 + var aroundUpdateExitCount = 0 + var didUpdateCount = 0 + + var willSaveCount = 0 + var aroundSaveEnterCount = 0 + var aroundSaveExitCount = 0 + var didSaveCount = 0 + + var willDeleteCount = 0 + var aroundDeleteEnterCount = 0 + var aroundDeleteExitCount = 0 + var didDeleteCount = 0 +} + private struct PersistableRecordCustomizedCountry : PersistableRecord { var isoCode: String var name: String - let willInsert: () -> Void - let willUpdate: () -> Void - let willSave: () -> Void - let willDelete: () -> Void - let willExists: () -> Void + let callbacks = Callbacks() static let databaseTableName = "countries" @@ -66,29 +84,80 @@ private struct PersistableRecordCustomizedCountry : PersistableRecord { container["name"] = name } - func insert(_ db: Database) throws { - willInsert() - try performInsert(db) + func willInsert(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willInsertCount += 1 } - func update(_ db: Database, columns: Set) throws { - willUpdate() - try performUpdate(db, columns: columns) + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 } - func save(_ db: Database) throws { - willSave() - try performSave(db) + func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 } - func delete(_ db: Database) throws -> Bool { - willDelete() - return try performDelete(db) + func willUpdate(_ db: Database, columns: Set) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willUpdateCount += 1 } - func exists(_ db: Database) throws -> Bool { - willExists() - return try performExists(db) + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + // Make sure database can be used + try db.execute(sql: "SELECT 1") + + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 } } @@ -104,6 +173,79 @@ private struct Citizenship : PersistableRecord { } } +private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { + static let databaseTableName = "player" + let callbacks = Callbacks() + var id: Int64? + var name: String + + enum CodingKeys: String, CodingKey { + case id, name + } + + func willInsert(_ db: Database) throws { + callbacks.willInsertCount += 1 + } + + func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + callbacks.aroundInsertEnterCount += 1 + _ = try insert() + callbacks.aroundInsertExitCount += 1 + } + + func didInsert(_ inserted: InsertionSuccess) { + callbacks.didInsertCount += 1 + } + + func willUpdate(_ db: Database, columns: Set) throws { + callbacks.willUpdateCount += 1 + } + + func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + callbacks.aroundUpdateEnterCount += 1 + _ = try update() + callbacks.aroundUpdateExitCount += 1 + } + + func didUpdate(_ updated: PersistenceSuccess) { + callbacks.didUpdateCount += 1 + } + + func willSave(_ db: Database) throws { + callbacks.willSaveCount += 1 + } + + func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + callbacks.aroundSaveEnterCount += 1 + _ = try save() + callbacks.aroundSaveExitCount += 1 + } + + func didSave(_ saved: PersistenceSuccess) { + callbacks.didSaveCount += 1 + } + + func willDelete(_ db: Database) throws { + callbacks.willDeleteCount += 1 + } + + func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + callbacks.aroundDeleteEnterCount += 1 + _ = try delete() + callbacks.aroundDeleteExitCount += 1 + } + + func didDelete(deleted: Bool) { + callbacks.didDeleteCount += 1 + } +} + +private struct FullPlayer: Decodable, TableRecord, FetchableRecord { + var id: Int64 + var name: String + var score: Int +} + class PersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { @@ -120,12 +262,15 @@ class PersistableRecordTests: GRDBTestCase { CREATE TABLE citizenships ( countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode), personID INTEGER NOT NULL REFERENCES persons(id)); + CREATE TABLE player( + id INTEGER PRIMARY KEY, + name NOT NULL, + score INTEGER NOT NULL DEFAULT 1000); """) } try migrator.migrate(dbWriter) } - // MARK: - PersistableRecordPerson func testInsertPersistableRecordPerson() throws { @@ -139,7 +284,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - + func testSavePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -151,8 +296,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - - + // MARK: - PersistableRecordPersonClass func testInsertPersistableRecordPersonClass() throws { @@ -167,7 +311,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - + func testUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -181,7 +325,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertTrue([ "UPDATE \"persons\" SET \"age\"=42, \"name\"='Craig' WHERE \"id\"=1", "UPDATE \"persons\" SET \"name\"='Craig', \"age\"=42 WHERE \"id\"=1" - ].contains(self.lastSQLQuery)) + ].contains(self.lastSQLQuery)) let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) @@ -191,7 +335,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + func testPartialUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -247,7 +391,7 @@ class PersistableRecordTests: GRDBTestCase { } } } - + func testSavePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -283,7 +427,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + func testDeletePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -303,7 +447,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Barbara") } } - + func testExistsPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -315,8 +459,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertFalse(try person.exists(db)) } } - - + // MARK: - PersistableRecordCountry func testInsertPersistableRecordCountry() throws { @@ -331,7 +474,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + func testUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -352,7 +495,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testPartialUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -388,7 +531,7 @@ class PersistableRecordTests: GRDBTestCase { } } } - + func testSavePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -424,7 +567,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testDeletePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -444,7 +587,7 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -456,33 +599,36 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertFalse(try country.exists(db)) } } - - + // MARK: - PersistableRecordCustomizedCountry func testInsertPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 let country = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) @@ -490,43 +636,42 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + func testUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -536,43 +681,76 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + + func testPersistenceErrorPersistableRecordCustomizedCountry() throws { + let country = PersistableRecordCustomizedCountry( + isoCode: "FR", + name: "France") + + let dbQueue = try makeDatabaseQueue() + do { + try dbQueue.inDatabase { db in + try country.update(db) + } + XCTFail("Expected PersistenceError") + } catch PersistenceError.recordNotFound(databaseTableName: "countries", key: ["isoCode": "FR".databaseValue]) { } + + XCTAssertEqual(country.callbacks.willInsertCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(country.callbacks.didInsertCount, 0) + + XCTAssertEqual(country.callbacks.willUpdateCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 0) // last update has failed + XCTAssertEqual(country.callbacks.didSaveCount, 0) // last update has failed + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) + } + func testPartialUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" try country1.update(db, columns: ["name"]) XCTAssertEqual(self.lastSQLQuery, "UPDATE \"countries\" SET \"name\"='France Métropolitaine' WHERE \"isoCode\"='FR'") - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -582,30 +760,34 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testSavePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 1) - XCTAssertEqual(saveCount, 1) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) var rows = try Row.fetchAll(db, sql: "SELECT * FROM countries") XCTAssertEqual(rows.count, 1) @@ -614,22 +796,31 @@ class PersistableRecordTests: GRDBTestCase { let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.save(db) country1.name = "France Métropolitaine" try country1.save(db) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 2) - XCTAssertEqual(saveCount, 2) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) + + XCTAssertEqual(country1.callbacks.willSaveCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 2) + XCTAssertEqual(country1.callbacks.didSaveCount, 2) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country1.callbacks.didDeleteCount, 0) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -641,11 +832,25 @@ class PersistableRecordTests: GRDBTestCase { _ = try country1.delete(db) try country1.save(db) - XCTAssertEqual(insertCount, 2) - XCTAssertEqual(updateCount, 3) - XCTAssertEqual(saveCount, 3) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 2) + XCTAssertEqual(country1.callbacks.didInsertCount, 2) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 1) // last update has failed + XCTAssertEqual(country1.callbacks.didUpdateCount, 1) // last update has failed + + XCTAssertEqual(country1.callbacks.willSaveCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 3) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 3) + XCTAssertEqual(country1.callbacks.didSaveCount, 3) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country1.callbacks.didDeleteCount, 1) rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 2) @@ -655,32 +860,17 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "United States") } } - + func testDeletePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 let country1 = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country1.insert(db) let country2 = PersistableRecordCustomizedCountry( isoCode: "US", - name: "United States", - willInsert: { }, - willUpdate: { }, - willSave: { }, - willDelete: { }, - willExists: { }) + name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -688,11 +878,25 @@ class PersistableRecordTests: GRDBTestCase { deleted = try country1.delete(db) XCTAssertFalse(deleted) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 2) - XCTAssertEqual(existsCount, 0) + XCTAssertEqual(country1.callbacks.willInsertCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country1.callbacks.didInsertCount, 1) + + XCTAssertEqual(country1.callbacks.willUpdateCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country1.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country1.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country1.callbacks.willSaveCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country1.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country1.callbacks.didSaveCount, 1) + + XCTAssertEqual(country1.callbacks.willDeleteCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteEnterCount, 2) + XCTAssertEqual(country1.callbacks.aroundDeleteExitCount, 2) + XCTAssertEqual(country1.callbacks.didDeleteCount, 2) let rows = try Row.fetchAll(db, sql: "SELECT * FROM countries ORDER BY isoCode") XCTAssertEqual(rows.count, 1) @@ -700,46 +904,65 @@ class PersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "United States") } } - + func testExistsPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var insertCount: Int = 0 - var updateCount: Int = 0 - var saveCount: Int = 0 - var deleteCount: Int = 0 - var existsCount: Int = 0 let country = PersistableRecordCustomizedCountry( isoCode: "FR", - name: "France", - willInsert: { insertCount += 1 }, - willUpdate: { updateCount += 1 }, - willSave: { saveCount += 1 }, - willDelete: { deleteCount += 1 }, - willExists: { existsCount += 1 }) + name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 0) - XCTAssertEqual(existsCount, 1) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(country.callbacks.didDeleteCount, 0) _ = try country.delete(db) XCTAssertFalse(try country.exists(db)) - XCTAssertEqual(insertCount, 1) - XCTAssertEqual(updateCount, 0) - XCTAssertEqual(saveCount, 0) - XCTAssertEqual(deleteCount, 1) - XCTAssertEqual(existsCount, 2) + + XCTAssertEqual(country.callbacks.willInsertCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(country.callbacks.didInsertCount, 1) + + XCTAssertEqual(country.callbacks.willUpdateCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(country.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(country.callbacks.didUpdateCount, 0) + + XCTAssertEqual(country.callbacks.willSaveCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(country.callbacks.didSaveCount, 1) + + XCTAssertEqual(country.callbacks.willDeleteCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(country.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(country.callbacks.didDeleteCount, 1) } } - - + // MARK: - Errors - + func testInsertErrorDoesNotPreventSubsequentInserts() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -776,7 +999,7 @@ extension PersistableRecordTests { try db.create(table: "t1") { t in t.column("nested", .text) } - + let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) @@ -844,7 +1067,7 @@ extension PersistableRecordTests { try db.create(table: "t1") { t in t.column("nested", .text) } - + let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: [nested, nested]) try value.insert(db) @@ -915,13 +1138,13 @@ extension PersistableRecordTests { try db.create(table: "t1") { t in t.column("nested", .text) } - + let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT nested FROM t1")! - + // Encodable has a default implementation which encodes a model to JSON as String. // We expect here JSON in the form of a String XCTAssert(dbValue.storage.value is String) @@ -935,7 +1158,7 @@ extension PersistableRecordTests { XCTFail(error.localizedDescription) } } else { - XCTFail("Failed to convert " + string) + XCTFail("Failed to convert " + string) } } } @@ -1036,3 +1259,339 @@ extension PersistableRecordTests { } } + +// MARK: - Insert and Fetch + +extension PersistableRecordTests { + func test_insertAndFetch_as() 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 + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_insertAndFetch_selection_fetch() 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 + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement)! + } + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} + +// MARK: - Save and Fetch + +extension PersistableRecordTests { + func test_saveAndFetch_as() 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 + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(fullPlayer.id, 1) + XCTAssertEqual(fullPlayer.name, "Arthur") + XCTAssertEqual(fullPlayer.score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } + + func test_saveAndFetch_selection_fetch() 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 + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + + do { + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + try partialPlayer.delete(db) + sqlQueries.removeAll() + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1) + } + + do { + sqlQueries.removeAll() + let partialPlayer = PartialPlayer(id: 1, name: "Arthur") + let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) + XCTAssert(sqlQueries.contains(""" + UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(score, 1000) + + XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0) + + XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1) + + XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) + } + } + } +} diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index 1ee400cb6..76589e4b6 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 94d2de96a..6fed21b8f 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -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) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index beae0f620..c1fe278f8 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -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 { diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index d293a6838..195122336 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -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 { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 5581cca55..7e757b0d2 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -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 { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index ebdc8891b..50a2911d6 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -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 { diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index e75187f62..8de07ca0b 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -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) throws { + override func willUpdate(_ db: Database, columns: Set) throws { lastSavingMethod = .update - try super.update(db, columns: columns) + try super.willUpdate(db, columns: columns) } } diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index e5dd27106..03f95a3e2 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -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 } } diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 167f95dae..948a84366 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -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 * + """) + } + } + } } diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index c61353e6a..69ee86938 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -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) diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 2c38fa4b8..446927342 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -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 } }