Files
GRDB.swift/GRDB/Core/TransactionClock.swift
2025-11-12 18:04:31 +01:00

70 lines
2.5 KiB
Swift

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<API>: Sendable {
associatedtype API: SQLiteAPI
/// 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: <https://www.sqlite.org/c3ref/get_autocommit.html>
func now(_ db: DatabaseBase<API>) throws -> Date
}
#warning("TODO: expose a version with default api")
//extension TransactionClock where Self == DefaultTransactionClock {
// /// Returns the default clock.
// public static var `default`: Self { DefaultTransactionClock() }
//}
#warning("TODO: expose a version with default api")
//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 @Sendable (Database) throws -> Date) -> Self {
// CustomTransactionClock(now)
// }
//}
/// The default transaction clock.
public struct DefaultTransactionClock<API: SQLiteAPI>: TransactionClock {
/// Returns the start date of the current transaction.
public func now(_ db: DatabaseBase<API>) throws -> Date {
// An opportunity to fetch transaction time from the database when
// SQLite supports the feature.
Date()
}
}
/// A custom transaction clock.
public struct CustomTransactionClock<API: SQLiteAPI>: TransactionClock {
let _now: @Sendable (DatabaseBase<API>) throws -> Date
public init(_ now: @escaping @Sendable (DatabaseBase<API>) throws -> Date) {
self._now = now
}
public func now(_ db: DatabaseBase<API>) throws -> Date {
try _now(db)
}
}