mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-25 04:07:47 +00:00
Cleanup
This commit is contained in:
1 parent
ea3f22c8a4
commit
a46505e907
3 files changed
+364
-351
No files matched your search
@@ -150,7 +150,9 @@ public final class Database {
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) }
|
||||
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
|
||||
try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS"))
|
||||
}
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
@@ -527,6 +529,25 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Read-Only Access
|
||||
|
||||
/// Grants read-only access, starting SQLite 3.8.0
|
||||
func readOnly<T>(_ block: () throws -> T) rethrows -> T {
|
||||
if configuration.readonly {
|
||||
return try block()
|
||||
}
|
||||
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
// Assume those pragmas never fail
|
||||
try! execute("PRAGMA query_only = 1")
|
||||
defer { try! execute("PRAGMA query_only = 0") }
|
||||
return try block()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Transactions & Savepoint
|
||||
@@ -548,7 +569,7 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
@@ -679,7 +700,7 @@ extension Database {
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil). If nil, the
|
||||
/// transaction type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
|
||||
+190
-196
@@ -9,7 +9,7 @@ import Foundation
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
@@ -315,8 +315,8 @@ extension DatabasePool : DatabaseReader {
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
@@ -335,199 +335,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbPool.add(function: fn)
|
||||
/// try dbPool.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
writer.sync { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
writer.sync { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbPool.add(collation: collation)
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result of the block.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or by the wrapping transaction.
|
||||
public func write<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try writer.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// The block is guaranteed to be executed outside of a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue,
|
||||
/// wrapped in a deferred transaction.
|
||||
///
|
||||
@@ -635,6 +442,193 @@ extension DatabasePool : DatabaseWriter {
|
||||
throw readError
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result of the block.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements.
|
||||
/// - throws: The error thrown by the block, or by the wrapping transaction.
|
||||
public func write<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try writer.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// The block is guaranteed to be executed outside of a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbPool.add(function: fn)
|
||||
/// try dbPool.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
writer.sync { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
writer.sync { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbPool.add(collation: collation)
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
+150
-152
@@ -5,7 +5,7 @@ import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
@@ -68,63 +68,6 @@ public final class DatabaseQueue {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try serializedDatabase.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
@@ -193,7 +136,7 @@ extension DatabaseQueue {
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@@ -201,31 +144,35 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// and returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this meethod throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return try serializedDatabase.sync { try readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
return try serializedDatabase.sync { try readOnly($0, block) }
|
||||
} else {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
#endif
|
||||
return try serializedDatabase.sync { db in
|
||||
try db.readOnly { try block(db) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.unsafeRead { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
@@ -234,18 +181,143 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantRead { db in
|
||||
/// try db.execute(...)
|
||||
/// let players = try dbQueue.unsafeReentrantRead { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this meethod throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// Check that we're on the correct queue...
|
||||
serializedDatabase.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
db.readOnly { block(db) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that executes SQL statements.
|
||||
/// - throws: An eventual database error, or the error thrown by the block.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try serializedDatabase.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.writeWithoutTransaction { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// // INSERT INTO players ...
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// // INSERT INTO players ...
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -290,77 +362,3 @@ extension DatabaseQueue : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.writeWithoutTransaction`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// Check that we're on the correct queue...
|
||||
serializedDatabase.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
readOnly(db, block)
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
readOnly(db, block)
|
||||
} else {
|
||||
block(db)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Unsafe Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
}
|
||||
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
guard !db.configuration.readonly else {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
// Assume those pragmas never fail
|
||||
try! db.internalCachedUpdateStatement("PRAGMA query_only = 1").execute()
|
||||
defer { try! db.internalCachedUpdateStatement("PRAGMA query_only = 0").execute() }
|
||||
return try block(db)
|
||||
}
|
||||
Reference in new issue
Block a user