From f649d9e19ecb2ac253e42d9d96732ca995dd32ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Feb 2023 17:27:43 +0100 Subject: [PATCH 01/10] Transaction Date --- GRDB.xcodeproj/project.pbxproj | 4 ++ GRDB/Core/Configuration.swift | 13 ++++ GRDB/Core/Database+Statements.swift | 23 +++++++ GRDB/Core/Database.swift | 40 ++++++++++++ GRDB/Core/TransactionClock.swift | 64 +++++++++++++++++++ .../Extension/Configuration.md | 2 + GRDBCustom.xcodeproj/project.pbxproj | 4 ++ 7 files changed, 150 insertions(+) create mode 100644 GRDB/Core/TransactionClock.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 089a9fd2a..14f30e31f 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -250,6 +250,7 @@ 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 */; }; 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 +712,7 @@ 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 = ""; }; 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 = ""; }; @@ -1467,6 +1469,7 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, + 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, 5605F1471C672E4000235C62 /* Support */, @@ -2098,6 +2101,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..09fcc7fa0 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -169,6 +169,19 @@ public struct Configuration { /// ``` public var publicStatementArguments = false + /// The clock that feeds ``Database/transactionDate``. + /// + /// 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..06accbab9 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,45 @@ 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 + } + + /// Whether the last executed statement left the database is the auto-commit + /// mode or not. + 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. + /// + /// It is constant at any point during a transaction. + /// + /// When the database is not currently in a transaction, a new date is + /// returned on each call. + public var transactionDate: Date { + get throws { + // 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/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/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3b15a8f99..6f655dec2 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -240,6 +240,7 @@ 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 */; }; 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 +723,7 @@ 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 = ""; }; 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 = ""; }; @@ -1463,6 +1465,7 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, + 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56564F3828637C9900A19E9F /* WALSnapshot.swift */, 5605F1471C672E4000235C62 /* Support */, @@ -1923,6 +1926,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 */, From 93928a791aa883ffa3c2db0f3e94a042841c09c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Feb 2023 19:10:26 +0100 Subject: [PATCH 02/10] Tests for Transaction Date --- GRDB.xcodeproj/project.pbxproj | 4 + GRDBCustom.xcodeproj/project.pbxproj | 4 + Tests/GRDBTests/TransactionDateTests.swift | 88 ++++++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 Tests/GRDBTests/TransactionDateTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 14f30e31f..1d711ca40 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -251,6 +251,7 @@ 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 */; }; @@ -713,6 +714,7 @@ 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 = ""; }; @@ -1370,6 +1372,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, + 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, ); name = Core; @@ -1953,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 */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 6f655dec2..3d8f50e2f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -241,6 +241,7 @@ 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 */; }; @@ -724,6 +725,7 @@ 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 = ""; }; @@ -1366,6 +1368,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, + 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, ); name = Core; @@ -2194,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/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift new file mode 100644 index 000000000..44ffce110 --- /dev/null +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -0,0 +1,88 @@ +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() throws { + let dates = [ + Date.distantPast, + Date(timeIntervalSince1970: 0), + Date(timeIntervalSinceReferenceDate: 0), + Date(), + Date.distantPast, + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + try makeDatabaseQueue().inDatabase { db in + do { + // Dates are constant within a transaction block + var collectedDates: [Date] = [] + try db.inTransaction { + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + return .commit + } + XCTAssertEqual(collectedDates, [dates[0], dates[0]]) + } + + do { + // Dates are no longer constant when transaction has completed + try XCTAssertEqual(db.transactionDate, dates[1]) + } + + do { + // Dates are constant within a transaction + var collectedDates: [Date] = [] + try db.beginTransaction() + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try db.rollback() + XCTAssertEqual(collectedDates, [dates[2], dates[2]]) + } + + do { + // Dates are no longer constant when transaction has completed + try XCTAssertEqual(db.transactionDate, dates[3]) + } + + do { + // Dates are constant within a transaction + var collectedDates: [Date] = [] + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try db.execute(sql: "COMMIT") + XCTAssertEqual(collectedDates, [dates[4], dates[4]]) + } + + do { + // Dates are no longer constant when transaction has completed + try XCTAssertEqual(db.transactionDate, dates[5]) + } + } + } +} + From efa8f0e69d13d689268fd369122e35b971e72331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Feb 2023 19:59:39 +0100 Subject: [PATCH 03/10] Configuration.transactionClock is experimental as well --- GRDB/Core/Configuration.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 09fcc7fa0..0dae035df 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -171,6 +171,8 @@ public struct Configuration { /// 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()`). /// From 961b3a9cad7927785f194e57507783d6844baf64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Feb 2023 20:01:43 +0100 Subject: [PATCH 04/10] Database.transactionDate must be called from a valid DispatchQueue --- GRDB/Core/Database.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 06accbab9..b9d3e8d2d 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -304,6 +304,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// returned on each call. 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) From c8339db68b6d88aa12e329d94532a676d0f5cf98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Feb 2023 10:17:10 +0100 Subject: [PATCH 05/10] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab1900f7a..baec6b06e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,7 @@ 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 - Added support for `Table` in SQL interpolation. ## 6.6.1 From e4421c509cc498fb8ad4de1d36933d10fc3922b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Feb 2023 10:18:10 +0100 Subject: [PATCH 06/10] Improve transactionDate documentation --- GRDB/Core/Database.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b9d3e8d2d..c18cc5e7b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -298,10 +298,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The date of the current transaction. /// - /// It is constant at any point during a 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. + /// + /// 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) From 3c71a6deea8faf54d4e504d7955217d9a4159494 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Feb 2023 10:18:20 +0100 Subject: [PATCH 07/10] "Record Timestamps and Transaction Date" documentation chapter --- CHANGELOG.md | 1 + GRDB/Core/Database.swift | 2 + GRDB/Documentation.docc/Documentation.md | 1 + GRDB/Documentation.docc/RecordTimestamps.md | 187 ++++++++++++++++++++ README.md | 5 +- 5 files changed, 195 insertions(+), 1 deletion(-) create mode 100644 GRDB/Documentation.docc/RecordTimestamps.md diff --git a/CHANGELOG.md b/CHANGELOG.md index baec6b06e..2770419b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,6 +109,7 @@ 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/Core/Database.swift b/GRDB/Core/Database.swift index c18cc5e7b..d7ef11e01 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -306,6 +306,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// 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``. 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/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md new file mode 100644 index 000000000..58c3c3015 --- /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 + +GRDB does not provide any ready-made apis that automatically update record timestamps: this is 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). This is not the technique explored here. +> +> This is not an advice against triggers! It just happens that this article aims at letting you in control. 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/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 From 6500a97f880a0347cc3e3cc643fe480701b15681 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Feb 2023 11:58:46 +0100 Subject: [PATCH 08/10] Documentation --- GRDB/Core/Database.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index d7ef11e01..c007c812d 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -284,8 +284,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib case on } - /// Whether the last executed statement left the database is the auto-commit - /// mode or not. + /// 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 From 72216beacb536829e2cb19976ff9a4a0ac17a106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Feb 2023 12:06:11 +0100 Subject: [PATCH 09/10] Enhance wording --- GRDB/Documentation.docc/RecordTimestamps.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/Documentation.docc/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md index 58c3c3015..8b3427dcd 100644 --- a/GRDB/Documentation.docc/RecordTimestamps.md +++ b/GRDB/Documentation.docc/RecordTimestamps.md @@ -4,11 +4,11 @@ Learn how applications can save creation and modification dates of records. ## Overview -GRDB does not provide any ready-made apis that automatically update record timestamps: this is the responsibility of your application. This article provides some sample code that you can adapt for your specific needs. +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). This is not the technique explored here. +> 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! It just happens that this article aims at letting you in control. Consider: +> 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. From e9afb04b1e7015daeabe9c4caa9d274bf78a6df7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Feb 2023 12:19:56 +0100 Subject: [PATCH 10/10] Test that transaction date is reset after a rollback error --- Tests/GRDBTests/TransactionDateTests.swift | 109 +++++++++++---------- 1 file changed, 59 insertions(+), 50 deletions(-) diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift index 44ffce110..5a9383b20 100644 --- a/Tests/GRDBTests/TransactionDateTests.swift +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -22,13 +22,10 @@ class TransactionDateTests: GRDBTestCase { XCTAssertEqual(collectedDates, dates) } - func testTransactionDateInsideTransaction() throws { + func testTransactionDateInsideTransaction_commit() throws { let dates = [ Date.distantPast, - Date(timeIntervalSince1970: 0), - Date(timeIntervalSinceReferenceDate: 0), Date(), - Date.distantPast, Date.distantFuture, ] var dateIterator = dates.makeIterator() @@ -36,53 +33,65 @@ class TransactionDateTests: GRDBTestCase { dateIterator.next()! } + var collectedDates: [Date] = [] try makeDatabaseQueue().inDatabase { db in - do { - // Dates are constant within a transaction block - var collectedDates: [Date] = [] - try db.inTransaction { - try collectedDates.append(db.transactionDate) - try collectedDates.append(db.transactionDate) - return .commit - } - XCTAssertEqual(collectedDates, [dates[0], dates[0]]) - } - - do { - // Dates are no longer constant when transaction has completed - try XCTAssertEqual(db.transactionDate, dates[1]) - } - - do { - // Dates are constant within a transaction - var collectedDates: [Date] = [] - try db.beginTransaction() - try collectedDates.append(db.transactionDate) - try collectedDates.append(db.transactionDate) - try db.rollback() - XCTAssertEqual(collectedDates, [dates[2], dates[2]]) - } - - do { - // Dates are no longer constant when transaction has completed - try XCTAssertEqual(db.transactionDate, dates[3]) - } - - do { - // Dates are constant within a transaction - var collectedDates: [Date] = [] - try db.execute(sql: "BEGIN") - try collectedDates.append(db.transactionDate) - try collectedDates.append(db.transactionDate) - try db.execute(sql: "COMMIT") - XCTAssertEqual(collectedDates, [dates[4], dates[4]]) - } - - do { - // Dates are no longer constant when transaction has completed - try XCTAssertEqual(db.transactionDate, dates[5]) - } + 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]]) } } -