diff --git a/CHANGELOG.md b/CHANGELOG.md index ab1900f7a..2770419b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Fixed**: [#1316](https://github.com/groue/GRDB.swift/pull/1316) and [#1320](https://github.com/groue/GRDB.swift/pull/1320) by [@baekteun](https://github.com/baekteun): Replace "OSX" with "macOS". - **Fixed**: [#1328](https://github.com/groue/GRDB.swift/pull/1328) by [@ytti](https://github.com/ytti): Fix documentation about Data passphrases. +- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date +- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records. - Added support for `Table` in SQL interpolation. ## 6.6.1 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 089a9fd2a..1d711ca40 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -250,6 +250,8 @@ 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; }; 56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; }; 56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; }; + 56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; }; + 56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; }; 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; }; @@ -711,6 +713,8 @@ 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = ""; }; 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; + 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = ""; }; + 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = ""; }; 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; @@ -1368,6 +1372,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, + 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, ); name = Core; @@ -1467,6 +1472,7 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, + 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, 5605F1471C672E4000235C62 /* Support */, @@ -1950,6 +1956,7 @@ 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, + 56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, @@ -2098,6 +2105,7 @@ 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, + 56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, 56959629222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 5d453fa72..0dae035df 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -169,6 +169,21 @@ public struct Configuration { /// ``` public var publicStatementArguments = false + /// The clock that feeds ``Database/transactionDate``. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The default clock is ``DefaultTransactionClock`` (which returns the + /// current date with `Date()`). + /// + /// For example: + /// + /// ```swift + /// var config = Configuration() + /// config.transactionClock = .custom { db in /* return some Date */ } + /// ``` + public var transactionClock: TransactionClock = .default + // MARK: - Managing SQLite Connections private var setups: [(Database) throws -> Void] = [] diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 77703eccd..c3fabdeaf 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -445,6 +445,8 @@ extension Database { clearSchemaCache() } + checkForAutocommitTransition() + // Database observation: cleanup try observationBroker?.statementDidExecute(statement) } @@ -460,6 +462,8 @@ extension Database { internalStatementCache.remove(statement) publicStatementCache.remove(statement) + checkForAutocommitTransition() + // Extract values that may be modified by the user in their // `TransactionObserver.databaseDidRollback(_:)` implementation // (see below). @@ -481,6 +485,25 @@ extension Database { arguments: arguments, publicStatementArguments: configuration.publicStatementArguments) } + + private func checkForAutocommitTransition() { + if sqlite3_get_autocommit(sqliteConnection) == 0 { + if autocommitState == .on { + // Record transaction date as soon as the connection leaves + // auto-commit mode. + // We grab a result, so that this failure is later reported + // whenever the user calls `Database.transactionDate`. + transactionDateResult = Result { try configuration.transactionClock.now(self) } + } + autocommitState = .off + } else { + if autocommitState == .off { + // Reset transaction date + transactionDateResult = nil + } + autocommitState = .on + } + } } /// A thread-unsafe statement cache diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 094cc0446..c007c812d 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -61,6 +61,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``inTransaction(_:_:)`` /// - ``isInsideTransaction`` /// - ``rollback()`` +/// - ``transactionDate`` /// - ``TransactionCompletion`` /// - ``TransactionKind`` /// @@ -276,6 +277,60 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? + // MARK: - Transaction Date + + enum AutocommitState { + case off + case on + } + + /// The state of the auto-commit mode, as left by the last + /// executed statement. + /// + /// The goal of this property is to detect changes in the auto-commit mode. + /// When you need to know if the database is currently in the auto-commit + /// mode, always prefer ``isInsideTransaction``. + var autocommitState = AutocommitState.on + + /// The date of the current transaction, wrapped in a result that is an + /// error if there was an error grabbing this date when the transaction has + /// started. + /// + /// Invariant: `transactionDateResult` is nil iff connection is not + /// inside a transaction. + var transactionDateResult: Result? + + /// The date of the current transaction. + /// + /// The returned date is constant at any point during a transaction. It is + /// set when the database leaves the + /// [autocommit mode](https://www.sqlite.org/c3ref/get_autocommit.html) with + /// a `BEGIN` statement. + /// + /// When the database is not currently in a transaction, a new date is + /// returned on each call. + /// + /// See for an example of usage. + /// + /// Transaction dates, by default, are built from a new `Date()` instance. + /// You can override this default behavior by configuring + /// ``Configuration/transactionClock``. + public var transactionDate: Date { + get throws { + SchedulingWatchdog.preconditionValidQueue(self) + + // Check invariant: `transactionDateResult` is nil iff connection + // is not inside a transaction. + assert(isInsideTransaction || transactionDateResult == nil) + + if let transactionDateResult { + return try transactionDateResult.get() + } else { + return try configuration.transactionClock.now(self) + } + } + } + // MARK: - Private properties /// Support for ``Configuration/busyMode``. diff --git a/GRDB/Core/TransactionClock.swift b/GRDB/Core/TransactionClock.swift new file mode 100644 index 000000000..0e033d5d6 --- /dev/null +++ b/GRDB/Core/TransactionClock.swift @@ -0,0 +1,64 @@ +import Foundation + +/// A type that provides the moment of a transaction. +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// ## Topics +/// +/// ### Built-in Clocks +/// +/// - ``DefaultTransactionClock`` +/// - ``CustomTransactionClock`` +public protocol TransactionClock { + /// Returns the date of the current transaction. + /// + /// This function is called whenever a transaction starts - precisely + /// speaking, whenever the database connection leaves the auto-commit mode. + /// + /// It is also called when the ``Database/transactionDate`` property is + /// called, and the database connection is not in a transaction. + /// + /// Related SQLite documentation: + func now(_ db: Database) throws -> Date +} + +extension TransactionClock where Self == DefaultTransactionClock { + /// Returns the default clock. + public static var `default`: Self { DefaultTransactionClock() } +} + +extension TransactionClock where Self == CustomTransactionClock { + /// Returns a custom clock. + /// + /// The provided closure is called whenever a transaction starts - precisely + /// speaking, whenever the database connection leaves the auto-commit mode. + /// + /// It is also called when the ``Database/transactionDate`` property is + /// called, and the database connection is not in a transaction. + public static func custom(_ now: @escaping (Database) throws -> Date) -> Self { + CustomTransactionClock(now) + } +} + +/// The default clock. +public struct DefaultTransactionClock: TransactionClock { + public func now(_ db: Database) throws -> Date { + // An opportunity to fetch transaction time from the database when + // SQLite supports the feature. + Date() + } +} + +/// A custom transaction clock. +public struct CustomTransactionClock: TransactionClock { + let _now: (Database) throws -> Date + + public init(_ now: @escaping (Database) throws -> Date) { + self._now = now + } + + public func now(_ db: Database) throws -> Date { + try _now(db) + } +} diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index eead88397..5fa411950 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -32,6 +32,7 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD ### Records and the Query Interface - +- ### Responding to Database Changes diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index 3954ae64a..87464a9e7 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -94,6 +94,8 @@ do { - ``observesSuspensionNotifications`` - ``prepareDatabase(_:)`` - ``publicStatementArguments`` +- ``transactionClock`` +- ``TransactionClock`` ### Configuring the Quality of Service diff --git a/GRDB/Documentation.docc/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md new file mode 100644 index 000000000..8b3427dcd --- /dev/null +++ b/GRDB/Documentation.docc/RecordTimestamps.md @@ -0,0 +1,187 @@ +# Record Timestamps and Transaction Date + +Learn how applications can save creation and modification dates of records. + +## Overview + +Record timestamps are the responsibility of your application. This article provides some sample code that you can adapt for your specific needs. + +> Note: Creation and modification timestamps can be automatically handled by [SQLite triggers](https://www.sqlite.org/lang_createtrigger.html). We'll explore a different technique. +> +> This is not an advice against triggers, and you won't feel hindered in any way if you prefer to use triggers. Still, consider: +> +> - A trigger does not suffer any exception, when some applications eventually want to fine-tune timestamps, or to perform migrations without touching timestamps. +> - The "current time" according to SQLite can't be controlled in tests and previews. +> - The "current time" according to SQLite is not guaranteed to be constant in a given transaction, and this may create undesired timestamp variations. + +We'll start from this table and record type: + +```swift +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("creationDate", .datetime).notNull() + t.column("modificationDate", .datetime).notNull() + t.column("name", .text).notNull() + t.column("score", .integer).notNull() +} + +struct Player: Identifiable { + var id: Int64? + var creationDate: Date? + var modificationDate: Date? + var name: String + var score: Int +} +``` + +Note that the table has non-null dates, while the record has optional dates. + +This is because we intend, in this article, to timestamp actual database operations. The `creationDate` property is the date of database insertion, and `modificationDate` is the date of last modification in the database. A new `Player` instance has no meaningful timestamp until it is saved, and this absence of information is represented with `nil`: + +```swift +// A new player has no timestamps. +var player = Player(id: nil, name: "Arthur", score: 1000) +player.id // nil, because never saved +player.creationDate // nil, because never saved +player.modificationDate // nil, because never saved + +// After insertion, the player has timestamps. +try dbQueue.write { db in + try player.insert(db) +} +player.id // not nil +player.creationDate // not nil +player.modificationDate // not nil +``` + +In the rest of the article, we'll address insertion first, then updates, and finally we'll see a way to avoid those optional timestamps. + +## Insertion Timestamp + +On insertion, the record should get fresh `creationDate` and `modificationDate`. The ``MutablePersistableRecord`` protocol provides the necessary tooling: + +```swift +extension Player: Encodable, MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } + + // Update timestamps before insertion + mutating func willInsert(_ db: Database) throws { + creationDate = try db.transactionDate + modificationDate = try db.transactionDate + } +} +``` + +Note that we are using the ``Database/transactionDate`` instead of `Date()`. This has two advantages: + +- Within a write transaction, all inserted players get the same timestamp: + + ```swift + // All players have the same timestamp. + try dbQueue.write { db in + for var player in players { + try player.insert(db) + } + } + ``` + +- The transaction date can be configured with ``Configuration/transactionClock``, so that your tests and previews can control the date. + +## Modification Timestamp + +Let's now deal with updates. The `update` persistence method won't automatically bump the timestamp as the `insert` method does. We have to explicitly deal with the modification date: + +```swift +// Increment the player score. +try dbQueue.write { db in + var player: Player + try player.updateChanges(db) { + $0.score += 1 + $0.modificationDate = try db.transactionDate + } +} +``` + +Again, we use ``Database/transactionDate``, so that all modified players get the same timestamp within a given write transaction. + +## Dealing with Optional Timestamps + +When you fetch timestamped records from the database, it may be inconvenient to deal with optional dates, even though the database columns are guaranteed to be not null: + +```swift +let player = try dbQueue.read { db + try Player.find(db, id: 1) +} +player.creationDate // optional 😕 +player.modificationDate // optional 😕 +``` + +A possible technique is to define two record types. + +One record can deal with unsaved players: + +```swift +struct Player: Identifiable { + var id: Int64? + var creationDate: Date? + var modificationDate: Date? + var name: String + var score: Int +} + +extension Player: Encodable, MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } + + // Update timestamps before insertion + mutating func willInsert(_ db: Database) throws { + creationDate = try db.transactionDate + modificationDate = try db.transactionDate + } +} +``` + +The other record only deals with saved players: + +```swift +struct TimestampedPlayer: Identifiable { + let id: Int64 + let creationDate: Date + var modificationDate: Date + var name: String + var score: Int +} + +extension TimestampedPlayer: Codable, FetchableRecord, PersistableRecord { + static var databaseTableName: String { Player.databaseTableName } +} +``` + +Usage: + +```swift +// Fetch +let timestampedPlayer = try dbQueue.read { db + try TimestampedPlayer.find(db, id: 1) +} +timestampedPlayer.creationDate // not optional +timestampedPlayer.modificationDate // not optional + +// Insert +try dbQueue.write { db in + var player = Player(id: nil, name: "Arthur", score: 1000) + + let timestampedPlayer = try player.insertAndFetch(db, as: TimestampedPlayer.self) + + timestampedPlayer.id // not optional + timestampedPlayer.creationDate // not optional + timestampedPlayer.modificationDate // not optional +} +``` + +See ``MutablePersistableRecord/insertAndFetch(_:onConflict:as:)`` and related methods for more information. diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3b15a8f99..3d8f50e2f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -240,6 +240,8 @@ 56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AE6428222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */; }; 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; + 56AFEF3229969F7E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */; }; + 56AFEF3A2996B9EE00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */; }; 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; }; @@ -722,6 +724,8 @@ 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; + 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = ""; }; + 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = ""; }; 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; @@ -1364,6 +1368,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, + 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, ); name = Core; @@ -1463,6 +1468,7 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, + 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56564F3828637C9900A19E9F /* WALSnapshot.swift */, 5605F1471C672E4000235C62 /* Support */, @@ -1923,6 +1929,7 @@ 5656A8852295BD56001FF3FF /* SQLOrdering.swift in Sources */, F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */, F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, + 56AFEF3229969F7E00CA1E51 /* TransactionClock.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, @@ -2190,6 +2197,7 @@ 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 56AFEF3A2996B9EE00CA1E51 /* TransactionDateTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, 563F4CB4242F7F140052E96C /* ValueObservationTests.swift in Sources */, 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, diff --git a/README.md b/README.md index ff239f428..d633126bb 100644 --- a/README.md +++ b/README.md @@ -2080,13 +2080,14 @@ Extending structs with record protocols is more "swifty". Subclassing the Record - [TableRecord Protocol](#tablerecord-protocol) - [PersistableRecord Protocol](#persistablerecord-protocol) - [Persistence Methods] - - [Persistence Methods and the `RETURNING` clause](#persistence-methods-and-the-returning-clause) + - [Persistence Methods and the `RETURNING` clause] - [Persistence Callbacks] - [Identifiable Records] - [Codable Records] - [Record Class](#record-class) - [Record Comparison] - [Record Customization Options] +- [Record Timestamps and Transaction Date] **Records in a Glance** @@ -7029,6 +7030,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Record Customization Options]: #record-customization-options [Persistence Callbacks]: #persistence-callbacks [persistence callbacks]: #persistence-callbacks +[Record Timestamps and Transaction Date]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps [TableRecord]: #tablerecord-protocol [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation [DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation @@ -7050,6 +7052,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Database Configuration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration [Persistence Methods]: #persistence-methods [persistence methods]: #persistence-methods +[Persistence Methods and the `RETURNING` clause]: #persistence-methods-and-the-returning-clause [RecordError]: #recorderror [Transactions and Savepoints]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions [`DatabaseQueue`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift new file mode 100644 index 000000000..5a9383b20 --- /dev/null +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -0,0 +1,97 @@ +import XCTest +import GRDB + +class TransactionDateTests: GRDBTestCase { + func testTransactionDateOutsideOfTransaction() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, dates) + } + + func testTransactionDateInsideTransaction_commit() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try db.execute(sql: "COMMIT") + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + } + + func testTransactionDateInsideTransaction_rollback() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try db.execute(sql: "ROLLBACK") + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + } + + func testTransactionDateInsideTransaction_rollbackingError() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try? db.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY ON CONFLICT ROLLBACK); + INSERT INTO t VALUES (1); + INSERT INTO t VALUES (1); -- fails and rollbacks + """) + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + } +}