read(_:)
Executes read-only database operations, and returns their result after they have finished executing.
func read<T>(_ value: @escaping (Database) throws -> T) async throws -> T where T : Sendable
Parameters
- value
A closure which accesses the database.
Throws
Any DatabaseError
that happens while establishing the database access, or the error thrown by value
, or CancellationError
if the task is cancelled.
For example:
let count = try await reader.read { db in
try Player.fetchCount(db)
}
Database operations are isolated in a transaction: they do not see changes performed by eventual concurrent writes (even writes performed by other processes).
The database connection is read-only: attempts to write throw a DatabaseError
with resultCode SQLITE_READONLY
.
The Database
argument to value
is valid only during the execution of the closure. Do not store or return the database connection for later use.