Compare commits

...
Author SHA1 Message Date
Gwendal Roué ae2c7ad364 Fix test concurrency errors for DatabaseMigrator 2023-11-05 15:58:17 +01:00
Gwendal Roué 856cc69088 Fix test concurrency errors for BusyCallback 2023-11-05 15:58:17 +01:00
Gwendal Roué c211410875 Fix test concurrency errors for TransactionClock 2023-11-05 15:58:17 +01:00
Gwendal Roué 244d77fb85 Fix test concurrency errors for Configuration.prepareDatabase 2023-11-05 15:58:17 +01:00
Gwendal Roué c3d4838655 Fix test concurrency errors for ValueObservation fetch closures 2023-11-05 15:58:17 +01:00
Gwendal Roué cd5af9a2eb Fix test concurrency errors 2023-11-05 15:58:17 +01:00
Gwendal Roué d83718c231 Fix a compiler warning with DispatchQueue.mainKey 2023-11-05 15:58:17 +01:00
Gwendal Roué 8bebd116f7 Fix compiler warnings with Pool 2023-11-05 15:58:17 +01:00
Gwendal Roué 4d9a6ff199 Fix compiler error 2023-11-05 15:58:17 +01:00
Gwendal Roué 415805d79b Fix compiler error with UIApplication.endBackgroundTask 2023-11-05 15:58:17 +01:00
Gwendal Roué 7f0dfc3311 Fix compiler error with WALSnapshotTransaction 2023-11-05 15:58:17 +01:00
Gwendal Roué 9ce4690db8 Fix compiler error with AnyDatabaseCancellable 2023-11-05 15:58:17 +01:00
Gwendal Roué bb2013501c Fix compiler error with DatabaseFuture 2023-11-05 15:58:17 +01:00
Gwendal Roué 6e5e7efb7b Sendable public types 2023-11-05 15:58:17 +01:00
Gwendal Roué d6c712d19b RenameColumnAdapter requires a Sendable closure 2023-11-05 15:58:17 +01:00
Gwendal Roué 0d7b13058c AdaptedFetchRequest requires a Sendable closure 2023-11-05 15:46:32 +01:00
Gwendal Roué 7c339d5fe5 Custom strategy closures are Sendable 2023-11-05 15:34:12 +01:00
Gwendal Roué f1c0a5d5eb Migrations are Sendable 2023-11-05 15:34:12 +01:00
Gwendal Roué bec785052f BusyCallback is Sendable 2023-11-05 15:34:12 +01:00
Gwendal Roué 63eb0b3f81 TransactionClock is Sendable 2023-11-05 15:34:12 +01:00
Gwendal Roué 28f1cec1be All xxxWhenConnected closures are Sendable 2023-11-05 15:34:12 +01:00
Gwendal Roué 403c0fab5d Fetch functions are Sendable 2023-11-05 15:34:12 +01:00
Gwendal Roué cc26fb91aa Configuration.prepareDatabase requires a Sendable closure 2023-11-05 15:13:18 +01:00
Gwendal Roué 904f53749e All ValueObservation fetch closures are @Sendable 2023-11-05 15:13:18 +01:00
Gwendal Roué c7e21a27ff All ValueObservation closures are @Sendable 2023-11-05 15:12:31 +01:00
Gwendal Roué 1d47e46b8a All publisher closures are @Sendable 2023-11-05 15:12:31 +01:00
Gwendal Roué 3d1bbe534e All async closures are @Sendable
This is necessary because DispatchQueue.async accepts a Sendable closure.
2023-11-05 15:12:31 +01:00
Gwendal Roué 5efd204f5c Concurrency checks 2023-11-05 15:12:31 +01:00
83 changed files with 708 additions and 474 deletions

No files matched your search

