Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2019-09-06 08:07:49 +02:00
commit aa157a77d2
26 files changed
+1447 -318

No files matched your search

+56
View File
@@ -13,6 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
#### 4.x Releases
- `4.4.x` Releases - [4.4.0](#440)
- `4.3.x` Releases - [4.3.0](#430)
- `4.2.x` Releases - [4.2.0](#420) | [4.2.1](#421)
- `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411)
@@ -60,6 +61,61 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
## Next Release
-->
## 4.4.0
Released September 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.3.0...v4.4.0)
### New
- [#602](https://github.com/groue/GRDB.swift/pull/602): Don't keep the sqlCipher passphrase in memory longer than necessary
- [#603](https://github.com/groue/GRDB.swift/pull/603): DatabasePool write barrier
### Documentation Diff
SQLCipher passphrase management has been refactored: you will get deprecation warnings. Check out the rewritten [Encryption](README.md#encryption) chapter in order to migrate your code and remove those warnings.
The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been extended for the new `barrierWriteWithoutTransaction` method.
### API Diff
**Deprecations**
```diff
class DatabaseQueue {
+ @available(*, deprecated)
func change(passphrase: String) throws
}
class DatabasePool {
+ @available(*, deprecated)
func change(passphrase: String) throws
}
struct Configuration {
+ @available(*, deprecated)
var passphrase: String?
}
```
**New Methods**
```diff
class DatabasePool {
+ func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
+ func invalidateReadOnlyConnections()
}
class Database {
+ func usePassphrase(_ passphrase: String) throws
+ func changePassphrase(_ passphrase: String) throws
+ var lastErrorCode: ResultCode
+ var lastErrorMessage: String?
}
```
## 4.3.0
+1 -1
View File
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v4.3.0
git checkout v4.4.0
git submodule update --init SQLiteCustom/src
````
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '4.3.0'
s.version = '4.4.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+16
View File
@@ -179,6 +179,9 @@
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4F4231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4F5231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
@@ -490,6 +493,9 @@
5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; };
5690C3401D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
5690C3431D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; };
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; };
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; };
569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */; };
569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */; };
5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */; };
@@ -1360,6 +1366,7 @@
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
@@ -1477,6 +1484,7 @@
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = "<group>"; };
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
56915781231BF28B00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = "<group>"; };
569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = "<group>"; };
569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = "<group>"; };
@@ -2177,6 +2185,7 @@
569BBA4522906A8200478429 /* InflectionsTests.json */,
569BBA3522905FFA00478429 /* InflectionsTests.swift */,
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */,
56915781231BF28B00E1D237 /* PoolTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
);
@@ -2191,6 +2200,7 @@
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */,
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */,
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */,
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */,
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */,
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */,
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */,
@@ -3391,6 +3401,7 @@
56176C6E1EACCCC9000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
56A2384C1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */,
56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */,
563DE4F4231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */,
56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E4227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
@@ -3494,6 +3505,7 @@
5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
@@ -3591,6 +3603,7 @@
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */,
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */,
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */,
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
@@ -3694,6 +3707,7 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
@@ -3923,6 +3937,7 @@
AAA4DD1E230F262000C74B15 /* FTS5TableBuilderTests.swift in Sources */,
AAA4DD1F230F262000C74B15 /* UpdateStatementTests.swift in Sources */,
AAA4DD20230F262000C74B15 /* DatabaseMigratorTests.swift in Sources */,
563DE4F5231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */,
AAA4DD21230F262000C74B15 /* PrefixWhileCursorTests.swift in Sources */,
AAA4DD22230F262000C74B15 /* AssociationPrefetchingSQLTests.swift in Sources */,
AAA4DD23230F262000C74B15 /* FoundationNSNullTests.swift in Sources */,
@@ -4026,6 +4041,7 @@
AAA4DD85230F262000C74B15 /* AssociationParallelRowScopesTests.swift in Sources */,
AAA4DD86230F262000C74B15 /* SQLExpressionLiteralTests.swift in Sources */,
AAA4DD87230F262000C74B15 /* DropFirstCursorTests.swift in Sources */,
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */,
AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
AAA4DD8A230F262000C74B15 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
+12 -9
View File
@@ -75,23 +75,26 @@ public struct Configuration {
/// Default: nil
public var trace: TraceFunction?
// MARK: - Encryption
#if SQLITE_HAS_CODEC
// TODO: remove when the deprecated passphrase turns unavailable.
var _passphrase: String?
/// The passphrase for the encrypted database.
///
/// Default: nil
public var passphrase: String?
@available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
public var passphrase: String? {
get { return _passphrase }
set { _passphrase = newValue }
}
#endif
/// If set, allows custom configuration to be run every time
/// a new connection is opened.
///
/// This block is run after the Database's connection has opened, but
/// before that connection has been made available to any read/write
/// API's.
// MARK: - Managing SQLite Connections
/// A function that is run when an SQLite connection is opened, before the
/// connection is made available for database access methods.
///
/// For example:
///
+45 -24
View File
@@ -125,9 +125,11 @@ public final class Database {
lazy var internalStatementCache = StatementCache(database: self)
lazy var publicStatementCache = StatementCache(database: self)
// Errors
var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
/// The last error code
public var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
/// The last error message
public var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
/// Statement authorizer. Use withAuthorizer(_:_:).
fileprivate var _authorizer: StatementAuthorizer?
@@ -213,15 +215,14 @@ extension Database {
#if SQLITE_HAS_CODEC
try validateSQLCipher()
if let passphrase = configuration.passphrase {
try setCipherPassphrase(passphrase)
if let passphrase = configuration._passphrase {
try _usePassphrase(passphrase)
}
#endif
// Last step before we can start accessing the database.
// This is the opportunity to run SQLCipher configuration
// pragmas such as cipher_page_size, for example.
try configuration.prepareDatabase?(self)
try validateFormat()
configuration.SQLiteConnectionDidOpen?()
}
@@ -385,22 +386,6 @@ extension Database {
""")
}
}
private func setCipherPassphrase(_ passphrase: String) throws {
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
#endif
private func validateFormat() throws {
@@ -975,7 +960,43 @@ extension Database {
// MARK: - Encryption
func change(passphrase: String) throws {
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from Configuration.prepareDatabase, as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase = { db in
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
// Support for the deprecated method change(passphrase:).
// After it has been called, the passphrase used for opening the
// database must be ignored.
if configuration._passphrase != nil {
return
}
try _usePassphrase(passphrase)
}
/// See usePassphrase(_:)
private func _usePassphrase(_ passphrase: String) throws {
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: String) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
+41 -7
View File
@@ -171,12 +171,17 @@ extension DatabasePool {
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
/// This method blocks the current thread until all database accesses
/// are completed.
///
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
forEachConnection { $0.releaseMemory() }
readerPool.clear()
// Release writer memory
writer.sync { $0.releaseMemory() }
// Release readers memory by closing all connections
readerPool.barrier {
readerPool.removeAll()
}
}
@@ -237,11 +242,13 @@ extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try writer.sync { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
try readerPool.barrier {
try writer.sync { try $0.changePassphrase(passphrase) }
readerPool.removeAll()
readerConfig._passphrase = passphrase
}
}
}
#endif
@@ -590,6 +597,17 @@ extension DatabasePool: DatabaseReader {
}
#endif
/// Invalidates open read-only SQLite connections.
///
/// After this method is called, read-only database access methods will use
/// new SQLite connections.
///
/// Eventual concurrent read-only accesses are not invalidated: they will
/// proceed until completion.
public func invalidateReadOnlyConnections() {
readerPool.removeAll()
}
/// Returns a reader that can be used from the current dispatch queue,
/// if any.
private var currentReader: SerializedDatabase? {
@@ -631,6 +649,22 @@ extension DatabasePool: DatabaseReader {
return try writer.sync(updates)
}
/// A barrier write ensures that no database access is executed until all
/// previous accesses have completed, and the specified updates have been
/// executed.
///
/// This method is *not* reentrant.
///
/// - important: Reads executed by concurrent *database snapshots* are not
/// considered: they can run concurrently with the barrier updates.
/// - parameter updates: The updates to the database.
/// - throws: The error thrown by the updates.
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try readerPool.barrier {
try writer.sync(updates)
}
}
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
+2 -1
View File
@@ -140,8 +140,9 @@ extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws {
try writer.sync { try $0.change(passphrase: passphrase) }
try writer.sync { try $0.changePassphrase(passphrase) }
}
}
#endif
+60 -38
View File
@@ -38,52 +38,52 @@ import Dispatch
final class Pool<T> {
private class Item {
let element: T
var available: Bool
var isAvailable: Bool
init(element: T, available: Bool) {
init(element: T, isAvailable: Bool) {
self.element = element
self.available = available
self.isAvailable = isAvailable
}
}
private let makeElement: () throws -> T
private var items: ReadWriteBox<[Item]> = ReadWriteBox([])
private let semaphore: DispatchSemaphore // limits the number of elements
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
init(maximumCount: Int, makeElement: @escaping () throws -> T) {
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
self.semaphore = DispatchSemaphore(value: maximumCount)
self.itemsSemaphore = DispatchSemaphore(value: maximumCount)
self.itemsGroup = DispatchGroup()
self.barrierQueue = DispatchQueue(label: "GRDB.Pool.barrier", attributes: [.concurrent])
}
/// Returns a tuple (element, release)
/// Client MUST call release() after the element has been used.
func get() throws -> (T, () -> Void) {
_ = semaphore.wait(timeout: .distantFuture)
do {
let item = try items.write { items -> Item in
if let item = items.first(where: { $0.available }) {
item.available = false
return item
} else {
let element = try makeElement()
let item = Item(element: element, available: false)
items.append(item)
return item
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: () -> Void) {
return try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try items.write { items -> Item in
if let item = items.first(where: { $0.isAvailable }) {
item.isAvailable = false
return item
} else {
let element = try makeElement()
let item = Item(element: element, isAvailable: false)
items.append(item)
return item
}
}
return (element: item.element, release: { self.release(item) })
} catch {
itemsSemaphore.signal()
itemsGroup.leave()
throw error
}
let release = {
self.items.write { _ in
// This is why Item is a class, not a struct: so that we can
// release it without having to find in it the items array.
item.available = true
}
self.semaphore.signal()
}
return (item.element, release)
} catch {
semaphore.signal()
throw error
}
}
@@ -95,6 +95,16 @@ final class Pool<T> {
return try block(element)
}
private func release(_ item: Item) {
items.write { _ in
// This is why Item is a class, not a struct: so that we can
// release it without having to find in it the items array.
item.isAvailable = true
}
itemsSemaphore.signal()
itemsGroup.leave()
}
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
@@ -105,17 +115,29 @@ final class Pool<T> {
}
}
/// Empty the pool. Currently used items won't be reused.
func clear() {
clear {}
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
/// The `execute` function is executed before any other element is dequeued.
func removeAll() {
removeAll(andThen: {})
}
/// Empty the pool. Currently used items won't be reused.
/// Eventual block is executed before any other element is dequeued.
func clear(andThen block: () throws -> Void) rethrows {
try items.write { items in
/// Removes all elements from the pool, and runs the `body` function before
/// any other element is dequeued.
/// Currently used elements won't be reused.
func removeAll<T>(andThen body: () throws -> T) rethrows -> T {
return try items.write { items in
items.removeAll()
try block()
return try body()
}
}
/// Blocks until no element is used, and runs the `barrier` function before
/// any other element is dequeued.
func barrier<T>(execute barrier: () throws -> T) rethrows -> T {
return try barrierQueue.sync(flags: [.barrier]) {
itemsGroup.wait()
return try barrier()
}
}
}
+3 -2
View File
@@ -8,8 +8,8 @@ final class ReadWriteBox<T> {
}
init(_ value: T) {
self._value = value
self.queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
_value = value
queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
}
func read<U>(_ block: (T) throws -> U) rethrows -> U {
@@ -29,6 +29,7 @@ final class ReadWriteBox<T> {
}
extension ReadWriteBox where T: Numeric {
@discardableResult
func increment() -> T {
return write { n in
n += 1
+13 -1
View File
@@ -91,6 +91,8 @@
563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; };
563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4F9231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; };
563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; };
563EF442216131F5007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */; };
@@ -323,6 +325,8 @@
5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; };
5690C3421D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
5690C3451D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578B231BF2BE00E1D237 /* PoolTests.swift */; };
5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578B231BF2BE00E1D237 /* PoolTests.swift */; };
56959620222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; };
56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; };
56959636222D058B002CB7C9 /* AssociationHasManySQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */; };
@@ -772,6 +776,7 @@
563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
563EF44C2161F196007DAACD /* Inflections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Inflections.swift; sourceTree = "<group>"; };
@@ -899,6 +904,7 @@
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = "<group>"; };
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
5691578B231BF2BE00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = "<group>"; };
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = "<group>"; };
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = "<group>"; };
@@ -1514,6 +1520,7 @@
569BBA42229066CB00478429 /* InflectionsTests.json */,
569BBA3E229065CF00478429 /* InflectionsTests.swift */,
56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */,
5691578B231BF2BE00E1D237 /* PoolTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
);
@@ -1528,6 +1535,7 @@
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */,
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */,
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */,
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */,
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */,
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */,
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */,
@@ -1546,8 +1554,8 @@
56741EA71E66A8B3003E422D /* FetchRequestTests.swift */,
56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */,
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */,
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */,
565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */,
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */,
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */,
56A2381D1B9C74A90082EB20 /* Row */,
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */,
@@ -2282,6 +2290,7 @@
F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */,
5657AB4D1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
563DE4F9231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */,
56CC923C201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */,
F3BA80E51CFB3011003DC1BA /* DatabaseFunctionTests.swift in Sources */,
560714EE227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
@@ -2385,6 +2394,7 @@
F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */,
5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */,
5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */,
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B06DA2185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */,
@@ -2614,6 +2624,7 @@
F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */,
56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */,
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */,
F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714ED227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
@@ -2717,6 +2728,7 @@
F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */,
5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */,
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B06D92185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */,
+3 -3
View File
@@ -414,10 +414,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.3.0 \
--module-version 4.3.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.4.0 \
--module-version 4.4.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/4.3/ \
--root-url http://groue.github.io/GRDB.swift/docs/4.4/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+233 -70
View File
@@ -5,14 +5,14 @@ GRDB 4 [![Swift 4.2](https://img.shields.io/badge/swift-4.2-orange.svg?style=fla
---
**Latest release**: August 28, 2019 • version 4.3.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
**Latest release**: September 6, 2019 • version 4.4.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
**Requirements**: iOS 9.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+ &bull; Swift 4.2+ / Xcode 10.0+
| Swift version | GRDB version |
| ------------- | ----------------------------------------------------------- |
| **Swift 5** | **v4.3.0** |
| **Swift 4.2** | **v4.3.0** |
| **Swift 5** | **v4.4.0** |
| **Swift 4.2** | **v4.4.0** |
| Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) |
| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
@@ -256,7 +256,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.3/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -338,7 +338,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
```swift
let package = Package(
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.3.0"))
.package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.4.0"))
]
)
```
@@ -353,7 +353,7 @@ Note that Linux is not currently supported.
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.3.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.3.0` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.4.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.4.0` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -468,7 +468,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.3/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.4/Structs/Configuration.html) for more details.
## Database Pools
@@ -549,7 +549,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.3/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.4/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -609,7 +609,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
In Swift 5, you can embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -810,7 +810,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.3/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.4/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -892,7 +892,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1175,7 +1175,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1582,7 +1582,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.3/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.4/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1696,7 +1696,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1955,7 +1955,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.3/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.4/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support).
@@ -2413,7 +2413,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -2791,7 +2791,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.3/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.3/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.3/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.4/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.4/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.4/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -4134,7 +4134,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4667,7 +4667,7 @@ let request = Player.all()
**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol.
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.3/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.4/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -4711,7 +4711,7 @@ let request = Player.all()
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.3/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.4/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
### Fetching From Custom Requests
@@ -5141,7 +5141,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html):
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -5390,7 +5390,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.3/Structs/StatementArguments.html):
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -7274,7 +7274,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.3/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.4/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
@@ -7284,7 +7284,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.3/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.4/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7338,73 +7338,216 @@ pod 'GRDB.swift/SQLCipher'
pod 'SQLCipher', '~> 3.4'
```
> :warning: **Warning**: SQLCipher 4 is *not compatible** with SQLCipher 3.
>
> When you want to open your existing SQLCipher 3 database with SQLCipher 4, you may want to run the `cipher_compatibility` pragma:
>
> ```swift
> // Open an SQLCipher 3 database with SQLCipher 4
> var configuration = Configuration()
> configuration.passphrase = "..."
> configuration.prepareDatabase = { db in
> try db.execute(sql: "PRAGMA cipher_compatibility = 3")
> }
> let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
> ```
>
> See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher-400-release/) and [Upgrading to SQLCipher 4](https://discuss.zetetic.net/t/upgrading-to-sqlcipher-4/3283) for more information. See also [Advanced configuration options for SQLCipher](#advanced-configuration-options-for-sqlcipher) below.
- [Creating or Opening an Encrypted Database](#creating-or-opening-an-encrypted-database)
- [Changing the Passphrase of an Encrypted Database](#changing-the-passphrase-of-an-encrypted-database)
- [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database)
- [Security Considerations](#security-considerations)
### Creating or Opening an Encrypted Database
**You create and open an encrypted database** by providing a passphrase to your [database connection](#database-connections):
```swift
var configuration = Configuration()
configuration.passphrase = "secret"
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
**You can change the passphrase** of an already encrypted database:
It is also in `prepareDatabase` that you perform other [SQLCipher configuration steps](https://www.zetetic.net/sqlcipher/sqlcipher-api/) that must happen early in the lifetime of a SQLCipher connection. For example:
```swift
try dbQueue.change(passphrase: "newSecret")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_page_size = ...")
try db.execute(sql: "PRAGMA kdf_iter = ...")
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
When you want to open an existing SQLCipher 3 database with SQLCipher 4, you may want to run the `cipher_compatibility` pragma:
```swift
// Open an SQLCipher 3 database with SQLCipher 4
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_compatibility = 3")
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher-400-release/) and [Upgrading to SQLCipher 4](https://discuss.zetetic.net/t/upgrading-to-sqlcipher-4/3283) for more information.
### Changing the Passphrase of an Encrypted Database
**You can change the passphrase** of an already encrypted database.
When you use a [database queue](#database-queues), open the database with the old passphrase, and then apply the new passphrase:
```swift
try dbQueue.write { db in
try db.changePassphrase("newSecret")
}
```
When you use a [database pool](#database-pools), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method:
```swift
try dbPool.barrierWriteWithoutTransaction { db in
try db.changePassphrase("newSecret")
dbPool.invalidateReadOnlyConnections()
}
```
> :point_up: **Note**: When an application wants to keep on using a database queue or pool after the passphrase has changed, it is responsible for providing the correct passphrase to the `usePassphrase` method called in the database preparation function. Consider:
>
> ```swift
> // WRONG: this won't work across a passphrase change
> let passphrase = try getPassphrase()
> var config = Configuration()
> config.prepareDatabase = { db in
> try db.usePassphrase(passphrase)
> }
>
> // CORRECT: get the latest passphrase when it is needed
> var config = Configuration()
> config.prepareDatabase = { db in
> let passphrase = try getPassphrase()
> try db.usePassphrase(passphrase)
> }
> ```
> :point_up: **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](#database-snapshots) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed.
> :point_up: **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database).
### Exporting a Database to an Encrypted Database
Providing a passphrase won't encrypt a clear-text database that already exists, though. SQLCipher can't do that, and you will get an error instead: `SQLite error 26: file is encrypted or is not a database`.
**To encrypt an existing clear-text database**, create a new and empty encrypted database, and copy the content of the clear-text database in it. The technique to do that is [documented](https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868/1) by SQLCipher. With GRDB, it gives:
Instead, create a new encrypted database, at a distinct location, and export the content of the existing database. This can both encrypt a clear-text database, or change the passphrase of an encrypted databaase.
The technique to do that is [documented](https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868/1) by SQLCipher.
With GRDB, it gives:
```swift
// The clear-text database
let clearDBQueue = try DatabaseQueue(path: "/path/to/clear.db")
// The existing database
let existingDBQueue = try DatabaseQueue(path: "/path/to/existing.db")
// The encrypted database, at some distinct location:
var configuration = Configuration()
configuration.passphrase = "secret"
let encryptedDBQueue = try DatabaseQueue(path: "/path/to/encrypted.db", configuration: config)
// The new encrypted database, at some distinct location:
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let newDBQueue = try DatabaseQueue(path: "/path/to/new.db", configuration: config)
try clearDBQueue.inDatabase { db in
try db.execute(sql: "ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"])
try db.execute(sql: "SELECT sqlcipher_export('encrypted')")
try db.execute(sql: "DETACH DATABASE encrypted")
try existingDBQueue.inDatabase { db in
try db.execute(
sql: """
ATTACH DATABASE ? AS encrypted KEY ?;
SELECT sqlcipher_export('encrypted');
DETACH DATABASE encrypted;
""",
arguments: [newDBQueue.path, "secret"])
}
// Now the copy is done, and the clear-text database can be deleted.
// Now the export is completed, and the existing database can be deleted.
```
## Advanced configuration options for SQLCipher
Some advanced SQLCipher configuration steps must happen very early in the database lifetime, and you will have to use the `configuration.prepareDatabase` property in order to run them correctly:
### Security Considerations
#### Managing the lifetime of the passphrase string
It is recommended to avoid keeping the passphrase in memory longer than necessary. To do this, make sure you load the passphrase from inside the `prepareDatabase` function:
```swift
var configuration = Configuration()
configuration.passphrase = "secret"
configuration.prepareDatabase = { db in
try db.execute(sql: "PRAGMA cipher_page_size = 4096")
try db.execute(sql: "PRAGMA kdf_iter = 128000")
// NOT RECOMMENDED: this keeps the passphrase in memory longer than necessary
let passphrase = try getPassphrase()
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase(passphrase)
}
// RECOMMENDED: only load the passphrase when it is needed
var config = Configuration()
config.prepareDatabase = { db in
let passphrase = try getPassphrase()
try db.usePassphrase(passphrase)
}
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
```
See [PRAGMA cipher_page_size](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_page_size) and [PRAGMA kdf_iter](https://www.zetetic.net/sqlcipher/sqlcipher-api/#kdf_iter) for more information.
This technique manages the lifetime of the passphrase string. Some demanding users will want to go further, and manage the lifetime of the raw passphrase bytes. See below.
#### Managing the lifetime of the passphrase bytes
GRDB offers convenience methods for providing the database passphrases as Swift strings: `usePassphrase(_:)` and `changePassphrase(_:)`. Those methods don't keep the passphrase String in memory longer than necessary. But they are as secure as the standard String type: the lifetime of actual passphrase bytes in memory is not under control.
When you want to precisely manage the passphrase bytes, talk directly to SQLCipher, using its raw C functions.
For example:
```swift
import GRDB
import SQLCipher
var config = Configuration()
config.prepareDatabase = { db in
... // Carefully load passphrase bytes
let code = sqlite3_key(db.sqliteConnection, /* passphrase bytes */)
... // Carefully dispose passphrase bytes
guard code == SQLITE_OK else {
throw DatabaseError(
resultCode: ResultCode(rawValue: code),
message: db.lastErrorMessage)
}
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
#### Passphrase availability vs. Database availability
When the passphrase is securely stored in the system keychain, your application can protect it using the [`kSecAttrAccessible`](https://developer.apple.com/documentation/security/ksecattraccessible) attribute.
Such protection prevents GRDB from creating SQLite connections when the passphrase is not available:
```swift
var config = Configuration()
config.prepareDatabase = { db in
let passphrase = try loadPassphraseFromSystemKeychain()
try db.usePassphrase(passphrase)
}
// Success if and only if the passphrase is available
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
For the same reason, [database pools](#database-pools), which open SQLite connections on demand, may fail at any time as soon as the passphrase becomes unavailable:
```swift
// Success if and only if the passphrase is available
let dbPool = try DatabasePool(path: dbPath, configuration: config)
// May fail if passphrase has turned unavailable
try dbPool.read { ... }
// May trigger value observation failure if passphrase has turned unavailable
try dbPool.write { ... }
```
Because DatabasePool maintains a pool of long-lived SQLite connections, some database accesses will use an existing connection, and succeed. And some other database accesses will fail, as soon as the pool wants to open a new connection. It is impossible to predict which accesses will succeed or fail.
For the same reason, a database queue, which also maintains a long-lived SQLite connection, will remain available even after the passphrase has turned unavailable.
Applications are thus responsible for protecting database accesses when the passphrase is unavailable. To this end, they can use [Data Protection](#data-protection). They can also destroy their instances of database queue or pool when the passphrase becomes unavailable.
## Backup
@@ -8016,6 +8159,12 @@ For more information about database pools, grab information about SQLite [WAL mo
### Advanced DatabasePool
- [The `concurrenRead` Method](#the-concurrenread-method)
- [The `barrierWriteWithoutTransaction` Method](#the-barrierwritewithouttransaction-method)
#### The `concurrenRead` Method
[Database pools](#database-pools) are very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid locking the writer queue longer than necessary:
@@ -8088,6 +8237,20 @@ try dbPool.writeWithoutTransaction { db in
[Transaction Observers](#transactionobserver-protocol) can also use `concurrentRead` in their `databaseDidCommit` method in order to process database changes without blocking other threads that want to write into the database.
#### The `barrierWriteWithoutTransaction` Method
```swift
try dbPool.barrierWriteWithoutTransaction { db in
// Exclusive database access
}
```
The barrier write guarantees exclusive access to the database: the method blocks until all concurrent database accesses are completed, reads and writes, and postpones all other accesses until it completes.
There is a known limitation: reads performed by [database snapshots](#database-snapshots) are out of scope, and may run concurrently with the barrier.
### Database Snapshots
**A database snapshot sees an unchanging database content, as it existed at the moment it was created.**
@@ -8149,7 +8312,7 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.3/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.3/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.4/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
@@ -8403,7 +8566,7 @@ If you absolutely need multiple connections, then:
- Read about [isolation in SQLite](https://www.sqlite.org/isolation.html)
- Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html)
- Become a master of the [WAL mode](https://www.sqlite.org/wal.html)
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.3/Structs/Configuration.html)
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.4/Structs/Configuration.html)
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
@@ -8680,10 +8843,10 @@ let dbQueue = try DatabaseQueue(path: databaseURL.path)
If your application does not need to modify the database, open a read-only [connection](#database-connections) to your resource:
```swift
var configuration = Configuration()
configuration.readonly = true
var config = Configuration()
config.readonly = true
let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the [Application Support directory](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html). Only then, open a [connection](#database-connections):
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>4.3.0</string>
<string>4.4.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -15,6 +15,8 @@
56057C692291D0AC00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C672291D0AB00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; };
560714F0227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
560714F1227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; };
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; };
@@ -385,6 +387,8 @@
5656A803229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; };
5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; };
56915793231C0D6A00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915792231C0D6A00E1D237 /* PoolTests.swift */; };
56915794231C0D6A00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915792231C0D6A00E1D237 /* PoolTests.swift */; };
569BBA31228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; };
569BBA32228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; };
56DF0027228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; };
@@ -403,6 +407,7 @@
56057C5E2291B8E400A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
56057C672291D0AB00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = "<group>"; };
563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
@@ -592,6 +597,7 @@
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = "<group>"; };
56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = "<group>"; };
56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = "<group>"; };
@@ -685,6 +691,7 @@
564A1FD7226B89E0001F64F1 /* DatabaseAfterNextTransactionCommitTests.swift */,
564A1F31226B89CF001F64F1 /* DatabaseAggregateTests.swift */,
564A1F53226B89D2001F64F1 /* DatabaseCollationTests.swift */,
563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */,
564A1F67226B89D5001F64F1 /* DatabaseCursorTests.swift */,
564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */,
564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */,
@@ -774,6 +781,7 @@
564A1FCE226B89DF001F64F1 /* MutablePersistableRecordTests.swift */,
564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */,
564A1FCB226B89DF001F64F1 /* PersistableRecordTests.swift */,
56915792231C0D6A00E1D237 /* PoolTests.swift */,
564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */,
564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */,
564A1F97226B89DA001F64F1 /* PrimaryKeyInfoTests.swift */,
@@ -911,11 +919,14 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1020;
LastUpgradeCheck = 1020;
LastUpgradeCheck = 1100;
TargetAttributes = {
564A1F1C226B876D001F64F1 = {
CreatedOnToolsVersion = 10.2.1;
LastSwiftMigration = 1020;
LastSwiftMigration = 1100;
};
564A2095226B8E18001F64F1 = {
LastSwiftMigration = 1100;
};
};
};
@@ -925,6 +936,7 @@
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 564A1F12226B8750001F64F1;
productRefGroup = 564A1F1E226B876D001F64F1 /* Products */;
@@ -1096,6 +1108,7 @@
564A201F226B89E1001F64F1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
564A2000226B89E1001F64F1 /* PrefixCursorTests.swift in Sources */,
564A1FE1226B89E1001F64F1 /* SelectStatementTests.swift in Sources */,
563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */,
564A1FF8226B89E1001F64F1 /* QueryInterfaceExpressionsTests.swift in Sources */,
564A202E226B89E1001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1129,6 +1142,7 @@
564A2064226B89E1001F64F1 /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */,
564A1FFA226B89E1001F64F1 /* FTS5WrapperTokenizerTests.swift in Sources */,
564A2056226B89E1001F64F1 /* TableRecordTests.swift in Sources */,
56915793231C0D6A00E1D237 /* PoolTests.swift in Sources */,
564A2042226B89E1001F64F1 /* FTS5TableBuilderTests.swift in Sources */,
564A2089226B89E1001F64F1 /* DatabaseValueConversionErrorTests.swift in Sources */,
564A2081226B89E1001F64F1 /* TransactionObserverTests.swift in Sources */,
@@ -1294,6 +1308,7 @@
564A20C9226B8E18001F64F1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
564A20CA226B8E18001F64F1 /* PrefixCursorTests.swift in Sources */,
564A20CB226B8E18001F64F1 /* SelectStatementTests.swift in Sources */,
563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */,
564A20CC226B8E18001F64F1 /* QueryInterfaceExpressionsTests.swift in Sources */,
564A20CD226B8E18001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1327,6 +1342,7 @@
564A20E8226B8E18001F64F1 /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */,
564A20E9226B8E18001F64F1 /* FTS5WrapperTokenizerTests.swift in Sources */,
564A20EA226B8E18001F64F1 /* TableRecordTests.swift in Sources */,
56915794231C0D6A00E1D237 /* PoolTests.swift in Sources */,
564A20EB226B8E18001F64F1 /* FTS5TableBuilderTests.swift in Sources */,
564A20EC226B8E18001F64F1 /* DatabaseValueConversionErrorTests.swift in Sources */,
564A20ED226B8E18001F64F1 /* TransactionObserverTests.swift in Sources */,
@@ -1440,7 +1456,34 @@
564A1F17226B8750001F64F1 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.9;
ONLY_ACTIVE_ARCH = YES;
SWIFT_VERSION = 4.2;
};
name = Debug;
@@ -1448,6 +1491,31 @@
564A1F18226B8750001F64F1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.9;
SWIFT_VERSION = 4.2;
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -41,6 +41,15 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
@@ -67,17 +76,6 @@
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
@@ -89,8 +87,6 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -15,6 +15,8 @@
56057C6C2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C6A2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; };
560714F3227DD1AE0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */; };
560714F4227DD1AE0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */; };
563DE4FE231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4FF231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; };
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; };
@@ -387,6 +389,8 @@
5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; };
5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; };
56915790231C0D5100E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578F231C0D5100E1D237 /* PoolTests.swift */; };
56915791231C0D5100E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578F231C0D5100E1D237 /* PoolTests.swift */; };
569BBA2E228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; };
569BBA2F228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; };
56DF0021228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; };
@@ -405,6 +409,7 @@
56057C5B2291B8D600A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
56057C6A2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = "<group>"; };
563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
@@ -595,6 +600,7 @@
564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; };
5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = "<group>"; };
56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = "<group>"; };
56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = "<group>"; };
@@ -688,6 +694,7 @@
564A1FD7226B89E0001F64F1 /* DatabaseAfterNextTransactionCommitTests.swift */,
564A1F31226B89CF001F64F1 /* DatabaseAggregateTests.swift */,
564A1F53226B89D2001F64F1 /* DatabaseCollationTests.swift */,
563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */,
564A1F67226B89D5001F64F1 /* DatabaseCursorTests.swift */,
564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */,
564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */,
@@ -778,6 +785,7 @@
564A1FCE226B89DF001F64F1 /* MutablePersistableRecordTests.swift */,
564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */,
564A1FCB226B89DF001F64F1 /* PersistableRecordTests.swift */,
5691578F231C0D5100E1D237 /* PoolTests.swift */,
564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */,
564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */,
564A1F97226B89DA001F64F1 /* PrimaryKeyInfoTests.swift */,
@@ -915,11 +923,14 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1020;
LastUpgradeCheck = 1020;
LastUpgradeCheck = 1100;
TargetAttributes = {
564A1F1C226B876D001F64F1 = {
CreatedOnToolsVersion = 10.2.1;
LastSwiftMigration = 1020;
LastSwiftMigration = 1100;
};
564A2095226B8E18001F64F1 = {
LastSwiftMigration = 1100;
};
};
};
@@ -929,6 +940,7 @@
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 564A1F12226B8750001F64F1;
productRefGroup = 564A1F1E226B876D001F64F1 /* Products */;
@@ -1102,6 +1114,7 @@
564A201F226B89E1001F64F1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
564A2000226B89E1001F64F1 /* PrefixCursorTests.swift in Sources */,
564A1FE1226B89E1001F64F1 /* SelectStatementTests.swift in Sources */,
563DE4FE231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */,
564A1FF8226B89E1001F64F1 /* QueryInterfaceExpressionsTests.swift in Sources */,
564A202E226B89E1001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1135,6 +1148,7 @@
564A2064226B89E1001F64F1 /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */,
564A1FFA226B89E1001F64F1 /* FTS5WrapperTokenizerTests.swift in Sources */,
564A2056226B89E1001F64F1 /* TableRecordTests.swift in Sources */,
56915790231C0D5100E1D237 /* PoolTests.swift in Sources */,
564A2042226B89E1001F64F1 /* FTS5TableBuilderTests.swift in Sources */,
564A2089226B89E1001F64F1 /* DatabaseValueConversionErrorTests.swift in Sources */,
564A2081226B89E1001F64F1 /* TransactionObserverTests.swift in Sources */,
@@ -1300,6 +1314,7 @@
564A20C9226B8E18001F64F1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
564A20CA226B8E18001F64F1 /* PrefixCursorTests.swift in Sources */,
564A20CB226B8E18001F64F1 /* SelectStatementTests.swift in Sources */,
563DE4FF231A9239005081B7 /* DatabaseConfigurationTests.swift in Sources */,
564A20CC226B8E18001F64F1 /* QueryInterfaceExpressionsTests.swift in Sources */,
564A20CD226B8E18001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1333,6 +1348,7 @@
564A20E8226B8E18001F64F1 /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */,
564A20E9226B8E18001F64F1 /* FTS5WrapperTokenizerTests.swift in Sources */,
564A20EA226B8E18001F64F1 /* TableRecordTests.swift in Sources */,
56915791231C0D5100E1D237 /* PoolTests.swift in Sources */,
564A20EB226B8E18001F64F1 /* FTS5TableBuilderTests.swift in Sources */,
564A20EC226B8E18001F64F1 /* DatabaseValueConversionErrorTests.swift in Sources */,
564A20ED226B8E18001F64F1 /* TransactionObserverTests.swift in Sources */,
@@ -1446,7 +1462,34 @@
564A1F17226B8750001F64F1 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.9;
ONLY_ACTIVE_ARCH = YES;
SWIFT_VERSION = 4.2;
};
name = Debug;
@@ -1454,6 +1497,31 @@
564A1F18226B8750001F64F1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.9;
SWIFT_VERSION = 4.2;
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -41,6 +41,15 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
@@ -67,17 +76,6 @@
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
@@ -89,8 +87,6 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -0,0 +1,75 @@
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class DatabaseConfigurationTests: GRDBTestCase {
func testPrepareDatabase() throws {
// prepareDatabase is called when connection opens
var connectionCount = 0
var configuration = Configuration()
configuration.prepareDatabase = { db in
connectionCount += 1
}
_ = DatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 1)
_ = try makeDatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 2)
let pool = try makeDatabasePool(configuration: configuration)
XCTAssertEqual(connectionCount, 3)
try pool.read { _ in }
XCTAssertEqual(connectionCount, 4)
try pool.makeSnapshot().read { _ in }
XCTAssertEqual(connectionCount, 5)
}
func testPrepareDatabaseError() throws {
struct TestError: Error { }
var error: TestError?
var configuration = Configuration()
configuration.prepareDatabase = { db in
if let error = error {
throw error
}
}
// TODO: what about in-memory DatabaseQueue???
do {
error = TestError()
_ = try makeDatabaseQueue(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
_ = try makeDatabasePool(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = nil
let pool = try makeDatabasePool(configuration: configuration)
do {
error = TestError()
try pool.read { _ in }
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
_ = try pool.makeSnapshot()
XCTFail("Expected TestError")
} catch is TestError { }
}
}
}
@@ -8,15 +8,9 @@ import XCTest
class DatabasePoolBackupTests: GRDBTestCase {
func testBackup() throws {
#if GRDBCIPHER
// SQLCipher can't backup encrypted databases: skip this test
if dbConfiguration.passphrase != nil {
return
}
#endif
let source = try makeDatabasePool(filename: "source.sqlite")
let destination = try makeDatabasePool(filename: "destination.sqlite")
// SQLCipher can't backup encrypted databases: use a pristine Configuration
let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration())
let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration())
try source.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
@@ -1186,4 +1186,94 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
#endif
// MARK: - Barrier
func testBarrierLocksReads() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
var fetchedValue: Int?
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
try! dbPool.barrierWriteWithoutTransaction { db in
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s1.signal()
s2.wait()
}
}
DispatchQueue.global().async {
// Wait for barrier to start
s1.wait()
fetchedValue = try! dbPool.read { db in
try Int.fetchOne(db, sql: "SELECT id FROM items")!
}
expectation.fulfill()
s3.signal()
}
// Assert that read is blocked
waitForExpectations(timeout: 1)
// Release barrier
s2.signal()
// Wait for read to complete
s3.wait()
XCTAssertEqual(fetchedValue, 1)
}
}
func testBarrierIsLockedByOneUnfinishedRead() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
let s4 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
try! dbPool.read { _ in
s1.signal()
s2.signal()
s3.wait()
}
}
DispatchQueue.global().async {
// Wait for read to start
s1.wait()
dbPool.barrierWriteWithoutTransaction { _ in }
expectation.fulfill()
s4.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release read
s3.signal()
// Wait for barrier to complete
s4.wait()
}
}
}
@@ -8,15 +8,9 @@ import XCTest
class DatabaseQueueBackupTests: GRDBTestCase {
func testBackup() throws {
#if GRDBCIPHER
// SQLCipher can't backup encrypted databases: skip this test
if dbConfiguration.passphrase != nil {
return
}
#endif
let source = try makeDatabaseQueue(filename: "source.sqlite")
let destination = try makeDatabaseQueue(filename: "destination.sqlite")
// SQLCipher can't backup encrypted databases: use a pristine Configuration
let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration())
let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration())
try source.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
+2 -8
View File
@@ -219,14 +219,8 @@ class DatabaseWriterTests : GRDBTestCase {
// See https://github.com/groue/GRDB.swift/issues/424
func testIssue424Minimal() throws {
#if GRDBCIPHER
// SQLCipher can't backup encrypted databases: skip this test
if dbConfiguration.passphrase != nil {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
// SQLCipher can't backup encrypted databases: use a pristine Configuration
let dbQueue = try makeDatabaseQueue(configuration: Configuration())
try dbQueue.inDatabase { db in
try db.execute(sql: """
CREATE TABLE t(a);
+357 -98
View File
@@ -6,8 +6,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -15,8 +18,11 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
@@ -25,8 +31,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -34,9 +43,8 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabaseQueue(filename: "test.sqlite")
_ = try makeDatabaseQueue(filename: "test.sqlite", configuration: Configuration())
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -47,8 +55,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -56,9 +67,12 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "wrong"
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("wrong")
}
do {
_ = try makeDatabaseQueue(filename: "test.sqlite")
_ = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -66,11 +80,14 @@ class EncryptionTests: GRDBTestCase {
}
}
}
func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -78,9 +95,17 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.change(passphrase: "newSecret")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
try dbQueue.write { db in
try db.changePassphrase("newSecret")
}
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
}
@@ -90,8 +115,11 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "newSecret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
@@ -100,8 +128,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -109,8 +140,11 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
@@ -119,8 +153,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -128,9 +165,8 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabasePool(filename: "test.sqlite")
_ = try makeDatabasePool(filename: "test.sqlite", configuration: Configuration())
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -141,8 +177,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -150,9 +189,12 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "wrong"
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("wrong")
}
do {
_ = try makeDatabasePool(filename: "test.sqlite")
_ = try makeDatabasePool(filename: "test.sqlite", configuration: config)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -163,8 +205,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -172,18 +217,35 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.change(passphrase: "newSecret")
var passphrase = "secret"
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase(passphrase)
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
try dbPool.barrierWriteWithoutTransaction { db in
passphrase = "newSecret"
try db.changePassphrase(passphrase)
dbPool.invalidateReadOnlyConnections()
}
try dbPool.write { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
dbConfiguration.passphrase = "newSecret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
@@ -192,8 +254,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -201,8 +266,11 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
@@ -211,8 +279,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -220,9 +291,8 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabasePool(filename: "test.sqlite")
_ = try makeDatabasePool(filename: "test.sqlite", configuration: Configuration())
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -233,8 +303,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithWrongPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -242,9 +315,12 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "wrong"
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("wrong")
}
do {
_ = try makeDatabasePool(filename: "test.sqlite")
_ = try makeDatabasePool(filename: "test.sqlite", configuration: config)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -256,8 +332,11 @@ class EncryptionTests: GRDBTestCase {
func testDatabasePoolWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
@@ -265,18 +344,35 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
try dbPool.change(passphrase: "newSecret")
var passphrase = "secret"
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase(passphrase)
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
try dbPool.barrierWriteWithoutTransaction { db in
passphrase = "newSecret"
try db.changePassphrase(passphrase)
dbPool.invalidateReadOnlyConnections()
}
try dbPool.write { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
dbConfiguration.passphrase = "newSecret"
let dbPool = try makeDatabasePool(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
@@ -285,8 +381,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPragmaPassphraseToDatabaseQueueWithPassphrase() throws {
do {
dbConfiguration.passphrase = nil
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: Configuration())
try dbQueue.inDatabase { db in
try db.execute(sql: "PRAGMA key = 'secret'")
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
@@ -295,8 +390,11 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
@@ -305,8 +403,7 @@ class EncryptionTests: GRDBTestCase {
func testDatabaseQueueWithPragmaPassphraseToDatabaseQueueWithoutPassphrase() throws {
do {
dbConfiguration.passphrase = nil
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: Configuration())
try dbQueue.inDatabase { db in
try db.execute(sql: "PRAGMA key = 'secret'")
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
@@ -315,9 +412,8 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = nil
do {
_ = try makeDatabaseQueue(filename: "test.sqlite")
_ = try makeDatabaseQueue(filename: "test.sqlite", configuration: Configuration())
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
@@ -328,24 +424,26 @@ class EncryptionTests: GRDBTestCase {
func testCipherPageSize() throws {
do {
dbConfiguration.passphrase = "secret"
dbConfiguration.prepareDatabase = { db in
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_page_size = 8192")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase({ db in
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 8192)
})
}
do {
dbConfiguration.passphrase = "secret"
dbConfiguration.prepareDatabase = { db in
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_page_size = 4096")
}
let dbPool = try makeDatabasePool(filename: "testpool.sqlite")
let dbPool = try makeDatabasePool(filename: "testpool.sqlite", configuration: config)
try dbPool.write({ db in
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 4096)
try db.execute(sql: "CREATE TABLE data(value INTEGER)")
@@ -361,24 +459,26 @@ class EncryptionTests: GRDBTestCase {
func testCipherKDFIterations() throws {
do {
dbConfiguration.passphrase = "secret"
dbConfiguration.prepareDatabase = { db in
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA kdf_iter = 128000")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 128000)
}
}
do {
dbConfiguration.passphrase = "secret"
dbConfiguration.prepareDatabase = { db in
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA kdf_iter = 128000")
}
let dbPool = try makeDatabasePool(filename: "testpool.sqlite")
let dbPool = try makeDatabasePool(filename: "testpool.sqlite", configuration: config)
try dbPool.write { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 128000)
try db.execute(sql: "CREATE TABLE data(value INTEGER)")
@@ -394,12 +494,13 @@ class EncryptionTests: GRDBTestCase {
func testCipherWithMismatchedKDFIterations() throws {
do {
dbConfiguration.passphrase = "secret"
dbConfiguration.prepareDatabase = { db in
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA kdf_iter = 128000")
}
let dbPool = try makeDatabasePool(filename: "testpool.sqlite")
let dbPool = try makeDatabasePool(filename: "testpool.sqlite", configuration: config)
try dbPool.write { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 128000)
try db.execute(sql: "CREATE TABLE data(value INTEGER)")
@@ -413,13 +514,14 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
dbConfiguration.prepareDatabase = { db in
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA kdf_iter = 64000")
}
do {
let dbPool = try makeDatabasePool(filename: "testpool.sqlite")
let dbPool = try makeDatabasePool(filename: "testpool.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 64000)
@@ -436,29 +538,25 @@ class EncryptionTests: GRDBTestCase {
func testExportPlainTextDatabaseToEncryptedDatabase() throws {
// See https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868?source_topic_id=939
do {
// https://github.com/sqlcipher/sqlcipher/issues/216
// SQLCipher 3.4.1 crashes when sqlcipher_export() is called and a
// trace hook has been installed. So we disable query tracing for
// this test.
dbConfiguration.trace = nil
dbConfiguration.passphrase = nil
let plainTextDBQueue = try makeDatabaseQueue(filename: "plaintext.sqlite")
let plainTextDBQueue = try makeDatabaseQueue(filename: "plaintext.sqlite", configuration: Configuration())
try plainTextDBQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
dbConfiguration.passphrase = "secret"
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
do {
_ = try makeDatabaseQueue(filename: "plaintext.sqlite")
_ = try makeDatabaseQueue(filename: "plaintext.sqlite", configuration: config)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is not a database")
}
let encryptedDBQueue = try makeDatabaseQueue(filename: "encrypted.sqlite")
let encryptedDBQueue = try makeDatabaseQueue(filename: "encrypted.sqlite", configuration: config)
try plainTextDBQueue.inDatabase { db in
try db.execute(sql: "ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"])
@@ -468,8 +566,11 @@ class EncryptionTests: GRDBTestCase {
}
do {
dbConfiguration.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "encrypted.sqlite")
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "encrypted.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
@@ -487,8 +588,8 @@ class EncryptionTests: GRDBTestCase {
let testBundle = Bundle(for: type(of: self))
let path = testBundle.url(forResource: "db", withExtension: "SQLCipher3")!.path
var configuration = Configuration()
configuration.passphrase = "secret"
configuration.prepareDatabase = { db in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_compatibility = 3")
}
@@ -505,5 +606,163 @@ class EncryptionTests: GRDBTestCase {
}
}
}
// MARK: - Deprecated
func testDeprecatedPassphrase() throws {
do {
var config = Configuration()
config.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
}
do {
var config = Configuration()
config.passphrase = nil
do {
_ = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is not a database")
}
}
}
func testDeprecatedDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws {
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.change(passphrase: "newSecret")
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
}
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
}
func testDeprecatedDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
}
func testDeprecatedDatabasePoolWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
}
}
#endif
+16 -4
View File
@@ -28,18 +28,28 @@ class GRDBTestCase: XCTestCase {
// Builds a database queue based on dbConfiguration
func makeDatabaseQueue(filename: String? = nil) throws -> DatabaseQueue {
return try makeDatabaseQueue(filename: filename, configuration: dbConfiguration)
}
// Builds a database queue
func makeDatabaseQueue(filename: String? = nil, configuration: Configuration) throws -> DatabaseQueue {
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename ?? ProcessInfo.processInfo.globallyUniqueString)
let dbQueue = try DatabaseQueue(path: dbPath, configuration: dbConfiguration)
let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
try setup(dbQueue)
return dbQueue
}
// Builds a database pool based on dbConfiguration
func makeDatabasePool(filename: String? = nil) throws -> DatabasePool {
return try makeDatabasePool(filename: filename, configuration: dbConfiguration)
}
// Builds a database pool
func makeDatabasePool(filename: String? = nil, configuration: Configuration) throws -> DatabasePool {
try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename ?? ProcessInfo.processInfo.globallyUniqueString)
let dbPool = try DatabasePool(path: dbPath, configuration: dbConfiguration)
let dbPool = try DatabasePool(path: dbPath, configuration: configuration)
try setup(dbPool)
return dbPool
}
@@ -107,8 +117,10 @@ class GRDBTestCase: XCTestCase {
}
#if GRDBCIPHER_USE_ENCRYPTION
// We are testing encrypted databases.
dbConfiguration.passphrase = "secret"
// Encrypt all databases by default.
dbConfiguration.prepareDatabase = { db in
try db.usePassphrase("secret")
}
#endif
sqlQueries = []
+254
View File
@@ -0,0 +1,254 @@
import XCTest
#if GRDBCUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
@testable import GRDB
#endif
class PoolTests: XCTestCase {
/// Returns a Pool whose elements are incremented integers: 1, 2, 3...
private func makeCounterPool(maximumCount: Int) -> Pool<Int> {
let count = ReadWriteBox(0)
return Pool(maximumCount: maximumCount, makeElement: count.increment)
}
func testElementsAreReused() throws {
let pool = makeCounterPool(maximumCount: 2)
// Get and release element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
first.release()
// Get recycled element
let second = try pool.get()
XCTAssertEqual(second.element, 1)
// Get new element
let third = try pool.get()
XCTAssertEqual(third.element, 2)
// Release elements
second.release()
third.release()
// Get and release recycled elements
let fourth = try pool.get()
XCTAssertEqual(fourth.element, 1)
let fifth = try pool.get()
XCTAssertEqual(fifth.element, 2)
fourth.release()
fifth.release()
}
func testRemoveAll() throws {
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
// removeAll is not locked by used elements
pool.removeAll()
// Release elements
first.release()
second.release()
// Get and release new elements
let third = try pool.get()
XCTAssertEqual(third.element, 3)
let fourth = try pool.get()
XCTAssertEqual(fourth.element, 4)
third.release()
fourth.release()
}
func testBarrierLocksElements() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
var element: Int?
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier {
s1.signal()
s2.wait()
}
}
DispatchQueue.global().async {
// Wait for barrier to start
s1.wait()
let first = try! pool.get()
element = first.element
first.release()
expectation.fulfill()
s3.signal()
}
// Assert that get() is blocked
waitForExpectations(timeout: 1)
// Release barrier
s2.signal()
// Wait for get() to complete
s3.wait()
XCTAssertEqual(element, 1)
}
}
func testBarrierIsLockedByOneUsedElementOutOfOne() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
// Get element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release element
first.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let second = try pool.get()
XCTAssertEqual(second.element, 1)
second.release()
}
}
func testBarrierIsLockedByOneUsedElementOutOfTwo() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
// Release first element
first.release()
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release second element
second.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
third.release()
}
}
func testBarrierIsLockedByTwoUsedElementsOutOfTwo() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release elements
first.release()
second.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
third.release()
}
}
func testBarrierRemoveAll() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
// Get element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
// No deadlock
pool.barrier { pool.removeAll() }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release element
first.release()
// Wait for barrier to complete
s.wait()
// Get and release new element
let second = try pool.get()
XCTAssertEqual(second.element, 2)
second.release()
}
}
}