mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-25 04:07:47 +00:00
Merge branch 'development' into dev/async
This commit is contained in:
commit
1a87faacfa
18 files changed
+499
-39
No files matched your search
@@ -86,6 +86,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- **New**: [#1079](https://github.com/groue/GRDB.swift/pull/1079) by [@groue](https://github.com/groue): Async / Await
|
||||
- **New**: [#1088](https://github.com/groue/GRDB.swift/pull/1088) by [@groue](https://github.com/groue): Shared ValueObservation
|
||||
- **New**: `DatabasePool.erase()` prevents concurrent reads until it has completed.
|
||||
- **New**: A new `close()` method allows precise closing of database connections.
|
||||
- **Fixed**: Filtering records by primary key now properly encodes dates and uuids according to the customized strategies (`filter(id:)`, `deleteAll(_:keys:)`, etc.)
|
||||
- **Documentation Update**: The [Concurrency Guide](Documentation/Concurrency.md) has been fully rewritten, and introduces the new support for Swift concurrency (async/await).
|
||||
- **Documentation Update**: The [Date and UUID Coding Strategies](README.md#date-and-uuid-coding-strategies) was updated for the new support for customized date and uuid primary key coding.
|
||||
|
||||
+19
-6
@@ -78,8 +78,10 @@
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -87,7 +89,7 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</RemoteRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -95,8 +97,10 @@
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -104,7 +108,16 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -1373,6 +1373,7 @@
|
||||
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
|
||||
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
@@ -2459,6 +2460,7 @@
|
||||
DC10500F19C904DD00D8CA30 /* Tests */,
|
||||
DC3773F419C8CBB3004FCF85 /* Products */,
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */,
|
||||
5643676D272EDF2400C718C7 /* Scripts */,
|
||||
);
|
||||
indentWidth = 4;
|
||||
sourceTree = "<group>";
|
||||
@@ -2859,7 +2861,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
};
|
||||
56EB54FA22C9115E00850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
@@ -2877,7 +2879,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
};
|
||||
AAA4DCFA230F1E0600C74B15 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
@@ -2895,7 +2897,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
|
||||
+56
-12
@@ -26,7 +26,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - SQLite C API
|
||||
|
||||
/// The raw SQLite connection, suitable for the SQLite C API.
|
||||
public let sqliteConnection: SQLiteConnection
|
||||
/// It is constant, until close() sets it to nil.
|
||||
public var sqliteConnection: SQLiteConnection?
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
@@ -112,7 +113,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// > connection while this routine is running, then the return value
|
||||
// > is undefined.
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
if isClosed { return false } // Support for SerializedDatabase.deinit
|
||||
if sqliteConnection == nil { return false } // Support for SerializedDatabase.deinit
|
||||
return sqlite3_get_autocommit(sqliteConnection) == 0
|
||||
}
|
||||
|
||||
@@ -182,7 +183,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
|
||||
private var isClosed = false
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
@@ -197,7 +197,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
deinit {
|
||||
assert(isClosed)
|
||||
assert(sqliteConnection == nil)
|
||||
}
|
||||
|
||||
// MARK: - Database Opening
|
||||
@@ -216,7 +216,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
|
||||
// > pointer argument is a harmless no-op.
|
||||
sqlite3_close(sqliteConnection)
|
||||
_ = sqlite3_close(sqliteConnection) // ignore result code
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
if let sqliteConnection = sqliteConnection {
|
||||
@@ -368,36 +368,80 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Database Closing
|
||||
|
||||
/// This method must be called before database deallocation
|
||||
func close() {
|
||||
/// Closes a connection with `sqlite3_close`. This method is intended for
|
||||
/// the public `close()` function. It may fail.
|
||||
func close() throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if isClosed {
|
||||
guard let sqliteConnection = sqliteConnection else {
|
||||
// Already closed
|
||||
return
|
||||
}
|
||||
|
||||
configuration.SQLiteConnectionWillClose?(sqliteConnection)
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
Database.closeConnection(sqliteConnection)
|
||||
isClosed = true
|
||||
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > If the database connection is associated with unfinalized prepared
|
||||
// > statements or unfinished sqlite3_backup objects then
|
||||
// > sqlite3_close() will leave the database connection open and
|
||||
// > return SQLITE_BUSY.
|
||||
let code = sqlite3_close(sqliteConnection)
|
||||
guard code == SQLITE_OK else {
|
||||
if let log = Self.logError {
|
||||
if code == SQLITE_BUSY {
|
||||
// Let the user know about unfinalized statements that did
|
||||
// prevent the connection from closing properly.
|
||||
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
|
||||
while stmt != nil {
|
||||
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
|
||||
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
|
||||
self.sqliteConnection = nil
|
||||
configuration.SQLiteConnectionDidClose?()
|
||||
}
|
||||
|
||||
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
|
||||
/// Closes a connection with `sqlite3_close_v2`. This method is intended for
|
||||
/// deallocated connections.
|
||||
func close_v2() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
guard let sqliteConnection = sqliteConnection else {
|
||||
// Already closed
|
||||
return
|
||||
}
|
||||
|
||||
configuration.SQLiteConnectionWillClose?(sqliteConnection)
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > If sqlite3_close_v2() is called with unfinalized prepared
|
||||
// > statements and/or unfinished sqlite3_backups, then the database
|
||||
// > connection becomes an unusable "zombie" which will automatically
|
||||
// > be deallocated when the last prepared statement is finalized or the
|
||||
// > last sqlite3_backup is finished.
|
||||
// >
|
||||
// > The sqlite3_close_v2() interface is intended for use with host
|
||||
// > languages that are garbage collected, and where the order in which
|
||||
// > destructors are called is arbitrary.
|
||||
let code = sqlite3_close_v2(sqliteConnection)
|
||||
if code != SQLITE_OK, let log = logError {
|
||||
if code != SQLITE_OK, let log = Self.logError {
|
||||
// A rare situation where GRDB doesn't fatalError on
|
||||
// unprocessed errors.
|
||||
let message = String(cString: sqlite3_errmsg(sqliteConnection))
|
||||
log(ResultCode(rawValue: code), "could not close database: \(message)")
|
||||
}
|
||||
|
||||
self.sqliteConnection = nil
|
||||
configuration.SQLiteConnectionDidClose?()
|
||||
}
|
||||
|
||||
// MARK: - Limits
|
||||
|
||||
@@ -7,7 +7,10 @@ import UIKit
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
|
||||
/// The pool of reader connections.
|
||||
/// It is constant, until close() sets it to nil.
|
||||
private var readerPool: Pool<SerializedDatabase>?
|
||||
|
||||
@LockedBox var databaseSnapshotCount = 0
|
||||
|
||||
@@ -153,7 +156,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
/// executed the *body* block.
|
||||
fileprivate func forEachConnection(_ body: (Database) -> Void) {
|
||||
writer.sync(body)
|
||||
readerPool.forEach { $0.sync(body) }
|
||||
readerPool?.forEach { $0.sync(body) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,8 +172,8 @@ extension DatabasePool {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
// Release readers memory by closing all connections
|
||||
readerPool.barrier {
|
||||
readerPool.removeAll()
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,11 +225,27 @@ extension DatabasePool {
|
||||
|
||||
extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func close() throws {
|
||||
try readerPool?.barrier {
|
||||
// Close writer connection first. If we can't close it,
|
||||
// don't close readers.
|
||||
try writer.sync { try $0.close() }
|
||||
|
||||
// OK writer is closed. Now close readers and
|
||||
// eventually prevent any future read access
|
||||
defer { readerPool = nil }
|
||||
|
||||
try readerPool?.forEach { reader in
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
writer.interrupt()
|
||||
readerPool.forEach { $0.interrupt() }
|
||||
readerPool?.forEach { $0.interrupt() }
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
@@ -280,6 +299,9 @@ extension DatabasePool: DatabaseReader {
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
var result: T? = nil
|
||||
@@ -305,7 +327,10 @@ extension DatabasePool: DatabaseReader {
|
||||
.makeDispatchQueue(label: label)
|
||||
.async {
|
||||
do {
|
||||
let (reader, releaseReader) = try self.readerPool.get()
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
@@ -345,7 +370,10 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
do {
|
||||
let (reader, releaseReader) = try self.readerPool.get()
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
@@ -377,6 +405,9 @@ extension DatabasePool: DatabaseReader {
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
@@ -421,6 +452,9 @@ extension DatabasePool: DatabaseReader {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
} else {
|
||||
guard let readerPool = readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
@@ -508,6 +542,9 @@ extension DatabasePool: DatabaseReader {
|
||||
let isolationSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
do {
|
||||
guard let readerPool = readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
@@ -592,12 +629,16 @@ extension DatabasePool: DatabaseReader {
|
||||
/// Eventual concurrent read-only accesses are not invalidated: they will
|
||||
/// proceed until completion.
|
||||
public func invalidateReadOnlyConnections() {
|
||||
readerPool.removeAll()
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
guard let readerPool = readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
@@ -626,13 +667,15 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try readerPool.barrier {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
try readerPool!.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
readerPool.asyncBarrier {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
readerPool!.asyncBarrier {
|
||||
self.writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +69,10 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try writer.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
@@ -24,6 +24,28 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// The database configuration
|
||||
var configuration: Configuration { get }
|
||||
|
||||
/// Closes the database connection with the `sqlite3_close()` function.
|
||||
///
|
||||
/// **Note**: You DO NOT HAVE to call this method, and you SHOULD NOT call
|
||||
/// it unless the correct execution of your program depends on precise
|
||||
/// database closing. Database connections are automatically closed when
|
||||
/// they are deinitialized, and this is sufficient for most applications.
|
||||
///
|
||||
/// If this method does not throw, then the database is properly closed, and
|
||||
/// every future database access will throw a `DatabaseError` of
|
||||
/// code `SQLITE_MISUSE`.
|
||||
///
|
||||
/// Otherwise, there exists concurrent database accesses or living prepared
|
||||
/// statements that prevent the database from closing, and this method
|
||||
/// throws a `DatabaseError` of code `SQLITE_BUSY`.
|
||||
/// See <https://www.sqlite.org/c3ref/close.html> for more information.
|
||||
///
|
||||
/// After an error has been thrown, the database may still be opened, and
|
||||
/// you can keep on accessing it. It may also remain in a "zombie" state,
|
||||
/// in which case it will throw `SQLITE_MISUSE` for all future
|
||||
/// database accesses.
|
||||
func close() throws
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// This method causes any pending database operation to abort and return at
|
||||
@@ -542,6 +564,10 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
|
||||
@@ -61,6 +61,10 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try serializedDatabase.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseReader
|
||||
|
||||
@@ -729,6 +729,10 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
|
||||
@@ -59,7 +59,7 @@ final class SerializedDatabase {
|
||||
//
|
||||
// So let's close the database now. The deinitializer
|
||||
// will only close the database if needed.
|
||||
db.close()
|
||||
db.close_v2()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ final class SerializedDatabase {
|
||||
deinit {
|
||||
// Database may be deallocated in its own queue: allow reentrancy
|
||||
reentrantSync { db in
|
||||
db.close()
|
||||
db.close_v2()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ extension ValueObservation {
|
||||
/// database observation for all subscriptions, and thus spares
|
||||
/// database resources.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sharedObservation = ValueObservation
|
||||
@@ -88,6 +90,8 @@ extension ValueObservation {
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// A shared value observation that shares a single underlying database
|
||||
/// observation for all subscriptions, and thus spares database resources.
|
||||
///
|
||||
|
||||
@@ -875,6 +875,7 @@
|
||||
56419A7F24A51614004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
|
||||
56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = "<group>"; };
|
||||
56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = "<group>"; };
|
||||
5643676E272EDF3700C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1912,6 +1913,7 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */,
|
||||
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */,
|
||||
DC10500F19C904DD00D8CA30 /* Tests */,
|
||||
5643676E272EDF3700C718C7 /* Scripts */,
|
||||
DC3773F419C8CBB3004FCF85 /* Products */,
|
||||
);
|
||||
indentWidth = 4;
|
||||
@@ -2225,7 +2227,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
};
|
||||
56EB54FD22C9119B00850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
@@ -2243,7 +2245,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
};
|
||||
EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
|
||||
@@ -5796,7 +5796,7 @@ try dbQueue.write { db in
|
||||
|
||||
Tracked changes are insertions, updates, and deletions that impact the tracked value, performed with the [query interface](#the-query-interface), or [raw SQL](#sqlite-api). This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
> :point_up: **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
> :point_up: **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite\_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
**ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Applications] for sample code.
|
||||
|
||||
@@ -6153,6 +6153,8 @@ See also [ValueObservation.handleEvents](#valueobservationhandleevents).
|
||||
|
||||
### ValueObservation Sharing
|
||||
|
||||
[**:fire: EXPERIMENTAL**](#what-are-experimental-features)
|
||||
|
||||
**Sharing a ValueObservation allows several components of your app to be notified of database changes, in an efficient way.**
|
||||
|
||||
A shared observation spares database resources. For example, when a database change happens, a fresh value is fetched only once, and then notified to all subscriptions.
|
||||
@@ -7579,10 +7581,15 @@ let dbQueue = try DatabaseQueue(path: dbPath)
|
||||
|
||||
### How do I close a database connection?
|
||||
|
||||
Database connections are managed by [database queues](#database-queues) and [pools](#database-pools). A connection is closed when its database queue or pool is deinitialized, and all usages of this connection are completed.
|
||||
Database connections are automatically closed when they are deinitialized.
|
||||
|
||||
Database accesses that run in background threads postpone the closing of connections.
|
||||
When the correct execution of your program depends on precise database closing, use the `close()` method:
|
||||
|
||||
```swift
|
||||
try dbQueue.close()
|
||||
```
|
||||
|
||||
This explicit `close()` may fail with an error. See the inline documentation of this method for more information. Generally speaking, you should not call this method: rely on automatic closing instead.
|
||||
|
||||
## FAQ: SQL
|
||||
|
||||
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Support for SwiftLint installed via Homebrew on Apple Silicon
|
||||
# https://github.com/realm/SwiftLint/issues/2992
|
||||
if test -d "/opt/homebrew/bin/"; then
|
||||
PATH="/opt/homebrew/bin/:${PATH}"
|
||||
fi
|
||||
|
||||
if which swiftlint >/dev/null; then
|
||||
swiftlint --config ${SRCROOT}/Scripts/swiftlint.yml
|
||||
else
|
||||
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
|
||||
fi
|
||||
@@ -1,5 +1,5 @@
|
||||
included:
|
||||
- GRDB
|
||||
- ../GRDB
|
||||
|
||||
disabled_rules:
|
||||
- comment_spacing
|
||||
@@ -26,6 +26,7 @@ disabled_rules:
|
||||
opt_in_rules:
|
||||
- anyobject_protocol
|
||||
- array_init
|
||||
- capture_variable
|
||||
- closure_spacing
|
||||
- collection_alignment
|
||||
- contains_over_filter_count
|
||||
@@ -33,6 +34,7 @@ opt_in_rules:
|
||||
- contains_over_first_not_nil
|
||||
- contains_over_range_nil_comparison
|
||||
- convenience_type
|
||||
- discouraged_assert
|
||||
- empty_collection_literal
|
||||
- empty_count
|
||||
- empty_string
|
||||
@@ -75,4 +75,142 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
// calls `sqlite3_file_control` as part of the preparation function.
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
// MARK: - Closing
|
||||
|
||||
func testClose() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
do {
|
||||
try dbPool.read { db in
|
||||
_ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try dbPool.close()
|
||||
}
|
||||
|
||||
func testCloseAfterUse() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try dbPool.read { db in
|
||||
_ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try dbPool.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
do {
|
||||
try dbPool.read { db in
|
||||
_ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try dbPool.close()
|
||||
}
|
||||
|
||||
func testCloseAfterCachedStatement() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { db in
|
||||
_ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try dbPool.read { db in
|
||||
_ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try dbPool.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
do {
|
||||
try dbPool.read { db in
|
||||
_ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try dbPool.close()
|
||||
}
|
||||
|
||||
func testCloseFailedDueToWriter() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let statement = try dbPool.write { db in
|
||||
try db.makeStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
|
||||
try withExtendedLifetime(statement) {
|
||||
do {
|
||||
try dbPool.close()
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_BUSY { }
|
||||
}
|
||||
XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master"))
|
||||
|
||||
// Database is not closed: no error
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
}
|
||||
|
||||
func testCloseFailedDueToReader() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let statement = try dbPool.read { db in
|
||||
try db.makeStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
|
||||
try withExtendedLifetime(statement) {
|
||||
do {
|
||||
try dbPool.close()
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_BUSY { }
|
||||
}
|
||||
// Check for sqlite3_close_v2() logging:
|
||||
XCTAssert(lastMessage!.contains("close deferred due to unfinalized statement: \"SELECT * FROM sqlite_master\""))
|
||||
|
||||
// Database is in a zombie state.
|
||||
// In the zombie state, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
do {
|
||||
try dbPool.read { db in
|
||||
_ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// In the zombie state, closing is a noop
|
||||
try dbPool.close()
|
||||
}
|
||||
}
|
||||
@@ -193,4 +193,80 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
try test(qos: .background)
|
||||
try test(qos: .userInitiated)
|
||||
}
|
||||
|
||||
// MARK: - Closing
|
||||
|
||||
func testClose() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try dbQueue.close()
|
||||
}
|
||||
|
||||
func testCloseAfterUse() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try dbQueue.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try dbQueue.close()
|
||||
}
|
||||
|
||||
func testCloseWithCachedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
_ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try dbQueue.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try dbQueue.close()
|
||||
}
|
||||
|
||||
func testFailedClose() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let statement = try dbQueue.inDatabase { db in
|
||||
try db.makeStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
|
||||
try withExtendedLifetime(statement) {
|
||||
do {
|
||||
try dbQueue.close()
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_BUSY { }
|
||||
}
|
||||
XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master"))
|
||||
|
||||
// Database is not closed: no error
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -358,4 +358,80 @@ class DatabaseSnapshotTests: GRDBTestCase {
|
||||
XCTAssertNotNil(db.schemaCache[.main].primaryKey("t"))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Closing
|
||||
|
||||
func testClose() throws {
|
||||
let snapshot = try makeDatabasePool().makeSnapshot()
|
||||
try snapshot.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try snapshot.read { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try snapshot.close()
|
||||
}
|
||||
|
||||
func testCloseAfterUse() throws {
|
||||
let snapshot = try makeDatabasePool().makeSnapshot()
|
||||
try snapshot.read { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try snapshot.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try snapshot.read { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try snapshot.close()
|
||||
}
|
||||
|
||||
func testCloseWithCachedStatement() throws {
|
||||
let snapshot = try makeDatabasePool().makeSnapshot()
|
||||
try snapshot.read { db in
|
||||
_ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
try snapshot.close()
|
||||
|
||||
// After close, access throws SQLITE_MISUSE
|
||||
do {
|
||||
try snapshot.read { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_MISUSE { }
|
||||
|
||||
// After close, closing is a noop
|
||||
try snapshot.close()
|
||||
}
|
||||
|
||||
func testFailedClose() throws {
|
||||
let snapshot = try makeDatabasePool().makeSnapshot()
|
||||
let statement = try snapshot.read { db in
|
||||
try db.makeStatement(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
|
||||
try withExtendedLifetime(statement) {
|
||||
do {
|
||||
try snapshot.close()
|
||||
XCTFail("Expected Error")
|
||||
} catch DatabaseError.SQLITE_BUSY { }
|
||||
}
|
||||
XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master"))
|
||||
|
||||
// Database is not closed: no error
|
||||
try snapshot.read { db in
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user