+3 -3
View File
@@ -186,7 +186,7 @@ public struct Configuration {
// MARK: - Managing SQLite Connections
private var setups: [(Database) throws -> Void] = []
private var setups: [@Sendable (Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -223,7 +223,7 @@ public struct Configuration {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
setups.append(setup)
}
@@ -294,7 +294,7 @@ public struct Configuration {
/// connection is opened.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public enum JournalModeConfiguration {
public enum JournalModeConfiguration: Sendable {
/// The default setup has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool``
/// configure the database for the WAL mode (just like the
+6 -6
View File
@@ -847,7 +847,7 @@ extension Database {
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord {
public struct ColumnInfo: FetchableRecord, Sendable {
let cid: Int
let hidden: Int?
@@ -933,9 +933,9 @@ public struct ColumnInfo: FetchableRecord {
///
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
public struct IndexInfo {
public struct IndexInfo: Sendable {
/// The origin of an index.
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
public var rawValue: String
public init(rawValue: String) {
@@ -1008,7 +1008,7 @@ public struct IndexInfo {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
public struct ForeignKeyViolation {
public struct ForeignKeyViolation: Sendable {
/// The name of the table that contains the foreign key.
public var originTable: String
@@ -1157,7 +1157,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo {
public struct PrimaryKeyInfo: Sendable {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
@@ -1283,7 +1283,7 @@ public struct PrimaryKeyInfo {
/// `Database` method.
///
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
public struct ForeignKeyInfo {
public struct ForeignKeyInfo: Sendable {
/// The first column in the output of the `foreign_key_list` pragma.
public var id: Int
+10 -10
View File
@@ -1720,7 +1720,7 @@ extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
/// to access the database while it is locked by another connection.
@@ -1748,7 +1748,7 @@ extension Database {
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
public enum BusyMode {
public enum BusyMode: Sendable {
/// The `SQLITE_BUSY` error is immediately returned to the connection
/// that tries to access the locked database.
case immediateError
@@ -1766,7 +1766,7 @@ extension Database {
/// The available checkpoint modes.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
public enum CheckpointMode: CInt {
public enum CheckpointMode: CInt, Sendable {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
case passive = 0
@@ -1785,7 +1785,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable, Sendable {
public let rawValue: String
/// Creates a collation name.
@@ -1822,7 +1822,7 @@ extension Database {
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct ColumnType: RawRepresentable, Hashable {
public struct ColumnType: RawRepresentable, Hashable, Sendable {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
@@ -1874,7 +1874,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String {
public enum ConflictResolution: String, Sendable {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
@@ -1894,7 +1894,7 @@ extension Database {
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String {
public enum ForeignKeyAction: String, Sendable {
/// The `CASCADE` foreign key action.
case cascade = "CASCADE"
@@ -1917,7 +1917,7 @@ extension Database {
/// ``Database/trace(options:_:)`` method.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
public struct TracingOptions: OptionSet {
public struct TracingOptions: OptionSet, Sendable {
/// The raw trace event code.
public let rawValue: CInt
@@ -2050,7 +2050,7 @@ extension Database {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion {
public enum TransactionCompletion: Sendable {
case commit
case rollback
}
@@ -2058,7 +2058,7 @@ extension Database {
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String {
public enum TransactionKind: String, Sendable {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
+1 -1
View File
@@ -1,7 +1,7 @@
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress {
public struct DatabaseBackupProgress: Sendable {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
+5 -3
View File
@@ -3,7 +3,7 @@ import Foundation
/// An SQLite result code.
///
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
public struct ResultCode: RawRepresentable, Equatable {
public struct ResultCode: RawRepresentable, Equatable, Sendable {
/// The raw SQLite result code.
public let rawValue: CInt
@@ -206,8 +206,6 @@ extension ResultCode: CustomStringConvertible {
}
}
extension ResultCode: Sendable { }
/// A `DatabaseError` describes an SQLite error.
///
/// For example:
@@ -402,6 +400,10 @@ extension DatabaseError {
static func connectionIsClosed() -> Self {
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
}
static func snapshotIsLost() -> Self {
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
+23 -22
View File
@@ -257,7 +257,9 @@ extension DatabasePool {
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -357,7 +359,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -401,7 +403,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -446,25 +448,22 @@ extension DatabasePool: DatabaseReader {
}
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T, Error>? = nil
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
let builder = UnsafeDatabaseFutureBuilder<T>()
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
let result = dbResult.flatMap { db in
Result {
try value(db)
}
}
builder.setResultAndReleaseFuture(result)
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
return builder.makeFuture()
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncConcurrentRead(value)
}
@@ -505,7 +504,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -665,7 +664,9 @@ extension DatabasePool: DatabaseReader {
///
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
func asyncWALSnapshotTransaction(
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void)
{
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -691,7 +692,7 @@ extension DatabasePool: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if configuration.readonly {
@@ -722,7 +723,7 @@ extension DatabasePool: DatabaseReader {
private func _addConcurrent<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
@@ -756,7 +757,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -809,7 +810,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+9 -7
View File
@@ -169,7 +169,9 @@ extension DatabaseQueue {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -233,7 +235,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -258,7 +260,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -266,7 +268,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(Result {
@@ -309,7 +311,7 @@ extension DatabaseQueue: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if configuration.readonly {
@@ -379,7 +381,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -425,7 +427,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+13 -13
View File
@@ -213,7 +213,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -284,7 +284,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -342,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
}
@@ -551,7 +551,7 @@ extension DatabaseReader {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
value: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
Deferred {
@@ -601,7 +601,7 @@ extension DatabaseReader {
func _addReadOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if scheduler.immediateInitialValue() {
@@ -619,16 +619,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
var isCancelled = false
let cancellable = AnyDatabaseCancellable { }
asyncRead { dbResult in
guard !isCancelled else { return }
if cancellable.isCancelled { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
guard !isCancelled else { return }
if cancellable.isCancelled { return }
do {
try onChange(result.get())
} catch {
@@ -636,7 +636,7 @@ extension DatabaseReader {
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
return cancellable
}
}
}
@@ -677,7 +677,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -686,7 +686,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -697,7 +697,7 @@ extension AnyDatabaseReader: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
base._add(
@@ -757,7 +757,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
asyncRead(value)
}
}
+1 -1
View File
@@ -40,7 +40,7 @@
///
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion {
public struct DatabaseRegion: Sendable {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
+3 -3
View File
@@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
_addReadOnly(
+3 -3
View File
@@ -292,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -317,7 +317,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return try reader.reentrantSync { db in
let result = try value(db)
if snapshotIsLost(db) {
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
throw DatabaseError.snapshotIsLost()
}
return result
}
@@ -330,7 +330,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
public func _add<Reducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable where Reducer: ValueReducer
{
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
+1 -3
View File
@@ -52,7 +52,7 @@ import Foundation
/// - ``isNull``
/// - ``storage-swift.property``
/// - ``Storage-swift.enum``
public struct DatabaseValue: Hashable {
public struct DatabaseValue: Hashable, Sendable {
/// The SQLite storage.
public let storage: Storage
@@ -219,8 +219,6 @@ extension DatabaseValue: StatementBinding {
}
}
extension DatabaseValue: Sendable { }
// @unchecked Sendable because Data is not Sendable in all target OS
extension DatabaseValue.Storage: @unchecked Sendable { }
+12 -12
View File
@@ -301,7 +301,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -335,7 +335,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -370,7 +370,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -447,7 +447,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -482,7 +482,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -516,7 +516,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -603,7 +603,7 @@ extension DatabaseValueConvertible {
/// - request: A FetchRequest.
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -640,7 +640,7 @@ extension DatabaseValueConvertible {
/// - request: A FetchRequest.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -676,7 +676,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - request: A FetchRequest.
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -753,7 +753,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -787,7 +787,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -820,7 +820,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+18 -18
View File
@@ -181,7 +181,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
@@ -340,7 +340,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
}
extension DatabaseWriter {
@@ -426,8 +426,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -557,7 +557,7 @@ extension DatabaseWriter {
func _addWriteOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
@@ -803,7 +803,7 @@ extension DatabaseWriter {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping (Database) throws -> Output)
updates: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -868,8 +868,8 @@ extension DatabaseWriter {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
{
@@ -885,7 +885,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
self.spawnConcurrentRead { [updatesValue] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -1003,7 +1003,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -1012,7 +1012,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -1023,7 +1023,7 @@ extension AnyDatabaseWriter: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
base._add(
@@ -1044,11 +1044,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -1056,11 +1056,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
+6 -3
View File
@@ -166,7 +166,10 @@ extension FetchRequest {
///
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
public func adapted(
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter)
-> AdaptedFetchRequest<Self>
{
AdaptedFetchRequest(self, adapter)
}
}
@@ -176,11 +179,11 @@ extension FetchRequest {
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: (Database) throws -> any RowAdapter
let adapter: @Sendable (Database) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
+13 -13
View File
@@ -1447,7 +1447,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -1476,7 +1476,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -1505,7 +1505,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -1589,7 +1589,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -1618,7 +1618,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -1647,7 +1647,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -1736,7 +1736,7 @@ extension Row {
/// - request: A FetchRequest.
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows, nil)
@@ -1768,7 +1768,7 @@ extension Row {
/// - request: A FetchRequest.
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
@@ -1804,7 +1804,7 @@ extension Row {
/// - request: A FetchRequest.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
@@ -1874,7 +1874,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
try Row.fetchAll(db, self)
}
@@ -1895,7 +1895,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A set of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
try Row.fetchSet(db, self)
}
@@ -1916,7 +1916,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
try Row.fetchOne(db, self)
}
}
@@ -2059,7 +2059,7 @@ typealias RowIndex = Row.Index
extension Row {
/// An index to a (column, value) pair in a ``Row``.
public struct Index {
public struct Index: Sendable {
let index: Int
init(_ index: Int) { self.index = index }
}
+2 -2
View File
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
/// print(Array(adaptedRow.columnNames))
/// ```
public struct RenameColumnAdapter: RowAdapter {
let transform: (String) -> String
let transform: @Sendable (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping (String) -> String) {
public init(_ transform: @escaping @Sendable (String) -> String) {
self.transform = transform
}
+1 -1
View File
@@ -223,7 +223,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping (Database) -> Void) {
func async(_ block: @escaping @Sendable (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+9 -9
View File
@@ -312,7 +312,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -346,7 +346,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -384,7 +384,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - adapter: Optional RowAdapter
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -461,7 +461,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -496,7 +496,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -530,7 +530,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - adapter: Optional RowAdapter
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -619,7 +619,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -656,7 +656,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -692,7 +692,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - request: A FetchRequest.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -1,10 +1,10 @@
import Foundation
/// A database value that holds date components.
public struct DatabaseDateComponents {
public struct DatabaseDateComponents: Sendable {
/// The SQLite formats for date components.
public enum Format: String {
public enum Format: String, Sendable {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock {
public protocol TransactionClock: Sendable {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
///
/// 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 {
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: (Database) throws -> Date
let _now: @Sendable (Database) throws -> Date
public init(_ now: @escaping (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
self._now = now
}
+3 -3
View File
@@ -135,7 +135,7 @@ extension Database {
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent {
public enum TransactionObservationExtent: Sendable {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
@@ -1064,7 +1064,7 @@ protocol DatabaseEventProtocol {
/// ``TransactionObserver`` protocol for more information.
public struct DatabaseEvent {
/// An event kind.
public enum Kind: CInt {
public enum Kind: CInt, Sendable {
/// An insertion event
case insert = 18 // SQLITE_INSERT
@@ -1182,7 +1182,7 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
public struct DatabasePreUpdateEvent {
/// An event kind
public enum Kind: CInt {
public enum Kind: CInt, Sendable {
/// SQLITE_INSERT
case insert = 18
+27 -7
View File
@@ -5,8 +5,10 @@
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
class WALSnapshotTransaction {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
// nil when closed
private var reader: SerializedDatabase?
// nil when closed
private var release: ((_ isInsideTransaction: Bool) -> Void)?
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -59,21 +61,39 @@ class WALSnapshotTransaction {
}
deinit {
Self.commitAndRelease(reader: reader, release: release)
close()
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
func read<T>(_ value: (Database) throws -> T) throws -> T {
guard let reader else {
throw DatabaseError.snapshotIsLost()
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
try reader.sync(value)
return try reader.sync(value)
}
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping (Database) -> Void) {
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
guard let reader else {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
reader.async { db in
value(.success(db))
}
}
func close() {
guard let reader, let release else { return }
self.reader = nil
self.release = nil
Self.commitAndRelease(reader: reader, release: release)
}
private static func commitAndRelease(
+1 -1
View File
@@ -16,7 +16,7 @@
/// - ``init(matchingAllTokensIn:)``
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
public struct FTS3Pattern {
public struct FTS3Pattern: Sendable {
/// The raw pattern string.
///
/// It is guaranteed to be a valid FTS3/4 pattern.
+1 -1
View File
@@ -20,7 +20,7 @@
/// - ``simple``
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
/// - ``FTS3/Diacritics``
public struct FTS3TokenizerDescriptor {
public struct FTS3TokenizerDescriptor: Sendable {
let name: String
let arguments: [String]
+1 -1
View File
@@ -16,7 +16,7 @@
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
/// - ``init(matchingPrefixPhrase:)``
public struct FTS5Pattern {
public struct FTS5Pattern: Sendable {
/// The raw pattern string.
///
+1 -1
View File
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
/// The reason why FTS5 is requesting tokenization.
///
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5Tokenization: OptionSet {
public struct FTS5Tokenization: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -24,7 +24,7 @@
/// ### Instantiating Tokenizers
///
/// - ``Database/makeTokenizer(_:)``
public struct FTS5TokenizerDescriptor {
public struct FTS5TokenizerDescriptor: Sendable {
/// The tokenizer components.
///
/// For example:
+1 -1
View File
@@ -4,7 +4,7 @@ import Foundation
/// Flags that tell SQLite how to register a token.
///
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5TokenFlags: OptionSet {
public struct FTS5TokenFlags: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -73,7 +73,7 @@
/// > .fetchAll(db)
/// > }
/// > ```
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
public var name: String
/// Creates a `JSONColumn` given its name.
+3 -3
View File
@@ -40,7 +40,7 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks {
/// The migration runs with disabled foreign keys.
@@ -207,7 +207,7 @@ public struct DatabaseMigrator {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping (Database) throws -> Void)
migrate: @escaping @Sendable (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -264,7 +264,7 @@ public struct DatabaseMigrator {
/// from succeeding.
public func asyncMigrate(
_ writer: some DatabaseWriter,
completion: @escaping (Result<Database, Error>) -> Void)
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
+2 -2
View File
@@ -1,5 +1,5 @@
/// An internal struct that defines a migration.
struct Migration {
struct Migration: Sendable {
enum ForeignKeyChecks {
case deferred
case immediate
@@ -8,7 +8,7 @@ struct Migration {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: (Database) throws -> Void
let migrate: @Sendable (Database) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
+1 -1
View File
@@ -80,7 +80,7 @@
/// using: Book.translatorForeignKey)
/// }
/// ```
public struct ForeignKey: Equatable {
public struct ForeignKey: Equatable, Sendable {
var originColumns: [String]
var destinationColumns: [String]?
@@ -173,7 +173,10 @@ extension Association {
// SelectionRequest conformance
extension Association {
public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
withDestinationRelation { relation in
relation = relation.selectWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -181,7 +184,10 @@ extension Association {
}
}
public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
withDestinationRelation { relation in
relation = relation.annotatedWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -192,7 +198,10 @@ extension Association {
// FilteredRequest conformance
extension Association {
public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
withDestinationRelation { relation in
relation = relation.filterWhenConnected { db in
try predicate(db).sqlExpression
@@ -203,7 +212,10 @@ extension Association {
// OrderedRequest conformance
extension Association {
public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self {
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
-> Self
{
withDestinationRelation { relation in
relation = relation.orderWhenConnected { db in
try orderings(db).map(\.sqlOrdering)
@@ -239,7 +251,10 @@ extension Association {
// AggregatingRequest conformance
extension Association {
public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self {
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
-> Self
{
withDestinationRelation { relation in
relation = relation.groupWhenConnected { db in
try expressions(db).map(\.sqlExpression)
@@ -247,7 +262,10 @@ extension Association {
}
}
public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
withDestinationRelation { relation in
relation = relation.havingWhenConnected { db in
try predicate(db).sqlExpression
@@ -117,7 +117,7 @@ extension QueryInterfaceRequest: FetchRequest {
extension QueryInterfaceRequest: SelectionRequest {
public func selectWhenConnected(
_ selection: @escaping (Database) throws -> [any SQLSelectable])
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -281,7 +281,7 @@ extension QueryInterfaceRequest: SelectionRequest {
}
public func annotatedWhenConnected(
with selection: @escaping (Database) throws -> [any SQLSelectable])
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -294,7 +294,7 @@ extension QueryInterfaceRequest: SelectionRequest {
extension QueryInterfaceRequest: FilteredRequest {
public func filterWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -307,7 +307,7 @@ extension QueryInterfaceRequest: FilteredRequest {
extension QueryInterfaceRequest: OrderedRequest {
public func orderWhenConnected(
_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm])
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
-> Self
{
with {
@@ -354,7 +354,7 @@ extension QueryInterfaceRequest: OrderedRequest {
extension QueryInterfaceRequest: AggregatingRequest {
public func groupWhenConnected(
_ expressions: @escaping (Database) throws -> [any SQLExpressible])
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
-> Self
{
with {
@@ -365,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
public func havingWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -58,7 +58,7 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
/// Appends result columns to the selected columns.
///
@@ -78,7 +78,7 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
}
extension SelectionRequest {
@@ -240,7 +240,7 @@ public protocol FilteredRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
}
extension FilteredRequest {
@@ -729,7 +729,7 @@ public protocol AggregatingRequest {
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self
/// Filters the aggregated groups with a boolean SQL expression.
///
@@ -753,7 +753,7 @@ public protocol AggregatingRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
}
extension AggregatingRequest {
@@ -934,7 +934,7 @@ public protocol OrderedRequest {
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self
/// Returns a request with reversed ordering.
///
+1 -1
View File
@@ -92,7 +92,7 @@ extension ColumnExpression where Self == Column {
///
/// - ``init(_:)-5grmu``
/// - ``init(_:)-7xc4z``
public struct Column {
public struct Column: Sendable {
/// The hidden rowID column.
public static let rowID = Column("rowid")
+1 -1
View File
@@ -315,7 +315,7 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
public struct AssociativeBinaryOperator: Hashable {
public struct AssociativeBinaryOperator: Hashable, Sendable {
/// The SQL operator
let sql: String
+6 -6
View File
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
+1 -1
View File
@@ -324,7 +324,7 @@ extension SQLSelection: SQLSelectable {
/// let players = try Player.select(AllColumns()).fetchAll(db)
/// }
/// ```
public struct AllColumns {
public struct AllColumns: Sendable {
/// The `*` selection.
public init() { }
}
+14 -14
View File
@@ -138,7 +138,7 @@
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
public struct Table<RowDecoder> {
public struct Table<RowDecoder>: Sendable {
/// The table name.
public var tableName: String
@@ -800,7 +800,7 @@ extension Table {
/// ```
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
@Sendable public func fetchCount(_ db: Database) throws -> Int {
try all().fetchCount(db)
}
}
@@ -860,7 +860,7 @@ extension Table where RowDecoder: FetchableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
@@ -880,7 +880,7 @@ extension Table where RowDecoder: FetchableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
@@ -902,7 +902,7 @@ extension Table where RowDecoder: FetchableRecord & Hashable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
@@ -961,7 +961,7 @@ extension Table where RowDecoder == Row {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
try all().fetchAll(db)
}
@@ -980,7 +980,7 @@ extension Table where RowDecoder == Row {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
try all().fetchOne(db)
}
@@ -999,7 +999,7 @@ extension Table where RowDecoder == Row {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
try all().fetchSet(db)
}
}
@@ -1034,7 +1034,7 @@ extension Table where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
@@ -1048,7 +1048,7 @@ extension Table where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
@@ -1061,7 +1061,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable {
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
@@ -1096,7 +1096,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
@@ -1110,7 +1110,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
@@ -1123,7 +1123,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
@@ -76,7 +76,7 @@ public final class ColumnDefinition {
/// The kind of a generated column.
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
public enum GeneratedColumnQualification {
public enum GeneratedColumnQualification: Sendable {
/// A `VIRTUAL` generated column.
case virtual
/// A `STORED` generated column.
@@ -681,7 +681,7 @@ extension Database {
}
/// View creation options
public struct ViewOptions: OptionSet {
public struct ViewOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -7,7 +7,7 @@ struct IndexDefinition {
}
/// Index creation options
public struct IndexOptions: OptionSet {
public struct IndexOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -1,5 +1,5 @@
/// Table creation options.
public struct TableOptions: OptionSet {
public struct TableOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
+7 -7
View File
@@ -466,7 +466,7 @@ extension Row {
/// var jsonData: Data
/// }
/// ```
public enum DatabaseDataEncodingStrategy {
public enum DatabaseDataEncodingStrategy: Sendable {
/// Encodes `Data` columns as SQL blob.
case deferredToData
@@ -474,7 +474,7 @@ public enum DatabaseDataEncodingStrategy {
case text
/// Encodes `Data` column as the result of the user-provided function.
case custom((Data) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) -> DatabaseValue {
switch self {
@@ -508,7 +508,7 @@ public enum DatabaseDataEncodingStrategy {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy {
public enum DatabaseDateEncodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
@@ -538,7 +538,7 @@ public enum DatabaseDateEncodingStrategy {
case formatted(DateFormatter)
/// Encodes the result of the user-provided function
case custom((Date) -> (any DatabaseValueConvertible)?)
case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?)
private static let iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
@@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy {
/// var uuid: UUID
/// }
/// ```
public enum DatabaseUUIDEncodingStrategy {
public enum DatabaseUUIDEncodingStrategy: Sendable {
/// The strategy that uses formatting from the UUID type.
///
/// It encodes UUIDs as 16-bytes data blobs.
@@ -626,7 +626,7 @@ public enum DatabaseUUIDEncodingStrategy {
/// var playerID: String
/// }
/// ```
public enum DatabaseColumnEncodingStrategy {
public enum DatabaseColumnEncodingStrategy: Sendable {
/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
@@ -634,7 +634,7 @@ public enum DatabaseColumnEncodingStrategy {
case convertToSnakeCase
/// A key encoding strategy defined by the closure you supply.
case custom((any CodingKey) -> String)
case custom(@Sendable (any CodingKey) -> String)
func column(forKey key: some CodingKey) -> String {
switch self {
+24 -12
View File
@@ -52,7 +52,7 @@ extension FetchableRecord where Self: TableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database) throws -> [Self] {
try all().fetchAll(db)
}
@@ -71,7 +71,7 @@ extension FetchableRecord where Self: TableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database) throws -> Self? {
try all().fetchOne(db)
}
}
@@ -92,7 +92,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database) throws -> Set<Self> {
try all().fetchSet(db)
}
}
@@ -154,7 +154,7 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: A sequence of primary keys.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll<Keys>(_ db: Database, keys: Keys)
@Sendable public static func fetchAll<Keys>(_ db: Database, keys: Keys)
throws -> [Self]
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
@@ -182,7 +182,7 @@ extension FetchableRecord where Self: TableRecord {
/// - key: A primary key value.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
if key.databaseValue.isNull {
// Don't hit the database
return nil
@@ -275,7 +275,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
/// - ids: A collection of primary keys.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
@Sendable public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
where IDS: Collection, IDS.Element == ID
{
if ids.isEmpty {
@@ -301,7 +301,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
/// - id: A primary key value.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
try filter(id: id).fetchOne(db)
}
@@ -346,7 +346,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
/// - keys: A sequence of primary keys.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet<Keys>(_ db: Database, keys: Keys)
@Sendable public static func fetchSet<Keys>(_ db: Database, keys: Keys)
throws -> Set<Self>
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
@@ -377,7 +377,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID:
/// - ids: A collection of primary keys.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
@Sendable public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
where IDS: Collection, IDS.Element == ID
{
if ids.isEmpty {
@@ -449,7 +449,11 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: An array of key dictionaries.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] {
@Sendable public static func fetchAll(
_ db: Database,
keys: [[String: (any DatabaseValueConvertible)?]])
throws -> [Self]
{
if keys.isEmpty {
// Avoid hitting the database
return []
@@ -473,7 +477,11 @@ extension FetchableRecord where Self: TableRecord {
/// - key: A key dictionary.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
@Sendable public static func fetchOne(
_ db: Database,
key: [String: (any DatabaseValueConvertible)?]?)
throws -> Self?
{
guard let key else {
// Avoid hitting the database
return nil
@@ -527,7 +535,11 @@ extension FetchableRecord where Self: TableRecord & Hashable {
/// - keys: An array of key dictionaries.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set<Self> {
@Sendable public static func fetchSet(
_ db: Database,
keys: [[String: (any DatabaseValueConvertible)?]])
throws -> Set<Self>
{
if keys.isEmpty {
// Avoid hitting the database
return []
+18 -18
View File
@@ -320,7 +320,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -348,7 +348,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -378,7 +378,7 @@ extension FetchableRecord where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -449,7 +449,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -478,7 +478,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -509,7 +509,7 @@ extension FetchableRecord where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -589,7 +589,7 @@ extension FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
@@ -624,7 +624,7 @@ extension FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
if let supplementaryFetch = request.supplementaryFetch {
guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else {
@@ -664,7 +664,7 @@ extension FetchableRecord where Self: Hashable {
/// - sql: a FetchRequest.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
@@ -746,7 +746,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -774,7 +774,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -805,7 +805,7 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
/// - sql: a FetchRequest.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
@@ -875,7 +875,7 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
/// var myData: Data
/// }
/// ```
public enum DatabaseDataDecodingStrategy {
public enum DatabaseDataDecodingStrategy: Sendable {
/// Decodes `Data` columns from SQL blobs and UTF8 text.
case deferredToData
@@ -884,7 +884,7 @@ public enum DatabaseDataDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Data?)
case custom(@Sendable (DatabaseValue) -> Data?)
}
// MARK: - DatabaseDateDecodingStrategy
@@ -901,7 +901,7 @@ public enum DatabaseDataDecodingStrategy {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy {
public enum DatabaseDateDecodingStrategy: Sendable {
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
@@ -942,7 +942,7 @@ public enum DatabaseDateDecodingStrategy {
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Date?)
case custom(@Sendable (DatabaseValue) -> Date?)
}
// MARK: - DatabaseColumnDecodingStrategy
@@ -959,7 +959,7 @@ public enum DatabaseDateDecodingStrategy {
/// // Decoded from the player_id column
/// var playerID: Int
/// }
public enum DatabaseColumnDecodingStrategy {
public enum DatabaseColumnDecodingStrategy: Sendable {
/// A key decoding strategy that doesn’t change key names during decoding.
case useDefaultKeys
@@ -967,7 +967,7 @@ public enum DatabaseColumnDecodingStrategy {
case convertFromSnakeCase
/// A key decoding strategy defined by the closure you supply.
case custom((String) -> CodingKey)
case custom(@Sendable (String) -> CodingKey)
func key<K: CodingKey>(forColumn column: String) -> K? {
switch self {
+1 -1
View File
@@ -348,7 +348,7 @@ extension MutablePersistableRecord {
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
///
/// See <https://www.sqlite.org/lang_conflict.html>
public struct PersistenceConflictPolicy {
public struct PersistenceConflictPolicy: Sendable {
/// The conflict resolution algorithm for insertions
public let conflictResolutionForInsert: Database.ConflictResolution
+1 -1
View File
@@ -224,7 +224,7 @@ extension TableRecord {
/// ```
///
/// - parameter db: A database connection.
public static func fetchCount(_ db: Database) throws -> Int {
@Sendable public static func fetchCount(_ db: Database) throws -> Int {
try all().fetchCount(db)
}
}
+5 -3
View File
@@ -46,6 +46,8 @@ final class Pool<T> {
}
}
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
private let makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
@@ -75,7 +77,7 @@ final class Pool<T> {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
func get() throws -> ElementAndRelease {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
@@ -107,7 +109,7 @@ final class Pool<T> {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -172,7 +174,7 @@ final class Pool<T> {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
+23 -1
View File
@@ -67,7 +67,7 @@ extension Dictionary {
}
extension DispatchQueue {
private static var mainKey: DispatchSpecificKey<()> = {
private static let mainKey: DispatchSpecificKey<()> = {
let key = DispatchSpecificKey<()>()
DispatchQueue.main.setSpecific(key: key, value: ())
return key
@@ -194,3 +194,25 @@ extension NSLocking {
#if !canImport(ObjectiveC)
@inlinable func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result { try body() }
#endif
/// A helper class that builds a DatabaseFuture without compiler errors
/// regarding concurrency.
final class UnsafeDatabaseFutureBuilder<T>: @unchecked Sendable {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<T, Error>? = nil
/// - precondition: MUST be called once.
func setResultAndReleaseFuture(_ result: Result<T, Error>) {
self.result = result
semaphore.signal()
}
/// - precondition: MUST be called once.
func makeFuture() -> DatabaseFuture<T> {
DatabaseFuture { [self] in
// Block the future until results are fetched
_ = semaphore.wait(timeout: .distantFuture)
return try result!.get()
}
}
}
@@ -1,3 +1,5 @@
import Foundation
/// A protocol indicating that an activity or action supports cancellation.
///
/// ## Topics
@@ -16,8 +18,13 @@ public protocol DatabaseCancellable {
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized.
public class AnyDatabaseCancellable: DatabaseCancellable {
private let lock = NSLock()
private var _cancel: (() -> Void)?
var isCancelled: Bool {
lock.withLock { _cancel == nil }
}
/// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping () -> Void) {
_cancel = cancel
@@ -25,21 +32,20 @@ public class AnyDatabaseCancellable: DatabaseCancellable {
/// Creates a cancellable object that forwards cancellation to `base`.
public convenience init(_ base: some DatabaseCancellable) {
var cancellable = Optional.some(base)
self.init {
cancellable?.cancel()
cancellable = nil // Release memory
base.cancel()
}
}
deinit {
_cancel?()
cancel()
}
public func cancel() {
// Don't prevent multiple concurrent calls to _cancel, because it is
// pointless. But release memory!
_cancel?()
lock.lock()
let cancel = _cancel
_cancel = nil
lock.unlock()
cancel?()
}
}
@@ -353,10 +353,11 @@ extension ValueConcurrentObserver {
let initialFetchTransaction = try result.get()
// Second async jump because that's how
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
initialFetchTransaction.asyncRead { db in
initialFetchTransaction.asyncRead { dbResult in
do {
let fetchedValue: Reducer.Fetched
let initialRegion: DatabaseRegion
let db = try dbResult.get()
switch self.trackingMode {
case let .constantRegion(regions):
@@ -430,11 +431,9 @@ extension ValueConcurrentObserver {
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// However, we want to close `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
// available for other reads.
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
let events = self.lock.synchronized { self.notificationCallbacks?.events }
@@ -447,7 +446,7 @@ extension ValueConcurrentObserver {
// Was the database modified since the initial fetch?
let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
assert(ordering <= 0, "Unexpected snapshot ordering")
isModified = ordering < 0
} else {
@@ -455,9 +454,9 @@ extension ValueConcurrentObserver {
isModified = true
}
// Comparison done: end the WAL snapshot transaction
// Comparison done: close the WAL snapshot transaction
// and release its reader connection.
initialFetchTransaction = nil
initialFetchTransaction.close()
if isModified {
events.databaseDidChange?()
@@ -1,7 +1,7 @@
import Foundation
/// The extent of the shared subscription to a ``SharedValueObservation``.
public enum SharedValueObservationExtent {
public enum SharedValueObservationExtent: Sendable {
/// The ``SharedValueObservation`` starts a single database observation,
/// which stops when the `SharedValueObservation` is deallocated and all
/// subscriptions terminated.
+8 -8
View File
@@ -82,8 +82,8 @@ struct ValueObservationEvents: Refinable {
}
typealias ValueObservationStart<T> = (
_ onError: @escaping (Error) -> Void,
_ onChange: @escaping (T) -> Void)
_ onError: @escaping @Sendable (Error) -> Void,
_ onChange: @escaping @Sendable (T) -> Void)
-> AnyDatabaseCancellable
extension ValueObservation: Refinable {
@@ -138,8 +138,8 @@ extension ValueObservation: Refinable {
public func start(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
where Reducer: ValueReducer
{
@@ -703,7 +703,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func trackingConstantRegion<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -764,7 +764,7 @@ extension ValueObservation {
public static func tracking<Value>(
region: any DatabaseRegionConvertible,
_ otherRegions: any DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -820,7 +820,7 @@ extension ValueObservation {
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
regions: [any DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -877,7 +877,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -17,11 +17,11 @@ public protocol ValueObservationScheduler {
/// If the result is true, then this method was called on the main thread.
func immediateInitialValue() -> Bool
func schedule(_ action: @escaping () -> Void)
func schedule(_ action: @escaping @Sendable () -> Void)
}
extension ValueObservationScheduler {
func scheduleInitial(_ action: @escaping () -> Void) {
func scheduleInitial(_ action: @escaping @Sendable () -> Void) {
if immediateInitialValue() {
action()
} else {
@@ -42,7 +42,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler {
public func immediateInitialValue() -> Bool { false }
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
queue.async(execute: action)
}
}
@@ -86,7 +86,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
return true
}
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
+2 -3
View File
@@ -8,7 +8,6 @@ OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5
//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1
//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK
// Enable concurrency warning in Swift 5.5
// https://twitter.com/olebegemann/status/1421144304127463427?lang=en
// Those as commented out by default, until minimum support Xcode version can handle them.
// Enable concurrency checks
// OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks
// SWIFT_STRICT_CONCURRENCY = complete
@@ -6,40 +6,47 @@ class DatabaseConfigurationTests: GRDBTestCase {
func testPrepareDatabase() throws {
// prepareDatabase is called when connection opens
var connectionCount = 0
class Context {
var connectionCount = 0
}
let context = Context()
var configuration = Configuration()
configuration.prepareDatabase { db in
connectionCount += 1
context.connectionCount += 1
}
_ = try DatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 1)
XCTAssertEqual(context.connectionCount, 1)
_ = try makeDatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 2)
XCTAssertEqual(context.connectionCount, 2)
let pool = try makeDatabasePool(configuration: configuration)
XCTAssertEqual(connectionCount, 3)
XCTAssertEqual(context.connectionCount, 3)
try pool.read { _ in }
XCTAssertEqual(connectionCount, 4)
XCTAssertEqual(context.connectionCount, 4)
try pool.makeSnapshot().read { _ in }
XCTAssertEqual(connectionCount, 5)
XCTAssertEqual(context.connectionCount, 5)
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
try pool.makeSnapshotPool().read { _ in }
XCTAssertEqual(connectionCount, 6)
XCTAssertEqual(context.connectionCount, 6)
#endif
}
func testPrepareDatabaseError() throws {
struct TestError: Error { }
var error: TestError?
class Context {
var error: TestError?
}
let context = Context()
var configuration = Configuration()
configuration.prepareDatabase { db in
if let error {
if let error = context.error {
throw error
}
}
@@ -47,36 +54,36 @@ class DatabaseConfigurationTests: GRDBTestCase {
// TODO: what about in-memory DatabaseQueue???
do {
error = TestError()
context.error = TestError()
_ = try makeDatabaseQueue(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
context.error = TestError()
_ = try makeDatabasePool(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = nil
context.error = nil
let pool = try makeDatabasePool(configuration: configuration)
do {
error = TestError()
context.error = TestError()
try pool.read { _ in }
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
context.error = TestError()
_ = try pool.makeSnapshot()
XCTFail("Expected TestError")
} catch is TestError { }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
do {
error = TestError()
context.error = TestError()
_ = try pool.makeSnapshotPool()
XCTFail("Expected TestError")
} catch is TestError { }
+8 -4
View File
@@ -122,7 +122,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
let expectation = self.expectation(description: "")
migrator.asyncMigrate(writer, completion: { dbResult in
migrator.asyncMigrate(writer, completion: { [migrator2] dbResult in
// No migration error
let db = try! dbResult.get()
@@ -789,13 +789,17 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
var witness = 1
class Context {
var witness = 1
}
let context = Context()
migrator.registerMigration("1") { db in
try db.execute(sql: """
CREATE TABLE t1(id INTEGER PRIMARY KEY);
INSERT INTO t1(id) VALUES (?)
""", arguments: [witness])
witness += 1
""", arguments: [context.witness])
context.witness += 1
}
let dbQueue = try makeDatabaseQueue()
@@ -1146,13 +1146,16 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testAsyncConcurrentReadOpensATransaction() throws {
let dbPool = try makeDatabasePool()
var isInsideTransaction: Bool? = nil
class Context {
var isInsideTransaction: Bool? = nil
}
let context = Context()
let expectation = self.expectation(description: "read")
dbPool.writeWithoutTransaction { db in
dbPool.asyncConcurrentRead { dbResult in
do {
let db = try dbResult.get()
isInsideTransaction = db.isInsideTransaction
context.isInsideTransaction = db.isInsideTransaction
do {
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
XCTFail("Expected error")
@@ -1165,7 +1168,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(isInsideTransaction, true)
XCTAssertEqual(context.isInsideTransaction, true)
}
func testAsyncConcurrentReadOutsideOfTransaction() throws {
@@ -1188,14 +1191,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// <
// }
var count: Int? = nil
class Context {
var count: Int?
}
let context = Context()
let expectation = self.expectation(description: "read")
try dbPool.writeWithoutTransaction { db in
dbPool.asyncConcurrentRead { dbResult in
do {
_ = s1.wait(timeout: .distantFuture)
let db = try dbResult.get()
count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
context.count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
} catch {
XCTFail("Unexpected error: \(error)")
}
@@ -1205,14 +1211,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
s1.signal()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 0)
XCTAssertEqual(context.count, 0)
}
func testAsyncConcurrentReadError() throws {
// Necessary for this test to run as quickly as possible
dbConfiguration.readonlyBusyMode = .immediateError
let dbPool = try makeDatabasePool()
var readError: DatabaseError? = nil
class Context {
var readError: DatabaseError? = nil
}
let context = Context()
let expectation = self.expectation(description: "read")
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
@@ -1224,12 +1233,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTFail("Unexpected result: \(dbResult)")
return
}
readError = dbError
context.readError = dbError
expectation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY)
XCTAssertEqual(readError!.message!, "database is locked")
XCTAssertEqual(context.readError!.resultCode, .SQLITE_BUSY)
XCTAssertEqual(context.readError!.message!, "database is locked")
}
}
+12 -6
View File
@@ -228,7 +228,10 @@ class DatabasePoolTests: GRDBTestCase {
let group = DispatchGroup()
// The maximum number of threads we could witness
var maxThreadCount: CInt = 0
class Context {
var maxThreadCount: CInt = 0
}
let context = Context()
let lock = NSLock()
for _ in (0..<numberOfConcurrentReads) {
@@ -240,14 +243,14 @@ class DatabasePoolTests: GRDBTestCase {
let threadsCount = getThreadsCount()
lock.lock()
maxThreadCount = max(maxThreadCount, threadsCount)
context.maxThreadCount = max(context.maxThreadCount, threadsCount)
lock.unlock()
group.leave()
}
}
group.wait()
XCTAssert(maxThreadCount < 50)
XCTAssert(context.maxThreadCount < 50)
#endif
}
@@ -270,7 +273,10 @@ class DatabasePoolTests: GRDBTestCase {
let group = DispatchGroup()
// The maximum number of threads we could witness
var maxThreadCount: CInt = 0
class Context {
var maxThreadCount: CInt = 0
}
let context = Context()
let lock = NSLock()
for _ in (0..<numberOfConcurrentReads) {
@@ -282,14 +288,14 @@ class DatabasePoolTests: GRDBTestCase {
let threadsCount = getThreadsCount()
lock.lock()
maxThreadCount = max(maxThreadCount, threadsCount)
context.maxThreadCount = max(context.maxThreadCount, threadsCount)
lock.unlock()
group.leave()
}
}
group.wait()
XCTAssert(maxThreadCount < 50)
XCTAssert(context.maxThreadCount < 50)
#endif
}
@@ -244,9 +244,13 @@ class ConcurrencyTests: GRDBTestCase {
// BEGIN EXCLUSIVE TRANSACTION
// COMMIT
var busyCallbackCalled = false
class Context {
var busyCallbackCalled = false
}
let context = Context()
self.busyCallback = { n in
busyCallbackCalled = true
context.busyCallbackCalled = true
s2.signal()
return true
}
@@ -283,7 +287,7 @@ class ConcurrencyTests: GRDBTestCase {
_ = group.wait(timeout: .distantFuture)
XCTAssertTrue(busyCallbackCalled)
XCTAssertTrue(context.busyCallbackCalled)
}
func testReaderDuringDefaultTransaction() throws {
@@ -384,9 +388,13 @@ class ConcurrencyTests: GRDBTestCase {
// COMMIT
// COMMIT
var busyCallbackCalled = false
class Context {
var busyCallbackCalled = false
}
let context = Context()
self.busyCallback = { n in
busyCallbackCalled = true
context.busyCallbackCalled = true
s3.signal()
return true
}
@@ -431,6 +439,6 @@ class ConcurrencyTests: GRDBTestCase {
_ = group.wait(timeout: .distantFuture)
XCTAssertTrue(busyCallbackCalled)
XCTAssertTrue(context.busyCallbackCalled)
}
}
+7 -3
View File
@@ -205,15 +205,19 @@ class DatabaseReaderTests : GRDBTestCase {
// MARK: - AsyncRead
func testAsyncRead() throws {
class Context {
var count: Int?
}
func test(_ dbReader: some DatabaseReader) throws {
let context = Context()
let expectation = self.expectation(description: "updates")
let semaphore = DispatchSemaphore(value: 0)
var count: Int?
dbReader.asyncRead { dbResult in
// Make sure this block executes asynchronously
semaphore.wait()
do {
count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
context.count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
} catch {
XCTFail("Unexpected error: \(error)")
}
@@ -222,7 +226,7 @@ class DatabaseReaderTests : GRDBTestCase {
semaphore.signal()
waitForExpectations(timeout: 1, handler: nil)
XCTAssertNotNil(count)
XCTAssertNotNil(context.count)
}
try test(makeDatabaseQueue())
+13 -6
View File
@@ -114,11 +114,14 @@ class DatabaseTraceTests : GRDBTestCase {
}
func testTraceFromConfigurationWithDefaultOptions() throws {
var events: [String] = []
class Context {
var events: [String] = []
}
let context = Context()
var configuration = Configuration()
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
context.events.append("SQL: \(event)")
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
@@ -127,19 +130,23 @@ class DatabaseTraceTests : GRDBTestCase {
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
XCTAssertEqual(context.events.suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (?)"])
}
}
func testTraceFromConfigurationWithPublicStatementArguments() throws {
var events: [String] = []
class Context {
var events: [String] = []
}
let context = Context()
var configuration = Configuration()
configuration.publicStatementArguments = true
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
context.events.append("SQL: \(event)")
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
@@ -148,7 +155,7 @@ class DatabaseTraceTests : GRDBTestCase {
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
XCTAssertEqual(context.events.suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (1)"])
}
+9 -6
View File
@@ -272,16 +272,19 @@ class FTS4TableBuilderTests: GRDBTestCase {
func testFTS4Compression() throws {
// Based on https://github.com/groue/GRDB.swift/issues/369
var compressCalled = false
var uncompressCalled = false
class Context {
var compressCalled = false
var uncompressCalled = false
}
let context = Context()
dbConfiguration.prepareDatabase { db in
db.add(function: DatabaseFunction("zipit", argumentCount: 1, pure: true, function: { dbValues in
compressCalled = true
context.compressCalled = true
return dbValues[0]
}))
db.add(function: DatabaseFunction("unzipit", argumentCount: 1, pure: true, function: { dbValues in
uncompressCalled = true
context.uncompressCalled = true
return dbValues[0]
}))
}
@@ -296,12 +299,12 @@ class FTS4TableBuilderTests: GRDBTestCase {
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(content, compress=\"zipit\", uncompress=\"unzipit\")")
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["abc"])
XCTAssertTrue(compressCalled)
XCTAssertTrue(context.compressCalled)
}
try dbPool.read { db in
_ = try Row.fetchOne(db, sql: "SELECT * FROM documents")
XCTAssertTrue(uncompressCalled)
XCTAssertTrue(context.uncompressCalled)
}
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ private class Person : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)")
}
@@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)")
}
@@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)")
}
@@ -16,7 +16,7 @@ private class Person : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
creationDate TEXT NOT NULL,
@@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE citizenships (
personName TEXT NOT NULL,
@@ -14,7 +14,7 @@ private class Item : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE items (
name TEXT,
@@ -16,7 +16,7 @@ private class Person : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -12,7 +12,7 @@ class Pet : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE pets (
UUID TEXT NOT NULL PRIMARY KEY,
@@ -11,7 +11,7 @@ class Email : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE emails (
email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE,
+1 -1
View File
@@ -15,7 +15,7 @@ private class Person : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -13,7 +13,7 @@ class BadlyMangledStuff : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)")
}
@@ -523,10 +523,13 @@ class SharedValueObservationTests: GRDBTestCase {
}
let log = Log()
var fetchError: Error? = nil
class Context {
var fetchError: Error? = nil
}
let context = Context()
let publisher = ValueObservation
.tracking { db -> Int in
if let error = fetchError { throw error }
if let error = context.fetchError { throw error }
return try Table("player").fetchCount(db)
}
.print(to: log)
@@ -540,7 +543,7 @@ class SharedValueObservationTests: GRDBTestCase {
try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0)
try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0)
fetchError = TestError()
context.fetchError = TestError()
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
@@ -557,7 +560,7 @@ class SharedValueObservationTests: GRDBTestCase {
}
do {
fetchError = nil
context.fetchError = nil
let recorder = publisher.record()
if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") }
XCTAssertEqual(log.flush(), [])
@@ -579,10 +582,13 @@ class SharedValueObservationTests: GRDBTestCase {
}
let log = Log()
var fetchError: Error? = nil
class Context {
var fetchError: Error? = nil
}
let context = Context()
let publisher = ValueObservation
.tracking { db -> Int in
if let error = fetchError { throw error }
if let error = context.fetchError { throw error }
return try Table("player").fetchCount(db)
}
.print(to: log)
@@ -596,7 +602,7 @@ class SharedValueObservationTests: GRDBTestCase {
try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0)
try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0)
fetchError = TestError()
context.fetchError = TestError()
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
@@ -613,7 +619,7 @@ class SharedValueObservationTests: GRDBTestCase {
}
do {
fetchError = nil
context.fetchError = nil
let recorder = publisher.record()
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 1"])
+106 -41
View File
@@ -3,14 +3,22 @@ import GRDB
class TransactionDateTests: GRDBTestCase {
func testTransactionDateOutsideOfTransaction() throws {
let dates = [
class Context {
let dates: [Date]
var dateIterator: [Date].Iterator
init(dates: [Date]) {
self.dates = dates
self.dateIterator = dates.makeIterator()
}
}
let context = Context(dates: [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
])
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -19,18 +27,26 @@ class TransactionDateTests: GRDBTestCase {
try collectedDates.append(db.transactionDate)
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, dates)
XCTAssertEqual(collectedDates, context.dates)
}
func testTransactionDateInsideTransaction_commit() throws {
let dates = [
class Context {
let dates: [Date]
var dateIterator: [Date].Iterator
init(dates: [Date]) {
self.dates = dates
self.dateIterator = dates.makeIterator()
}
}
let context = Context(dates: [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
])
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -42,18 +58,31 @@ class TransactionDateTests: GRDBTestCase {
try db.execute(sql: "COMMIT")
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]])
XCTAssertEqual(collectedDates, [
context.dates[0],
context.dates[1],
context.dates[1],
context.dates[2],
])
}
func testTransactionDateInsideTransaction_rollback() throws {
let dates = [
class Context {
let dates: [Date]
var dateIterator: [Date].Iterator
init(dates: [Date]) {
self.dates = dates
self.dateIterator = dates.makeIterator()
}
}
let context = Context(dates: [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
])
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -65,18 +94,31 @@ class TransactionDateTests: GRDBTestCase {
try db.execute(sql: "ROLLBACK")
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]])
XCTAssertEqual(collectedDates, [
context.dates[0],
context.dates[1],
context.dates[1],
context.dates[2],
])
}
func testTransactionDateInsideTransaction_rollbackingError() throws {
let dates = [
class Context {
let dates: [Date]
var dateIterator: [Date].Iterator
init(dates: [Date]) {
self.dates = dates
self.dateIterator = dates.makeIterator()
}
}
let context = Context(dates: [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
])
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -92,7 +134,12 @@ class TransactionDateTests: GRDBTestCase {
""")
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]])
XCTAssertEqual(collectedDates, [
context.dates[0],
context.dates[1],
context.dates[1],
context.dates[2],
])
}
func test_TimestampedRecord_default_willInsert() throws {
@@ -107,8 +154,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -119,7 +169,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
do {
var player = Player(name: "Arthur")
@@ -152,8 +202,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -164,14 +217,14 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur")
try player.insert(db)
}
let newTransactionDate = Date()
currentDate = newTransactionDate
context.currentDate = newTransactionDate
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
@@ -198,8 +251,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -210,14 +266,14 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur")
try player.insert(db)
}
let newTransactionDate = Date()
currentDate = newTransactionDate
context.currentDate = newTransactionDate
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
@@ -251,8 +307,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -267,12 +326,12 @@ class TransactionDateTests: GRDBTestCase {
}
let newTransactionDate = Date()
currentDate = newTransactionDate
context.currentDate = newTransactionDate
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
try player.touch(db)
XCTAssertEqual(player.modificationDate, newTransactionDate)
try player.touch(db, modificationDate: .distantFuture)
XCTAssertEqual(player.modificationDate, .distantFuture)
}
@@ -303,8 +362,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -315,7 +377,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur", isInserted: false)
try player.insert(db)
@@ -354,8 +416,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -366,7 +431,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
let player = Player(name: "Arthur")
try player.insert(db)
@@ -410,11 +410,14 @@ class ValueObservationPrintTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
}
let context = Context()
let observation = ValueObservation
.trackingConstantRegion { db -> Int? in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
@@ -461,11 +464,14 @@ class ValueObservationPrintTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
}
let context = Context()
let observation = ValueObservation
.trackingConstantRegion { db -> Int? in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
@@ -130,7 +130,10 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
""")
}
var results: [Int] = []
class Context {
var results: [Int] = []
}
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
@@ -147,7 +150,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
results.append(count)
context.results.append(count)
notificationExpectation.fulfill()
})
@@ -162,7 +165,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [0, 1, 2, 3])
XCTAssertEqual(context.results, [0, 1, 2, 3])
XCTAssertEqual(regions.map(\.description), [
"a(value),source(name)",
@@ -181,7 +184,10 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
""")
}
var results: [Int] = []
class Context {
var results: [Int] = []
}
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
@@ -199,7 +205,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
results.append(count)
context.results.append(count)
notificationExpectation.fulfill()
})
@@ -214,7 +220,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [0, 1, 2, 3])
XCTAssertEqual(context.results, [0, 1, 2, 3])
XCTAssertEqual(regions.map(\.description), [
"a(value),source(name)",
+82 -63
View File
@@ -5,19 +5,22 @@ import Dispatch
class ValueObservationTests: GRDBTestCase {
func testImmediateError() throws {
struct TestError: Error { }
class Context {
var error: TestError?
}
func test(_ dbWriter: some DatabaseWriter) throws {
// Create an observation
let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() }
// Start observation
var error: TestError?
let context = Context()
_ = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { error = $0 as? TestError },
onError: { context.error = $0 as? TestError },
onChange: { _ in })
XCTAssertNotNil(error)
XCTAssertNotNil(context.error)
}
try test(makeDatabaseQueue())
@@ -26,36 +29,39 @@ class ValueObservationTests: GRDBTestCase {
func testErrorCompletesTheObservation() throws {
struct TestError: Error { }
class Context {
var nextError: Error? = nil // If not null, observation throws an error
var errorCaught = false
}
func test(_ dbWriter: some DatabaseWriter) throws {
// We need something to change
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
// Track reducer process
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
notificationExpectation.isInverted = true
var nextError: Error? = nil // If not null, observation throws an error
let observation = ValueObservation.trackingConstantRegion {
_ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")
if let error = nextError {
if let error = context.nextError {
throw error
}
}
// Start observation
var errorCaught = false
let cancellable = observation.start(
in: dbWriter,
onError: { _ in
errorCaught = true
context.errorCaught = true
notificationExpectation.fulfill()
},
onChange: {
XCTAssertFalse(errorCaught)
nextError = TestError()
XCTAssertFalse(context.errorCaught)
context.nextError = TestError()
notificationExpectation.fulfill()
// Trigger another change
try! dbWriter.writeWithoutTransaction { db in
@@ -65,7 +71,7 @@ class ValueObservationTests: GRDBTestCase {
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertTrue(errorCaught)
XCTAssertTrue(context.errorCaught)
}
}
@@ -325,10 +331,14 @@ class ValueObservationTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
@@ -341,18 +351,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0])
XCTAssertEqual(context.observedCounts, [0, 0])
}
}
@@ -365,10 +374,14 @@ class ValueObservationTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
@@ -381,18 +394,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0])
XCTAssertEqual(context.observedCounts, [0, 0])
}
}
@@ -405,10 +417,14 @@ class ValueObservationTests: GRDBTestCase {
// Allow pool to perform a single initial fetch, because between
// its first read access, and its write access that installs the
// transaction observer, no write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
try! dbPool.write { db in
try db.execute(sql: """
@@ -431,18 +447,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, expectedCounts)
XCTAssertEqual(context.observedCounts, expectedCounts)
}
}
@@ -455,10 +470,14 @@ class ValueObservationTests: GRDBTestCase {
// Allow pool to perform a single initial fetch, because between
// its first read access, and its write access that installs the
// transaction observer, no write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
try! dbPool.write { db in
try db.execute(sql: """
@@ -481,18 +500,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, expectedCounts)
XCTAssertEqual(context.observedCounts, expectedCounts)
}
}
@@ -531,7 +549,11 @@ class ValueObservationTests: GRDBTestCase {
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
// Track reducer process
var changesCount = 0
class Context {
var changesCount = 0
var cancellable: (any DatabaseCancellable)?
}
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
@@ -542,14 +564,13 @@ class ValueObservationTests: GRDBTestCase {
}
// Start observation and deallocate cancellable after second change
var cancellable: (any DatabaseCancellable)?
cancellable = observation.start(
context.cancellable = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { _ in
changesCount += 1
if changesCount == 2 {
cancellable = nil
context.changesCount += 1
if context.changesCount == 2 {
context.cancellable = nil
}
notificationExpectation.fulfill()
})
@@ -564,11 +585,8 @@ class ValueObservationTests: GRDBTestCase {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
// Avoid "Variable 'cancellable' was written to, but never read" warning
_ = cancellable
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(changesCount, 2)
XCTAssertEqual(context.changesCount, 2)
}
func testCancellableExplicitCancellation() throws {
@@ -577,7 +595,11 @@ class ValueObservationTests: GRDBTestCase {
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
// Track reducer process
var changesCount = 0
class Context {
var changesCount = 0
var cancellable: (any DatabaseCancellable)!
}
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
@@ -588,32 +610,29 @@ class ValueObservationTests: GRDBTestCase {
}
// Start observation and cancel cancellable after second change
var cancellable: (any DatabaseCancellable)!
cancellable = observation.start(
context.cancellable = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { _ in
changesCount += 1
if changesCount == 2 {
cancellable.cancel()
context.changesCount += 1
if context.changesCount == 2 {
context.cancellable.cancel()
}
notificationExpectation.fulfill()
})
try withExtendedLifetime(cancellable) {
// notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
// not notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(changesCount, 2)
// notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
// not notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(context.changesCount, 2)
}
func testCancellableInvalidation1() throws {