From 06d6c3866bc9f61bdaf8a39a9cc26b435ce7a64d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 16:28:16 +0200 Subject: [PATCH 01/45] ReadWriteBox Cleanup --- GRDB/Utils/ReadWriteBox.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift index 4dc9e4fec..b7c0b4449 100644 --- a/GRDB/Utils/ReadWriteBox.swift +++ b/GRDB/Utils/ReadWriteBox.swift @@ -8,8 +8,8 @@ final class ReadWriteBox { } 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(_ block: (T) throws -> U) rethrows -> U { @@ -29,6 +29,7 @@ final class ReadWriteBox { } extension ReadWriteBox where T: Numeric { + @discardableResult func increment() -> T { return write { n in n += 1 From e495df0114c03ef23ae214d2d58585609e35bc38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 16:32:18 +0200 Subject: [PATCH 02/45] Pool.barrier --- GRDB/Core/DatabasePool.swift | 11 ++-- GRDB/Utils/Pool.swift | 98 ++++++++++++++++++++++-------------- 2 files changed, 68 insertions(+), 41 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 2cc913f07..60a3e1bee 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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() + } } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 8c9c49657..b4555a289 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -38,52 +38,52 @@ import Dispatch final class Pool { 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 { 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 { } } - /// 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(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(execute barrier: () throws -> T) rethrows -> T { + return try barrierQueue.sync(flags: [.barrier]) { + itemsGroup.wait() + return try barrier() } } } From 473f6ff0d836c922337c50750de36afd30d87b86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 16:32:39 +0200 Subject: [PATCH 03/45] Tests for Pool.barrier --- GRDB.xcodeproj/project.pbxproj | 8 + GRDBCustom.xcodeproj/project.pbxproj | 8 +- .../GRDBTests.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + Tests/GRDBTests/PoolTests.swift | 254 ++++++++++++++++++ 5 files changed, 281 insertions(+), 1 deletion(-) create mode 100644 Tests/GRDBTests/PoolTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 6e64fd1c9..d860e10b7 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -490,6 +490,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 */; }; @@ -1477,6 +1480,7 @@ 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = ""; }; 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; + 56915781231BF28B00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = ""; }; 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = ""; }; @@ -2177,6 +2181,7 @@ 569BBA4522906A8200478429 /* InflectionsTests.json */, 569BBA3522905FFA00478429 /* InflectionsTests.swift */, 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */, + 56915781231BF28B00E1D237 /* PoolTests.swift */, 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */, 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */, ); @@ -3494,6 +3499,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 */, @@ -3694,6 +3700,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 */, @@ -4026,6 +4033,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 */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index a25ad20d2..3ff27b2ef 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -323,6 +323,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 */; }; @@ -899,6 +901,7 @@ 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = ""; }; 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; + 5691578B231BF2BE00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = ""; }; 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = ""; }; @@ -1514,6 +1517,7 @@ 569BBA42229066CB00478429 /* InflectionsTests.json */, 569BBA3E229065CF00478429 /* InflectionsTests.swift */, 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */, + 5691578B231BF2BE00E1D237 /* PoolTests.swift */, 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */, 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */, ); @@ -1546,8 +1550,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 */, @@ -2385,6 +2389,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 */, @@ -2717,6 +2722,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 */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index b68c3c6f9..84058313d 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -385,6 +385,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 */; }; @@ -592,6 +594,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 = ""; }; 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; + 56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; @@ -774,6 +777,7 @@ 564A1FCE226B89DF001F64F1 /* MutablePersistableRecordTests.swift */, 564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */, 564A1FCB226B89DF001F64F1 /* PersistableRecordTests.swift */, + 56915792231C0D6A00E1D237 /* PoolTests.swift */, 564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */, 564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */, 564A1F97226B89DA001F64F1 /* PrimaryKeyInfoTests.swift */, @@ -1129,6 +1133,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 */, @@ -1327,6 +1332,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 */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 573504ba6..f1c26e03c 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -387,6 +387,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 */; }; @@ -595,6 +597,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 = ""; }; 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; + 5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; @@ -778,6 +781,7 @@ 564A1FCE226B89DF001F64F1 /* MutablePersistableRecordTests.swift */, 564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */, 564A1FCB226B89DF001F64F1 /* PersistableRecordTests.swift */, + 5691578F231C0D5100E1D237 /* PoolTests.swift */, 564A1F49226B89D1001F64F1 /* PrefixCursorTests.swift */, 564A1F46226B89D1001F64F1 /* PrefixWhileCursorTests.swift */, 564A1F97226B89DA001F64F1 /* PrimaryKeyInfoTests.swift */, @@ -1135,6 +1139,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 */, @@ -1333,6 +1338,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 */, diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift new file mode 100644 index 000000000..7cb9f6680 --- /dev/null +++ b/Tests/GRDBTests/PoolTests.swift @@ -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 { + 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() + } + } +} From 8580023eda86117e6cf707bfc806b63e97ccd7e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 16:46:17 +0200 Subject: [PATCH 04/45] DatabasePool.barrierWriteWithoutTransaction --- GRDB/Core/DatabasePool.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 60a3e1bee..927ad74fc 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -636,6 +636,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(_ 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. /// From e3efcc0d87bc1b6dd9d5b581455997b22f07574b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 17:03:22 +0200 Subject: [PATCH 05/45] CHANGELOG --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f1dc658b..879a4f802 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 4.x Releases @@ -56,9 +54,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [0.110.0](#01100), ... - + +**New** + +- [#603](https://github.com/groue/GRDB.swift/pull/603): DatabasePool write barrier ## 4.3.0 From 5b4a225dc3a590cff73b0294d2ea4828a3028804 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 17:19:12 +0200 Subject: [PATCH 06/45] DatabasePool.barrierWriteWithoutTransaction tests --- .../DatabasePoolConcurrencyTests.swift | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 43ed466cb..4abb7c433 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1186,4 +1186,87 @@ 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)") + } + + // Read + let s1 = DispatchSemaphore(value: 0) + let s2 = DispatchSemaphore(value: 0) + dbPool.asyncRead { _ in + s1.signal() + s2.wait() + } + + let s3 = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + dbPool.barrierWriteWithoutTransaction { _ in } + expectation.fulfill() + s3.signal() + } + + // Assert that barrier is blocked + waitForExpectations(timeout: 1) + + // Release read + s2.signal() + + // Wait for barrier to complete + s3.wait() + } + } } From 04a6e969a5c9af277a9f8b7984b75d3c5a742943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 17:30:01 +0200 Subject: [PATCH 07/45] DatabasePool.barrierWriteWithoutTransaction documentation --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index 0b46bd50d..9b31beb03 100644 --- a/README.md +++ b/README.md @@ -8016,6 +8016,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 +8094,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.** From c7e4492846338907006b1476aeda8ac2a11ca883 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 19:33:03 +0200 Subject: [PATCH 08/45] Fix DatabasePool.change(passphrase:) --- GRDB/Core/DatabasePool.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 927ad74fc..f66f62539 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -243,10 +243,11 @@ extension DatabasePool { /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { - try readerPool.clear(andThen: { + try readerPool.barrier { try writer.sync { try $0.change(passphrase: passphrase) } + readerPool.removeAll() readerConfig.passphrase = passphrase - }) + } } } #endif From 00e2c2a626fa42133d734e700b2037da797e2891 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Sep 2019 05:39:38 +0200 Subject: [PATCH 09/45] Fix testBarrierIsLockedByOneUnfinishedRead for Swift 4.2 --- .../DatabasePoolConcurrencyTests.swift | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 4abb7c433..e02486620 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1244,29 +1244,36 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") } - // Read let s1 = DispatchSemaphore(value: 0) let s2 = DispatchSemaphore(value: 0) - dbPool.asyncRead { _ in - s1.signal() - s2.wait() + let s3 = DispatchSemaphore(value: 0) + let s4 = DispatchSemaphore(value: 0) + + DispatchQueue.global().async { + try! dbPool.read { _ in + s1.signal() + s2.signal() + s3.wait() + } } - let s3 = DispatchSemaphore(value: 0) DispatchQueue.global().async { + // Wait for read to start + s1.wait() + dbPool.barrierWriteWithoutTransaction { _ in } expectation.fulfill() - s3.signal() + s4.signal() } // Assert that barrier is blocked waitForExpectations(timeout: 1) // Release read - s2.signal() + s3.signal() // Wait for barrier to complete - s3.wait() + s4.wait() } } } From 943eca10a6c061c7f2839ff654786bb6a9d4b5a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 13:08:02 +0200 Subject: [PATCH 10/45] TODO --- TODO.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/TODO.md b/TODO.md index 0e03453df..98b3ce3d8 100644 --- a/TODO.md +++ b/TODO.md @@ -40,6 +40,14 @@ let players = Player.filter(...) // Returns a request that filters on column A or column B depending on the argument players.update(...) // Runs the expected UPDATE statement ``` +- [ ] Database.decrypt(with:) + - [ ] In order to allow SQLCipher tests to run all tests in an encrypted database, we need to make it possible to register several independent preparation blocks: + - [ ] Deprecate DatabaseConfiguration.prepareDatabase + - [ ] Introduce DatabaseConfiguration.onConnect { ... } as a replacement for DatabaseConfiguration.prepareDatabase + - [ ] Consider introducing DatabaseConfiguration.onDisconnect { ... } + - [ ] Deprecate change(passphrase:), and provide a static function instead + - [ ] Introduce Database.decrypt(with:) + - [ ] Deprecate DatabaseConfiguration.passphrase ## Unsure if necessary From 8f6611404222d3fdbc3c94e99093a0b14dc9f215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 13:11:32 +0200 Subject: [PATCH 11/45] Deprecate Configuration.prepareDatabase --- GRDB/Core/Configuration.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 1194e9a11..03bd553e0 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -99,6 +99,7 @@ public struct Configuration { /// config.prepareDatabase = { db in /// try db.execute(sql: "PRAGMA kdf_iter = 10000") /// } + @available(*, deprecated, message: "Register the database preparation function with Configuration.onConnect { db in ... } instead") public var prepareDatabase: ((Database) throws -> Void)? // MARK: - Transactions From d8b0b95842f1cde47408ae14b519537094b73708 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 14:03:30 +0200 Subject: [PATCH 12/45] DatabaseConfiguration.onConnect --- GRDB.xcodeproj/project.pbxproj | 8 ++ GRDB/Core/Configuration.swift | 51 +++++++++--- GRDB/Core/Database.swift | 5 +- GRDBCustom.xcodeproj/project.pbxproj | 6 ++ TODO.md | 7 +- .../GRDBTests.xcodeproj/project.pbxproj | 6 ++ .../GRDBTests.xcodeproj/project.pbxproj | 6 ++ .../DatabaseConfigurationTests.swift | 83 +++++++++++++++++++ Tests/GRDBTests/EncryptionTests.swift | 14 ++-- Tests/GRDBTests/GRDBTestCase.swift | 14 +++- 10 files changed, 175 insertions(+), 25 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseConfigurationTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d860e10b7..09e2a5b62 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 */; }; @@ -1363,6 +1366,7 @@ 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; 563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; @@ -2196,6 +2200,7 @@ 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */, 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */, 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */, + 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, @@ -3396,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 */, @@ -3597,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 */, @@ -3930,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 */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 03bd553e0..5f96a7e24 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -75,7 +75,6 @@ public struct Configuration { /// Default: nil public var trace: TraceFunction? - // MARK: - Encryption #if SQLITE_HAS_CODEC @@ -83,15 +82,16 @@ public struct Configuration { /// /// Default: nil public var passphrase: String? - #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 + + // TODO: remove when the deprecated prepareDatabase turns unavailable. + private var _prepareDatabase: ((Database) throws -> Void)? + private var _databaseDidConnect: ((Database) throws -> Void)? + + /// A function that is run when an SQLite connection is opened, before the + /// connection is made available for database access methods. /// /// For example: /// @@ -99,8 +99,39 @@ public struct Configuration { /// config.prepareDatabase = { db in /// try db.execute(sql: "PRAGMA kdf_iter = 10000") /// } - @available(*, deprecated, message: "Register the database preparation function with Configuration.onConnect { db in ... } instead") - public var prepareDatabase: ((Database) throws -> Void)? + @available(*, deprecated, message: "Register the database preparation function with Configuration.onConnect { db in ... } instead") // swiftlint:disable:this line_length + public var prepareDatabase: ((Database) throws -> Void)? { + get { return _prepareDatabase } + set { _prepareDatabase = newValue } + } + + /// Registers a function that is run when an SQLite connection is opened, + /// before the connection is made available for database access methods. + /// + /// For example: + /// + /// var config = Configuration() + /// config.onConnect { db in + /// try db.execute(sql: "PRAGMA kdf_iter = 10000") + /// } + /// + /// You can call this method multiple times. All registered functions are + /// run, in the same order as their registration. + public mutating func onConnect(execute function: @escaping (Database) throws -> Void) { + if let old = _databaseDidConnect { + _databaseDidConnect = { db in + try old(db) + try function(db) + } + } else { + _databaseDidConnect = function + } + } + + func databaseDidConnect(_ db: Database) throws { + try _prepareDatabase?(db) + try _databaseDidConnect?(db) + } // MARK: - Transactions diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 70cafee1a..72f8b5ab8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -219,9 +219,8 @@ extension Database { #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 configuration.databaseDidConnect(self) + try validateFormat() configuration.SQLiteConnectionDidOpen?() } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3ff27b2ef..cfff7548f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -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 */; }; @@ -774,6 +776,7 @@ 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; 563EF44C2161F196007DAACD /* Inflections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Inflections.swift; sourceTree = ""; }; @@ -1532,6 +1535,7 @@ 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */, 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */, 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */, + 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, @@ -2286,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 */, @@ -2619,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 */, diff --git a/TODO.md b/TODO.md index 98b3ce3d8..154b23116 100644 --- a/TODO.md +++ b/TODO.md @@ -42,12 +42,13 @@ ``` - [ ] Database.decrypt(with:) - [ ] In order to allow SQLCipher tests to run all tests in an encrypted database, we need to make it possible to register several independent preparation blocks: - - [ ] Deprecate DatabaseConfiguration.prepareDatabase - - [ ] Introduce DatabaseConfiguration.onConnect { ... } as a replacement for DatabaseConfiguration.prepareDatabase + - [X] Deprecate DatabaseConfiguration.prepareDatabase + - [X] Introduce DatabaseConfiguration.onConnect { ... } as a replacement for DatabaseConfiguration.prepareDatabase - [ ] Consider introducing DatabaseConfiguration.onDisconnect { ... } - [ ] Deprecate change(passphrase:), and provide a static function instead - - [ ] Introduce Database.decrypt(with:) + - [ ] Introduce Database.decrypt(with:). Make it a no-op if DatabaseConfiguration.passphrase is not nil. - [ ] Deprecate DatabaseConfiguration.passphrase + - [ ] Remove SQLiteConnectionDidOpen and ## Unsure if necessary diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 84058313d..efbba5c3c 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -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 */; }; @@ -405,6 +407,7 @@ 56057C5E2291B8E400A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; 56057C672291D0AB00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = ""; }; 560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = ""; }; + 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 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 = ""; }; 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; @@ -688,6 +691,7 @@ 564A1FD7226B89E0001F64F1 /* DatabaseAfterNextTransactionCommitTests.swift */, 564A1F31226B89CF001F64F1 /* DatabaseAggregateTests.swift */, 564A1F53226B89D2001F64F1 /* DatabaseCollationTests.swift */, + 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */, 564A1F67226B89D5001F64F1 /* DatabaseCursorTests.swift */, 564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */, 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, @@ -1100,6 +1104,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 */, @@ -1299,6 +1304,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 */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index f1c26e03c..3b8f19972 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -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 */; }; @@ -407,6 +409,7 @@ 56057C5B2291B8D600A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; 56057C6A2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = ""; }; 560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = ""; }; + 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 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 = ""; }; 564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; @@ -691,6 +694,7 @@ 564A1FD7226B89E0001F64F1 /* DatabaseAfterNextTransactionCommitTests.swift */, 564A1F31226B89CF001F64F1 /* DatabaseAggregateTests.swift */, 564A1F53226B89D2001F64F1 /* DatabaseCollationTests.swift */, + 563DE4FD231A9238005081B7 /* DatabaseConfigurationTests.swift */, 564A1F67226B89D5001F64F1 /* DatabaseCursorTests.swift */, 564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */, 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, @@ -1106,6 +1110,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 */, @@ -1305,6 +1310,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 */, diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift new file mode 100644 index 000000000..3c1286714 --- /dev/null +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -0,0 +1,83 @@ +import XCTest +#if GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class DatabaseConfigurationTests: GRDBTestCase { + func testOnConnect() throws { + // onConnect is called when connection opens + var connectionCount = 0 + var configuration = Configuration() + configuration.onConnect { 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) + } + + func testMultipleOnConnect() throws { + // onConnect can be called multiple times. Order is deterministic. + var events: [Int] = [] + var configuration = Configuration() + configuration.onConnect { db in + events.append(1) + } + configuration.onConnect { db in + events.append(2) + } + + _ = DatabaseQueue(configuration: configuration) + XCTAssertEqual(events, [1, 2]) + } + + func testDeprecatedPrepareDatabase() 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) + } + + func testDeprecatedPrepareDatabaseIsCalledBeforeOnConnect() throws { + // prepareDatabase is called before onConnect functions + var events: [Int] = [] + var configuration = Configuration() + configuration.onConnect { db in + events.append(2) + } + configuration.prepareDatabase = { db in + events.append(1) + } + configuration.onConnect { db in + events.append(3) + } + + _ = DatabaseQueue(configuration: configuration) + XCTAssertEqual(events, [1, 2, 3]) + } +} diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 8bfbb634e..f5c66e0bf 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -329,7 +329,7 @@ class EncryptionTests: GRDBTestCase { func testCipherPageSize() throws { do { dbConfiguration.passphrase = "secret" - dbConfiguration.prepareDatabase = { db in + dbConfiguration.onConnect { db in try db.execute(sql: "PRAGMA cipher_page_size = 8192") } @@ -341,7 +341,7 @@ class EncryptionTests: GRDBTestCase { do { dbConfiguration.passphrase = "secret" - dbConfiguration.prepareDatabase = { db in + dbConfiguration.onConnect { db in try db.execute(sql: "PRAGMA cipher_page_size = 4096") } @@ -362,7 +362,7 @@ class EncryptionTests: GRDBTestCase { func testCipherKDFIterations() throws { do { dbConfiguration.passphrase = "secret" - dbConfiguration.prepareDatabase = { db in + dbConfiguration.onConnect { db in try db.execute(sql: "PRAGMA kdf_iter = 128000") } @@ -374,7 +374,7 @@ class EncryptionTests: GRDBTestCase { do { dbConfiguration.passphrase = "secret" - dbConfiguration.prepareDatabase = { db in + dbConfiguration.onConnect { db in try db.execute(sql: "PRAGMA kdf_iter = 128000") } @@ -395,7 +395,7 @@ class EncryptionTests: GRDBTestCase { func testCipherWithMismatchedKDFIterations() throws { do { dbConfiguration.passphrase = "secret" - dbConfiguration.prepareDatabase = { db in + dbConfiguration.onConnect { db in try db.execute(sql: "PRAGMA kdf_iter = 128000") } @@ -414,7 +414,7 @@ class EncryptionTests: GRDBTestCase { do { dbConfiguration.passphrase = "secret" - dbConfiguration.prepareDatabase = { db in + dbConfiguration.onConnect { db in try db.execute(sql: "PRAGMA kdf_iter = 64000") } @@ -488,7 +488,7 @@ class EncryptionTests: GRDBTestCase { let path = testBundle.url(forResource: "db", withExtension: "SQLCipher3")!.path var configuration = Configuration() configuration.passphrase = "secret" - configuration.prepareDatabase = { db in + configuration.onConnect { db in try db.execute(sql: "PRAGMA cipher_compatibility = 3") } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index b9af335f6..459c6f1ca 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -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 } From eb112c912cceb32c19c2fa8197e237d6fef878ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 14:12:51 +0200 Subject: [PATCH 13/45] Fix Xcode 11 warnings in SQLCipher test projects --- .../GRDBTests.xcodeproj/project.pbxproj | 60 ++++++++++++++++++- .../xcshareddata/xcschemes/GRDBTests.xcscheme | 24 ++++---- .../GRDBTests.xcodeproj/project.pbxproj | 60 ++++++++++++++++++- .../xcshareddata/xcschemes/GRDBTests.xcscheme | 24 ++++---- 4 files changed, 136 insertions(+), 32 deletions(-) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index efbba5c3c..4a6e14f50 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -919,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; }; }; }; @@ -933,6 +936,7 @@ hasScannedForEncodings = 0; knownRegions = ( en, + Base, ); mainGroup = 564A1F12226B8750001F64F1; productRefGroup = 564A1F1E226B876D001F64F1 /* Products */; @@ -1452,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; @@ -1460,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; }; diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/xcshareddata/xcschemes/GRDBTests.xcscheme b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/xcshareddata/xcschemes/GRDBTests.xcscheme index 81d5a2758..2d421f983 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/xcshareddata/xcschemes/GRDBTests.xcscheme +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/xcshareddata/xcschemes/GRDBTests.xcscheme @@ -1,6 +1,6 @@ + + + + - - - - - - - - + + + + - - - - - - - - Date: Sat, 31 Aug 2019 17:19:03 +0200 Subject: [PATCH 14/45] Deprecate Configuration.passphrase, introduce Database.usePassphrase(_:) --- GRDB/Core/Configuration.swift | 11 +- GRDB/Core/Database.swift | 44 +-- GRDB/Core/DatabasePool.swift | 2 +- TODO.md | 5 +- Tests/GRDBTests/DatabasePoolBackupTests.swift | 12 +- .../GRDBTests/DatabaseQueueBackupTests.swift | 12 +- Tests/GRDBTests/DatabaseWriterTests.swift | 10 +- Tests/GRDBTests/EncryptionTests.swift | 295 ++++++++++++------ Tests/GRDBTests/GRDBTestCase.swift | 6 +- 9 files changed, 252 insertions(+), 145 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 5f96a7e24..6aae87db0 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -78,10 +78,17 @@ public struct Configuration { // 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.onConnect(execute:) instead.") + public var passphrase: String? { + get { return _passphrase } + set { _passphrase = newValue } + } #endif // MARK: - Managing SQLite Connections @@ -99,7 +106,7 @@ public struct Configuration { /// config.prepareDatabase = { db in /// try db.execute(sql: "PRAGMA kdf_iter = 10000") /// } - @available(*, deprecated, message: "Register the database preparation function with Configuration.onConnect { db in ... } instead") // swiftlint:disable:this line_length + @available(*, deprecated, message: "Use onConnect instead") public var prepareDatabase: ((Database) throws -> Void)? { get { return _prepareDatabase } set { _prepareDatabase = newValue } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 72f8b5ab8..b70fce697 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -213,8 +213,8 @@ 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 @@ -384,22 +384,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 { @@ -974,6 +958,30 @@ extension Database { // MARK: - Encryption + /// Sets the passphrase used to crypt and decrypt an SQLCipher database. + /// + /// Call this method from Configuration.onConnect, as in the example below: + /// + /// var config = Configuration() + /// config.prepareDatabase = { db in + /// try db.usePassphrase("secret") + /// } + public 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))) + } + } + func change(passphrase: String) throws { // FIXME: sqlite3_rekey is discouraged. // diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index f66f62539..e17db9eef 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -246,7 +246,7 @@ extension DatabasePool { try readerPool.barrier { try writer.sync { try $0.change(passphrase: passphrase) } readerPool.removeAll() - readerConfig.passphrase = passphrase + readerConfig._passphrase = passphrase } } } diff --git a/TODO.md b/TODO.md index 154b23116..00ba36705 100644 --- a/TODO.md +++ b/TODO.md @@ -40,13 +40,14 @@ let players = Player.filter(...) // Returns a request that filters on column A or column B depending on the argument players.update(...) // Runs the expected UPDATE statement ``` -- [ ] Database.decrypt(with:) +- [ ] Database.usePassphrase(_:) - [ ] In order to allow SQLCipher tests to run all tests in an encrypted database, we need to make it possible to register several independent preparation blocks: - [X] Deprecate DatabaseConfiguration.prepareDatabase - [X] Introduce DatabaseConfiguration.onConnect { ... } as a replacement for DatabaseConfiguration.prepareDatabase - [ ] Consider introducing DatabaseConfiguration.onDisconnect { ... } - [ ] Deprecate change(passphrase:), and provide a static function instead - - [ ] Introduce Database.decrypt(with:). Make it a no-op if DatabaseConfiguration.passphrase is not nil. + - [ ] Introduce Database.usePassphrase(_:). + - [ ] Make Database.usePassphrase(_:) a no-op if DatabaseConfiguration._passphrase is not nil, as support for the deprecated change(passphrase:). - [ ] Deprecate DatabaseConfiguration.passphrase - [ ] Remove SQLiteConnectionDidOpen and diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 55c760afd..790836fc9 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -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)") diff --git a/Tests/GRDBTests/DatabaseQueueBackupTests.swift b/Tests/GRDBTests/DatabaseQueueBackupTests.swift index 83ec12391..8f2662d91 100644 --- a/Tests/GRDBTests/DatabaseQueueBackupTests.swift +++ b/Tests/GRDBTests/DatabaseQueueBackupTests.swift @@ -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)") diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 0f13d9482..908188dcb 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -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); diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index f5c66e0bf..726902800 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -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.onConnect { 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.onConnect { 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.onConnect { 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.onConnect { 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.onConnect { 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) @@ -69,8 +83,11 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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,8 +95,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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)") @@ -90,8 +110,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "newSecret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +123,11 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +135,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +148,11 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithoutPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +160,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 +172,11 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithWrongPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +184,12 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "wrong" + var config = Configuration() + config.onConnect { 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 +200,11 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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,8 +212,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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)") @@ -182,8 +225,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "newSecret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +238,11 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +250,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +263,11 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithoutPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +275,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 +287,11 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithWrongPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +299,12 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "wrong" + var config = Configuration() + config.onConnect { 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 +316,11 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithNewPassphrase() throws { do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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,8 +328,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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)") @@ -275,8 +341,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "newSecret" - let dbPool = try makeDatabasePool(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +354,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 +363,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") + var config = Configuration() + config.onConnect { 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 +376,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 +385,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 +397,26 @@ class EncryptionTests: GRDBTestCase { func testCipherPageSize() throws { do { - dbConfiguration.passphrase = "secret" - dbConfiguration.onConnect { db in + var config = Configuration() + config.onConnect { 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.onConnect { db in + var config = Configuration() + config.onConnect { 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 +432,26 @@ class EncryptionTests: GRDBTestCase { func testCipherKDFIterations() throws { do { - dbConfiguration.passphrase = "secret" - dbConfiguration.onConnect { db in + var config = Configuration() + config.onConnect { 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.onConnect { db in + var config = Configuration() + config.onConnect { 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 +467,13 @@ class EncryptionTests: GRDBTestCase { func testCipherWithMismatchedKDFIterations() throws { do { - dbConfiguration.passphrase = "secret" - dbConfiguration.onConnect { db in + var config = Configuration() + config.onConnect { 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 +487,14 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - dbConfiguration.onConnect { db in + var config = Configuration() + config.onConnect { 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 +511,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.onConnect { 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 +539,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "encrypted.sqlite") + var config = Configuration() + config.onConnect { 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 +561,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.onConnect { db in + try db.usePassphrase("secret") try db.execute(sql: "PRAGMA cipher_compatibility = 3") } @@ -505,5 +579,38 @@ class EncryptionTests: GRDBTestCase { } } } + +// 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") +// } +// } +// } } #endif diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 459c6f1ca..093899c0c 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -117,8 +117,10 @@ class GRDBTestCase: XCTestCase { } #if GRDBCIPHER_USE_ENCRYPTION - // We are testing encrypted databases. - dbConfiguration.passphrase = "secret" + // Encrypt all databases by default. + dbConfiguration.onConnect { db in + try db.usePassphrase("secret") + } #endif sqlQueries = [] From aded6d206d3a275a468dffaaededb6211626f0c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 17:26:40 +0200 Subject: [PATCH 15/45] Failing test for change(passphrase:) --- Tests/GRDBTests/EncryptionTests.swift | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 726902800..56bb37cb5 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -222,6 +222,9 @@ class EncryptionTests: GRDBTestCase { 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 { @@ -338,6 +341,9 @@ class EncryptionTests: GRDBTestCase { 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 { From 1ba4e8c7715da9f6cce02f9f3512ecfb336c049e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 17:49:42 +0200 Subject: [PATCH 16/45] Fix failing test for change(passphrase:) --- GRDB/Core/Database.swift | 13 ++++++++++++- TODO.md | 6 +++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b70fce697..043ccdea0 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -214,7 +214,7 @@ extension Database { #if SQLITE_HAS_CODEC try validateSQLCipher() if let passphrase = configuration._passphrase { - try usePassphrase(passphrase) + try _usePassphrase(passphrase) } #endif @@ -967,6 +967,17 @@ extension Database { /// 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 { diff --git a/TODO.md b/TODO.md index 00ba36705..46bc7048c 100644 --- a/TODO.md +++ b/TODO.md @@ -46,9 +46,9 @@ - [X] Introduce DatabaseConfiguration.onConnect { ... } as a replacement for DatabaseConfiguration.prepareDatabase - [ ] Consider introducing DatabaseConfiguration.onDisconnect { ... } - [ ] Deprecate change(passphrase:), and provide a static function instead - - [ ] Introduce Database.usePassphrase(_:). - - [ ] Make Database.usePassphrase(_:) a no-op if DatabaseConfiguration._passphrase is not nil, as support for the deprecated change(passphrase:). - - [ ] Deprecate DatabaseConfiguration.passphrase + - [X] Introduce Database.usePassphrase(_:). + - [X] Make Database.usePassphrase(_:) a no-op if DatabaseConfiguration._passphrase is not nil, as support for the deprecated change(passphrase:). + - [X] Deprecate DatabaseConfiguration.passphrase - [ ] Remove SQLiteConnectionDidOpen and From 0b9fe9ae92b8a3f6d9ad85bbfcb62c9e6b5ae5e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2019 19:21:43 +0200 Subject: [PATCH 17/45] Documentation --- Documentation/GRDB3MigrationGuide.md | 4 ++-- GRDB/Core/Database.swift | 2 +- GRDB/Fixit/GRDB-4.0.swift | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Documentation/GRDB3MigrationGuide.md b/Documentation/GRDB3MigrationGuide.md index f698f1a0b..62ba66443 100644 --- a/Documentation/GRDB3MigrationGuide.md +++ b/Documentation/GRDB3MigrationGuide.md @@ -141,12 +141,12 @@ The integration of GRDB with SQLCipher has changed. 2. The default SQLCipher version which comes with GRDB 4 is now SQLCipher 4, which is incompatible with SQLCipher 3. SQLCipher 3 is still supported, though. See [Encryption] for more details. -3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `prepareDatabase` property of the configuration: +3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `onConnect` method of the configuration: ```swift var configuration = Configuration() configuration.passphrase = "secret" - configuration.prepareDatabase = { db in + configuration.onConnect { db in try db.execute(sql: "PRAGMA cipher_page_size = 4096") try db.execute(sql: "PRAGMA kdf_iter = 128000") } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 043ccdea0..041321dfe 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -963,7 +963,7 @@ extension Database { /// Call this method from Configuration.onConnect, as in the example below: /// /// var config = Configuration() - /// config.prepareDatabase = { db in + /// config.onConnect { db in /// try db.usePassphrase("secret") /// } public func usePassphrase(_ passphrase: String) throws { diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift index 1c6c41220..d4e9487cc 100644 --- a/GRDB/Fixit/GRDB-4.0.swift +++ b/GRDB/Fixit/GRDB-4.0.swift @@ -257,13 +257,13 @@ extension ValueObservation { } extension Configuration { - @available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.prepareDatabase instead.") + @available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.onConnect instead.") public var cipherPageSize: Int { get { preconditionFailure() } set { preconditionFailure() } } - @available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.prepareDatabase instead.") + @available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.onConnect instead.") public var kdfIterations: Int { get { preconditionFailure() } set { preconditionFailure() } From 9f26777cc35a4b2b4221399796518a7211bbcbc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Sep 2019 06:55:10 +0200 Subject: [PATCH 18/45] prepareDatabase did not need to be deprecated, after all --- Documentation/GRDB3MigrationGuide.md | 4 +- GRDB/Core/Configuration.swift | 40 +---------- GRDB/Core/Database.swift | 6 +- GRDB/Fixit/GRDB-4.0.swift | 4 +- TODO.md | 7 +- .../DatabaseConfigurationTests.swift | 56 +-------------- Tests/GRDBTests/EncryptionTests.swift | 68 +++++++++---------- Tests/GRDBTests/GRDBTestCase.swift | 2 +- 8 files changed, 46 insertions(+), 141 deletions(-) diff --git a/Documentation/GRDB3MigrationGuide.md b/Documentation/GRDB3MigrationGuide.md index 62ba66443..f698f1a0b 100644 --- a/Documentation/GRDB3MigrationGuide.md +++ b/Documentation/GRDB3MigrationGuide.md @@ -141,12 +141,12 @@ The integration of GRDB with SQLCipher has changed. 2. The default SQLCipher version which comes with GRDB 4 is now SQLCipher 4, which is incompatible with SQLCipher 3. SQLCipher 3 is still supported, though. See [Encryption] for more details. -3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `onConnect` method of the configuration: +3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `prepareDatabase` property of the configuration: ```swift var configuration = Configuration() configuration.passphrase = "secret" - configuration.onConnect { db in + configuration.prepareDatabase = { db in try db.execute(sql: "PRAGMA cipher_page_size = 4096") try db.execute(sql: "PRAGMA kdf_iter = 128000") } diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 6aae87db0..88ae224aa 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -84,7 +84,7 @@ public struct Configuration { /// The passphrase for the encrypted database. /// /// Default: nil - @available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.onConnect(execute:) instead.") + @available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") public var passphrase: String? { get { return _passphrase } set { _passphrase = newValue } @@ -93,10 +93,6 @@ public struct Configuration { // MARK: - Managing SQLite Connections - // TODO: remove when the deprecated prepareDatabase turns unavailable. - private var _prepareDatabase: ((Database) throws -> Void)? - private var _databaseDidConnect: ((Database) throws -> Void)? - /// A function that is run when an SQLite connection is opened, before the /// connection is made available for database access methods. /// @@ -106,39 +102,7 @@ public struct Configuration { /// config.prepareDatabase = { db in /// try db.execute(sql: "PRAGMA kdf_iter = 10000") /// } - @available(*, deprecated, message: "Use onConnect instead") - public var prepareDatabase: ((Database) throws -> Void)? { - get { return _prepareDatabase } - set { _prepareDatabase = newValue } - } - - /// Registers a function that is run when an SQLite connection is opened, - /// before the connection is made available for database access methods. - /// - /// For example: - /// - /// var config = Configuration() - /// config.onConnect { db in - /// try db.execute(sql: "PRAGMA kdf_iter = 10000") - /// } - /// - /// You can call this method multiple times. All registered functions are - /// run, in the same order as their registration. - public mutating func onConnect(execute function: @escaping (Database) throws -> Void) { - if let old = _databaseDidConnect { - _databaseDidConnect = { db in - try old(db) - try function(db) - } - } else { - _databaseDidConnect = function - } - } - - func databaseDidConnect(_ db: Database) throws { - try _prepareDatabase?(db) - try _databaseDidConnect?(db) - } + public var prepareDatabase: ((Database) throws -> Void)? // MARK: - Transactions diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 041321dfe..4ed883cb4 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -219,7 +219,7 @@ extension Database { #endif // Last step before we can start accessing the database. - try configuration.databaseDidConnect(self) + try configuration.prepareDatabase?(self) try validateFormat() configuration.SQLiteConnectionDidOpen?() @@ -960,10 +960,10 @@ extension Database { /// Sets the passphrase used to crypt and decrypt an SQLCipher database. /// - /// Call this method from Configuration.onConnect, as in the example below: + /// Call this method from Configuration.prepareDatabase, as in the example below: /// /// var config = Configuration() - /// config.onConnect { db in + /// config.prepareDatabase = { db in /// try db.usePassphrase("secret") /// } public func usePassphrase(_ passphrase: String) throws { diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift index d4e9487cc..1c6c41220 100644 --- a/GRDB/Fixit/GRDB-4.0.swift +++ b/GRDB/Fixit/GRDB-4.0.swift @@ -257,13 +257,13 @@ extension ValueObservation { } extension Configuration { - @available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.onConnect instead.") + @available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.prepareDatabase instead.") public var cipherPageSize: Int { get { preconditionFailure() } set { preconditionFailure() } } - @available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.onConnect instead.") + @available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.prepareDatabase instead.") public var kdfIterations: Int { get { preconditionFailure() } set { preconditionFailure() } diff --git a/TODO.md b/TODO.md index 46bc7048c..19c8e5636 100644 --- a/TODO.md +++ b/TODO.md @@ -41,15 +41,10 @@ players.update(...) // Runs the expected UPDATE statement ``` - [ ] Database.usePassphrase(_:) - - [ ] In order to allow SQLCipher tests to run all tests in an encrypted database, we need to make it possible to register several independent preparation blocks: - - [X] Deprecate DatabaseConfiguration.prepareDatabase - - [X] Introduce DatabaseConfiguration.onConnect { ... } as a replacement for DatabaseConfiguration.prepareDatabase - - [ ] Consider introducing DatabaseConfiguration.onDisconnect { ... } - - [ ] Deprecate change(passphrase:), and provide a static function instead + - [ ] Deprecate change(passphrase:), and provide an alternative solution - [X] Introduce Database.usePassphrase(_:). - [X] Make Database.usePassphrase(_:) a no-op if DatabaseConfiguration._passphrase is not nil, as support for the deprecated change(passphrase:). - [X] Deprecate DatabaseConfiguration.passphrase - - [ ] Remove SQLiteConnectionDidOpen and ## Unsure if necessary diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 3c1286714..d65fa8499 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -6,43 +6,7 @@ import XCTest #endif class DatabaseConfigurationTests: GRDBTestCase { - func testOnConnect() throws { - // onConnect is called when connection opens - var connectionCount = 0 - var configuration = Configuration() - configuration.onConnect { 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) - } - - func testMultipleOnConnect() throws { - // onConnect can be called multiple times. Order is deterministic. - var events: [Int] = [] - var configuration = Configuration() - configuration.onConnect { db in - events.append(1) - } - configuration.onConnect { db in - events.append(2) - } - - _ = DatabaseQueue(configuration: configuration) - XCTAssertEqual(events, [1, 2]) - } - - func testDeprecatedPrepareDatabase() throws { + func testPrepareDatabase() throws { // prepareDatabase is called when connection opens var connectionCount = 0 var configuration = Configuration() @@ -62,22 +26,4 @@ class DatabaseConfigurationTests: GRDBTestCase { try pool.read { _ in } XCTAssertEqual(connectionCount, 4) } - - func testDeprecatedPrepareDatabaseIsCalledBeforeOnConnect() throws { - // prepareDatabase is called before onConnect functions - var events: [Int] = [] - var configuration = Configuration() - configuration.onConnect { db in - events.append(2) - } - configuration.prepareDatabase = { db in - events.append(1) - } - configuration.onConnect { db in - events.append(3) - } - - _ = DatabaseQueue(configuration: configuration) - XCTAssertEqual(events, [1, 2, 3]) - } } diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 56bb37cb5..ca0871e91 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -7,7 +7,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabaseQueueWithPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -19,7 +19,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -32,7 +32,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabaseQueueWithoutPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -56,7 +56,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -68,7 +68,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("wrong") } do { @@ -84,7 +84,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -96,7 +96,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -111,7 +111,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("newSecret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -124,7 +124,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -136,7 +136,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -149,7 +149,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithoutPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -173,7 +173,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithWrongPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -185,7 +185,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("wrong") } do { @@ -201,7 +201,7 @@ class EncryptionTests: GRDBTestCase { func testDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -213,7 +213,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -229,7 +229,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("newSecret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -242,7 +242,7 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -254,7 +254,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -267,7 +267,7 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithoutPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -291,7 +291,7 @@ class EncryptionTests: GRDBTestCase { func testDatabasePoolWithPassphraseToDatabasePoolWithWrongPassphrase() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -303,7 +303,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("wrong") } do { @@ -320,7 +320,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -332,7 +332,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -348,7 +348,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("newSecret") } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) @@ -370,7 +370,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) @@ -404,7 +404,7 @@ class EncryptionTests: GRDBTestCase { func testCipherPageSize() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA cipher_page_size = 8192") } @@ -417,7 +417,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA cipher_page_size = 4096") } @@ -439,7 +439,7 @@ class EncryptionTests: GRDBTestCase { func testCipherKDFIterations() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA kdf_iter = 128000") } @@ -452,7 +452,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA kdf_iter = 128000") } @@ -474,7 +474,7 @@ class EncryptionTests: GRDBTestCase { func testCipherWithMismatchedKDFIterations() throws { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA kdf_iter = 128000") } @@ -494,7 +494,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA kdf_iter = 64000") } @@ -524,7 +524,7 @@ class EncryptionTests: GRDBTestCase { } var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } do { @@ -546,7 +546,7 @@ class EncryptionTests: GRDBTestCase { do { var config = Configuration() - config.onConnect { db in + config.prepareDatabase = { db in try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "encrypted.sqlite", configuration: config) @@ -567,7 +567,7 @@ class EncryptionTests: GRDBTestCase { let testBundle = Bundle(for: type(of: self)) let path = testBundle.url(forResource: "db", withExtension: "SQLCipher3")!.path var configuration = Configuration() - configuration.onConnect { db in + configuration.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA cipher_compatibility = 3") } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 093899c0c..a38cb5300 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -118,7 +118,7 @@ class GRDBTestCase: XCTestCase { #if GRDBCIPHER_USE_ENCRYPTION // Encrypt all databases by default. - dbConfiguration.onConnect { db in + dbConfiguration.prepareDatabase = { db in try db.usePassphrase("secret") } #endif From 1d71b9f311e073e524c8e6262884a15d2f3ab83b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Sep 2019 05:50:35 +0200 Subject: [PATCH 19/45] Update testPrepareDatabase for snapshots --- Tests/GRDBTests/DatabaseConfigurationTests.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index d65fa8499..b49c9a447 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -25,5 +25,8 @@ class DatabaseConfigurationTests: GRDBTestCase { try pool.read { _ in } XCTAssertEqual(connectionCount, 4) + + try pool.makeSnapshot().read { _ in } + XCTAssertEqual(connectionCount, 5) } } From 6fc7794e646c3a632d15652c397f1a240eee0c82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Sep 2019 06:07:36 +0200 Subject: [PATCH 20/45] Restore testDeprecatedPassphrase --- Tests/GRDBTests/EncryptionTests.swift | 64 +++++++++++++-------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index ca0871e91..20021d0b1 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -586,37 +586,37 @@ class EncryptionTests: GRDBTestCase { } } -// 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 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") + } + } + } } #endif From b9e2f3572859c553990a5bc6de4c947a4617aee9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Sep 2019 09:05:37 +0200 Subject: [PATCH 21/45] Deprecate change(passphrase:), and provide an alternative solution --- GRDB/Core/Database.swift | 3 +- GRDB/Core/DatabasePool.swift | 14 ++- GRDB/Core/DatabaseQueue.swift | 3 +- TODO.md | 2 +- Tests/GRDBTests/EncryptionTests.swift | 156 +++++++++++++++++++++++++- 5 files changed, 169 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 4ed883cb4..c03ed2e78 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -993,7 +993,8 @@ extension Database { } } - func change(passphrase: String) throws { + /// 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 diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e17db9eef..1ab665c6a 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -242,9 +242,10 @@ 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.barrier { - try writer.sync { try $0.change(passphrase: passphrase) } + try writer.sync { try $0.changePassphrase(passphrase) } readerPool.removeAll() readerConfig._passphrase = passphrase } @@ -596,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? { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 791a2f132..fd9ae3f35 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -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 diff --git a/TODO.md b/TODO.md index 19c8e5636..f7a658991 100644 --- a/TODO.md +++ b/TODO.md @@ -41,7 +41,7 @@ players.update(...) // Runs the expected UPDATE statement ``` - [ ] Database.usePassphrase(_:) - - [ ] Deprecate change(passphrase:), and provide an alternative solution + - [X] Deprecate change(passphrase:), and provide an alternative solution - [X] Introduce Database.usePassphrase(_:). - [X] Make Database.usePassphrase(_:) a no-op if DatabaseConfiguration._passphrase is not nil, as support for the deprecated change(passphrase:). - [X] Deprecate DatabaseConfiguration.passphrase diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 20021d0b1..3746374e4 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -100,7 +100,12 @@ class EncryptionTests: GRDBTestCase { try db.usePassphrase("secret") } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.change(passphrase: "newSecret") + 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)") } @@ -212,12 +217,20 @@ class EncryptionTests: GRDBTestCase { } do { + var passphrase = "secret" var config = Configuration() config.prepareDatabase = { db in - try db.usePassphrase("secret") + try db.usePassphrase(passphrase) } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.change(passphrase: "newSecret") + 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) @@ -331,12 +344,20 @@ class EncryptionTests: GRDBTestCase { } do { + var passphrase = "secret" var config = Configuration() config.prepareDatabase = { db in - try db.usePassphrase("secret") + try db.usePassphrase(passphrase) } let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.change(passphrase: "newSecret") + 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) @@ -586,6 +607,8 @@ class EncryptionTests: GRDBTestCase { } } + // MARK: - Deprecated + func testDeprecatedPassphrase() throws { do { var config = Configuration() @@ -618,5 +641,128 @@ class EncryptionTests: GRDBTestCase { } } } + + 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 From e6bc1c40fe374b79bd6ae329fcbd1fd8fb6b7327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 08:55:57 +0200 Subject: [PATCH 22/45] CHANGELOG --- CHANGELOG.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 879a4f802..125db6a6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,10 +56,38 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release -**New** +### 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 +### API Diff + +```diff + class DatabaseQueue { ++ @available(*, deprecated) + func change(passphrase: String) throws + } + + class DatabasePool { ++ func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T ++ func invalidateReadOnlyConnections() + ++ @available(*, deprecated) + func change(passphrase: String) throws + } + + class Database { ++ func usePassphrase(_ passphrase: String) throws ++ func changePassphrase(_ passphrase: String) throws + } + + struct Configuration { ++ @available(*, deprecated) + var passphrase: String? { + } +``` + ## 4.3.0 From 55d4a9c029720ba5641d57fc781c0d35cbd3ffd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 08:56:16 +0200 Subject: [PATCH 23/45] Test for attempting several passphrases --- Tests/GRDBTests/EncryptionTests.swift | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 3746374e4..20cebe7ba 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -81,6 +81,35 @@ class EncryptionTests: GRDBTestCase { } } + func testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphraseAndRetry() 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 + do { + try db.usePassphrase("wrong") + } catch let error as DatabaseError where error.resultCode == .SQLITE_NOTADB { + 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) + } + } + } + func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws { do { var config = Configuration() From 1f48405b5cf02d916e32a32c5c5166f3c93fe10f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 08:56:41 +0200 Subject: [PATCH 24/45] Rewrite passphrase documentation (WIP) --- README.md | 130 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 103 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 9b31beb03..893708a8d 100644 --- a/README.md +++ b/README.md @@ -7338,36 +7338,107 @@ 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) +- [Encrypting a Clear-Text Database](#encrypting-a-clear-text-database) +- [Attempting Several Passphrases](#attempting-several-passphrases) +- [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" +configuration.prepareDatabase = { db in + try db.usePassphrase("secret") +} let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) ``` -**You can change the passphrase** of an already encrypted database: +After you have set the passphrase, you can perform other [SQLCipher configuration steps](https://www.zetetic.net/sqlcipher/sqlcipher-api/) that must happen very early in the database lifetime. For example: ```swift -try dbQueue.change(passphrase: "newSecret") +var configuration = Configuration() +configuration.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: "...", configuration: configuration) ``` +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 configuration = Configuration() +configuration.prepareDatabase = { db in + try db.usePassphrase("secret") + 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. + + +### Changing the Passphrase of an Encrypted Database + +**You can change the passphrase** of an already encrypted database. + +The technique to do so is not the same, depending on whether you are using a [database queue](#database-queues) or a [database pool](#database-pools). + +For database queues, first open the database with the old passphrase, and then apply the new passphrase: + +```swift +// 1. Open the database queue +var configuration = Configuration() +configuration.prepareDatabase = { db in + try db.usePassphrase("oldSecret") +} +let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) + +// 2. Later on, change the passphrase +try dbQueue.write { db in + try db.changePassphrase("newSecret") +} + +// 3. Keep using the database queue with the new passphrase +try dbQueue.write { ... } +try dbQueue.read { ... } +``` + +For database pools, it is a little bit more complicated. This is because pools create SQLite connections on demand. Your application must provide a storage for the passphrase, ready to be queried whenever a new SQLite connection should be created. This "storage" can be, for example, the system keychain. + +In the sample code below, we assume the presence of two functions provided by the application: `loadPassphrase()` and `savePassphrase(_:)`. The first loads the passphrase, and the second stores a new passphrase and makes it available to future calls to `loadPassphrase()`: + +```swift +// 1. Open the database pool +var config = Configuration() +config.prepareDatabase = { db in + let passphrase = try loadPassphrase() + try db.usePassphrase(passphrase) +} +let dbPool = try DatabasePool(path: ..., configuration: config) + +// 2. Later on, change the passphrase +try dbPool.barrierWriteWithoutTransaction { db in + let newPassphrase = "newSecret" + try savePassphrase(newPassphrase) + try db.changePassphrase(newPassphrase) + dbPool.invalidateReadOnlyConnections() +} + +// 3. Keep using the database pool with the new passphrase +try dbPool.write { ... } +try dbPool.read { ... } +``` + + +### Encrypting a Clear-Text 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: @@ -7390,21 +7461,26 @@ try clearDBQueue.inDatabase { db in // Now the copy is done, and the clear-text database can be deleted. ``` -## Advanced configuration options for SQLCipher +### Attempting Several Passphrases -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: +TODO. Context: synchronizing the passphrase in the keychain, and the passphrase used by the database is tricky: one saving operation may succeed, and the other fail. It is possible that one has to try *two* passphrases: ```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") +var config = Configuration() +config.prepareDatabase = { db in + do { + try db.usePassphrase(passphrase1) + } catch let error as DatabaseError where error.resultCode == .SQLITE_NOTADB { + try db.usePassphrase(passphrase2) + } } -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. + +### Security Considerations + +- TODO: Connections can be used after passphrase has turned unavailable +- TODO: Advanced passphrase protection (use cases for the raw C SQLCioher functions) ## Backup From d4928eff9998909dca602d567fb04ba75b49d5ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 09:07:14 +0200 Subject: [PATCH 25/45] Test that prepareDatabase errors are rethrown --- .../DatabaseConfigurationTests.swift | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index b49c9a447..d9ab79d88 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -29,4 +29,47 @@ class DatabaseConfigurationTests: GRDBTestCase { 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 { } + } + } } From 8150dda951094abe69864c7f1b45d4a4aceb81bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 09:10:02 +0200 Subject: [PATCH 26/45] Passphrase documentation (WIP) --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 893708a8d..bff2a692f 100644 --- a/README.md +++ b/README.md @@ -7418,7 +7418,7 @@ In the sample code below, we assume the presence of two functions provided by th // 1. Open the database pool var config = Configuration() config.prepareDatabase = { db in - let passphrase = try loadPassphrase() + let passphrase = loadPassphrase() try db.usePassphrase(passphrase) } let dbPool = try DatabasePool(path: ..., configuration: config) @@ -7426,8 +7426,8 @@ let dbPool = try DatabasePool(path: ..., configuration: config) // 2. Later on, change the passphrase try dbPool.barrierWriteWithoutTransaction { db in let newPassphrase = "newSecret" - try savePassphrase(newPassphrase) try db.changePassphrase(newPassphrase) + savePassphrase(newPassphrase) dbPool.invalidateReadOnlyConnections() } @@ -7436,6 +7436,10 @@ try dbPool.write { ... } try dbPool.read { ... } ``` +TODO: Explain that if the `loadPassphrase` function throws an error, it is rethrown. + +TODO: Explain that if the `savePassphrase` function may throw an error, then you have to take in account the risk of passphrase desynchronization. You may have to attempt *several* passphrases (see below). + ### Encrypting a Clear-Text Database From f2198f5af7de711b62569418854aee01846c22c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 09:11:52 +0200 Subject: [PATCH 27/45] Passphrase documentation (WIP) --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index bff2a692f..f51ad0747 100644 --- a/README.md +++ b/README.md @@ -7436,6 +7436,8 @@ try dbPool.write { ... } try dbPool.read { ... } ``` +TODO: Explain that database snapshots are not managed and shold be invalidated. + TODO: Explain that if the `loadPassphrase` function throws an error, it is rethrown. TODO: Explain that if the `savePassphrase` function may throw an error, then you have to take in account the risk of passphrase desynchronization. You may have to attempt *several* passphrases (see below). From 9a69dbd8a1c22e5fc689f710262ef5c96ccdba92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Sep 2019 13:26:16 +0200 Subject: [PATCH 28/45] Remove testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphraseAndRetry --- Tests/GRDBTests/EncryptionTests.swift | 29 --------------------------- 1 file changed, 29 deletions(-) diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 20cebe7ba..59cf49ac2 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -80,35 +80,6 @@ class EncryptionTests: GRDBTestCase { } } } - - func testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphraseAndRetry() 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 - do { - try db.usePassphrase("wrong") - } catch let error as DatabaseError where error.resultCode == .SQLITE_NOTADB { - 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) - } - } - } func testDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws { do { From 7b3275ce45e53e62dddafeb93a1dca7fbbb63745 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 08:54:06 +0200 Subject: [PATCH 29/45] Make lastErrorCode and lastErrorMessage public --- GRDB/Core/Database.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c03ed2e78..bb4db1c17 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -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? From c2e68d95febf515f78ef69713200c1afab9b3a4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 08:54:22 +0200 Subject: [PATCH 30/45] Passphrase documentation --- README.md | 190 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 106 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index f51ad0747..fb2aa4561 100644 --- a/README.md +++ b/README.md @@ -7340,8 +7340,7 @@ pod 'SQLCipher', '~> 3.4' - [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) -- [Encrypting a Clear-Text Database](#encrypting-a-clear-text-database) -- [Attempting Several Passphrases](#attempting-several-passphrases) +- [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database) - [Security Considerations](#security-considerations) @@ -7350,35 +7349,35 @@ pod 'SQLCipher', '~> 3.4' **You create and open an encrypted database** by providing a passphrase to your [database connection](#database-connections): ```swift -var configuration = Configuration() -configuration.prepareDatabase = { db in +var config = Configuration() +config.prepareDatabase = { db in try db.usePassphrase("secret") } -let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` -After you have set the passphrase, you can perform other [SQLCipher configuration steps](https://www.zetetic.net/sqlcipher/sqlcipher-api/) that must happen very early in the database lifetime. For example: +It is also in the database preparation function 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 -var configuration = Configuration() -configuration.prepareDatabase = { db in +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: "...", configuration: configuration) +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 configuration = Configuration() -configuration.prepareDatabase = { db in +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: configuration) +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. @@ -7388,105 +7387,128 @@ See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher- **You can change the passphrase** of an already encrypted database. -The technique to do so is not the same, depending on whether you are using a [database queue](#database-queues) or a [database pool](#database-pools). - -For database queues, first open the database with the old passphrase, and then apply the new passphrase: +When you use a [database queue](#database-queues), open the database with the old passphrase, and then apply the new passphrase: ```swift -// 1. Open the database queue -var configuration = Configuration() -configuration.prepareDatabase = { db in - try db.usePassphrase("oldSecret") -} -let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) - -// 2. Later on, change the passphrase try dbQueue.write { db in try db.changePassphrase("newSecret") } - -// 3. Keep using the database queue with the new passphrase -try dbQueue.write { ... } -try dbQueue.read { ... } ``` -For database pools, it is a little bit more complicated. This is because pools create SQLite connections on demand. Your application must provide a storage for the passphrase, ready to be queried whenever a new SQLite connection should be created. This "storage" can be, for example, the system keychain. - -In the sample code below, we assume the presence of two functions provided by the application: `loadPassphrase()` and `savePassphrase(_:)`. The first loads the passphrase, and the second stores a new passphrase and makes it available to future calls to `loadPassphrase()`: +When you use a [database pool](#database-pools), make sure that no concurrent read can happen during the passphrase change with the `barrierWriteWithoutTransaction` method, and that all future reads open a new database connection with the `invalidateReadOnlyConnections` method: ```swift -// 1. Open the database pool -var config = Configuration() -config.prepareDatabase = { db in - let passphrase = loadPassphrase() - try db.usePassphrase(passphrase) -} -let dbPool = try DatabasePool(path: ..., configuration: config) - -// 2. Later on, change the passphrase try dbPool.barrierWriteWithoutTransaction { db in - let newPassphrase = "newSecret" - try db.changePassphrase(newPassphrase) - savePassphrase(newPassphrase) + try db.changePassphrase("newSecret") dbPool.invalidateReadOnlyConnections() } - -// 3. Keep using the database pool with the new passphrase -try dbPool.write { ... } -try dbPool.read { ... } ``` -TODO: Explain that database snapshots are not managed and shold be invalidated. - -TODO: Explain that if the `loadPassphrase` function throws an error, it is rethrown. - -TODO: Explain that if the `savePassphrase` function may throw an error, then you have to take in account the risk of passphrase desynchronization. You may have to attempt *several* passphrases (see below). +> :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. +> +> :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). -### Encrypting a Clear-Text 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) - -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") -} - -// Now the copy is done, and the clear-text database can be deleted. -``` - -### Attempting Several Passphrases - -TODO. Context: synchronizing the passphrase in the keychain, and the passphrase used by the database is tricky: one saving operation may succeed, and the other fail. It is possible that one has to try *two* passphrases: - -```swift +// The new encrypted database, at some distinct location: var config = Configuration() config.prepareDatabase = { db in - do { - try db.usePassphrase(passphrase1) - } catch let error as DatabaseError where error.resultCode == .SQLITE_NOTADB { - try db.usePassphrase(passphrase2) - } + try db.usePassphrase("secret") } +let newDBQueue = try DatabaseQueue(path: "/path/to/new.db", configuration: config) + +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 export is completed, and the existing database can be deleted. ``` ### Security Considerations -- TODO: Connections can be used after passphrase has turned unavailable -- TODO: Advanced passphrase protection (use cases for the raw C SQLCioher functions) +#### Managing the lifetime of 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: 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 is using the [`kSecAttrAccessible`](https://developer.apple.com/documentation/security/ksecattraccessible) attribute. + +```swift +var config = Configuration() +config.prepareDatabase = { db in + let passphrase = try loadPassphraseFromSystemKeychain() + try db.usePassphrase(passphrase) +} +``` + +Such protection prevents GRDB from creating SQLite connections when the passphrase is not available: + +```swift +// 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 { ... } +``` + +Those eventual database pool failures are not predictable, because pools maintain a pool of long-lived SQLite connection(s). Some database accesses will use those existing connections, and succeed. Some other database accesses will fail, as soon as the pool wants to open a new connection. + +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. + +Application that want to prevent any database access when the passphrase is unavailable are responsible for destroying their instances of database queue or pool when the passphrase becomes unavailable. ## Backup @@ -8782,10 +8804,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): From cc7d19d92567c6c71ba80ba474db7df5fc72afe6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:24:25 +0200 Subject: [PATCH 31/45] Apply wording by @michaelkirk-signal --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fb2aa4561..425f8cf7e 100644 --- a/README.md +++ b/README.md @@ -7395,7 +7395,7 @@ try dbQueue.write { db in } ``` -When you use a [database pool](#database-pools), make sure that no concurrent read can happen during the passphrase change with the `barrierWriteWithoutTransaction` method, and that all future reads open a new database connection with the `invalidateReadOnlyConnections` method: +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 From cb9323480c1abc301a068c22ae0101be656e2d74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:31:32 +0200 Subject: [PATCH 32/45] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 425f8cf7e..7ae23e213 100644 --- a/README.md +++ b/README.md @@ -7474,7 +7474,7 @@ 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 is using the [`kSecAttrAccessible`](https://developer.apple.com/documentation/security/ksecattraccessible) attribute. +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. ```swift var config = Configuration() From ad9b32f9a2e458f08269ca745b1e74bfcff0132a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:35:52 +0200 Subject: [PATCH 33/45] Fix ambiguous wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ae23e213..7125e4e65 100644 --- a/README.md +++ b/README.md @@ -7504,7 +7504,7 @@ try dbPool.read { ... } try dbPool.write { ... } ``` -Those eventual database pool failures are not predictable, because pools maintain a pool of long-lived SQLite connection(s). Some database accesses will use those existing connections, and succeed. Some other database accesses will fail, as soon as the pool wants to open a new connection. +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. From 8e764aadd20cbb73fc49084afb113932c94043ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:36:53 +0200 Subject: [PATCH 34/45] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7125e4e65..e0b230929 100644 --- a/README.md +++ b/README.md @@ -7508,7 +7508,7 @@ Because DatabasePool maintains a pool of long-lived SQLite connections, some dat 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. -Application that want to prevent any database access when the passphrase is unavailable are responsible for destroying their instances of database queue or pool when the passphrase becomes unavailable. +Applications that want to prevent any database access when the passphrase is unavailable are responsible for destroying their instances of database queue or pool when the passphrase becomes unavailable. ## Backup From 32842c22f0fc9454aff972f7c2c2e9d1eb87f463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:38:37 +0200 Subject: [PATCH 35/45] Wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e0b230929..949ad33dd 100644 --- a/README.md +++ b/README.md @@ -7356,7 +7356,7 @@ config.prepareDatabase = { db in let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` -It is also in the database preparation function 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: +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 var config = Configuration() From a1c96f909333e81909e1cfd06b335c42cc1147ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:46:44 +0200 Subject: [PATCH 36/45] Another suggestion by @michaelkirk-signal --- README.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 949ad33dd..094e2ec28 100644 --- a/README.md +++ b/README.md @@ -7404,10 +7404,26 @@ try dbPool.barrierWriteWithoutTransaction { db in } ``` -> :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. +> :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). From bfa1689d7d3237775cb7c754bf5aaa50126111ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:49:47 +0200 Subject: [PATCH 37/45] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 094e2ec28..143e6190c 100644 --- a/README.md +++ b/README.md @@ -7395,7 +7395,7 @@ try dbQueue.write { db in } ``` -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: +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 From 75f3540b8f39a0282664910d6c3710acdc21a3e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:50:16 +0200 Subject: [PATCH 38/45] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 143e6190c..806bdd686 100644 --- a/README.md +++ b/README.md @@ -7395,7 +7395,7 @@ try dbQueue.write { db in } ``` -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: +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 From 4ba199f0aac375baef4970fcf0c8d595882bae3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 18:53:11 +0200 Subject: [PATCH 39/45] Organization --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 806bdd686..11786bef1 100644 --- a/README.md +++ b/README.md @@ -7492,17 +7492,15 @@ let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) 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) } -``` -Such protection prevents GRDB from creating SQLite connections when the passphrase is not available: - -```swift // Success if and only if the passphrase is available let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` From 6285a599267944b503e8d9ee8ff4ff517ba6f63f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 19:09:32 +0200 Subject: [PATCH 40/45] Fix sample code --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 11786bef1..a2f18cd89 100644 --- a/README.md +++ b/README.md @@ -7482,7 +7482,9 @@ config.prepareDatabase = { db in let code = sqlite3_key(db.sqliteConnection, /* passphrase bytes */) ... // Carefully dispose passphrase bytes guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: db.lastErrorMessage) + throw DatabaseError( + resultCode: ResultCode(rawValue: code), + message: db.lastErrorMessage) } } let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) From 642089f41ac7f10c985fa0d9219eb7ed6e568aa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Sep 2019 19:16:14 +0200 Subject: [PATCH 41/45] Suggest using Data Protection --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a2f18cd89..8dfcc143a 100644 --- a/README.md +++ b/README.md @@ -7524,7 +7524,7 @@ Because DatabasePool maintains a pool of long-lived SQLite connections, some dat 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 that want to prevent any database access when the passphrase is unavailable are responsible for destroying their instances of database queue or pool when the passphrase becomes 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 From 5c125fae8b90687dc1b06db40ff68378d15be612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 5 Sep 2019 13:28:19 +0200 Subject: [PATCH 42/45] Add a "Managing the lifetime of the passphrase string" security consideration --- README.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8dfcc143a..e90b34548 100644 --- a/README.md +++ b/README.md @@ -7464,7 +7464,30 @@ try existingDBQueue.inDatabase { db in ### Security Considerations -#### Managing the lifetime of passphrase bytes +#### 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 +// 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) +} +``` + +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. From 3ff94c76078fe156b1d7fb696997257e0792cc5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 6 Sep 2019 07:44:10 +0200 Subject: [PATCH 43/45] CHANGELOG --- CHANGELOG.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 125db6a6c..4d0ab7102 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#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 ```diff @@ -80,11 +88,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: class Database { + func usePassphrase(_ passphrase: String) throws + func changePassphrase(_ passphrase: String) throws ++ var lastErrorCode: ResultCode ++ var lastErrorMessage: String? } struct Configuration { + @available(*, deprecated) - var passphrase: String? { + var passphrase: String? } ``` From 036178a55a62fdb9b6c572506c88bc5ae984b9f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 6 Sep 2019 07:52:18 +0200 Subject: [PATCH 44/45] CHANGELOG --- CHANGELOG.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d0ab7102..84feb0bc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,8 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex ### API Diff +**Deprecations** + ```diff class DatabaseQueue { + @available(*, deprecated) @@ -78,24 +80,30 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex } class DatabasePool { -+ func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T -+ func invalidateReadOnlyConnections() - + @available(*, deprecated) func change(passphrase: String) throws } + struct Configuration { ++ @available(*, deprecated) + var passphrase: String? + } +``` + +**New Methods** + +```diff + class DatabasePool { ++ func barrierWriteWithoutTransaction(_ 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? } - - struct Configuration { -+ @available(*, deprecated) - var passphrase: String? - } ``` From 254f3760b4b480a8fc06da55196576fd3b1042be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 6 Sep 2019 08:03:43 +0200 Subject: [PATCH 45/45] v4.4.0 --- CHANGELOG.md | 10 ++++++ Documentation/CustomSQLiteBuilds.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++-- README.md | 52 ++++++++++++++--------------- Support/Info.plist | 2 +- TODO.md | 5 --- 7 files changed, 42 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 84feb0bc1..7d0622365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,14 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. + #### 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) @@ -54,7 +57,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [0.110.0](#01100), ... + + +## 4.4.0 + +Released September 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.3.0...v4.4.0) + ### New diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 254b7d597..2d7991381 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -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 ```` diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 84a4ab8f2..ad71b7afa 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -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.' diff --git a/Makefile b/Makefile index 5923a7a70..8173db078 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index e90b34548..732313930 100644 --- a/README.md +++ b/README.md @@ -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+ • 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 @@ -8312,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: @@ -8566,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) diff --git a/Support/Info.plist b/Support/Info.plist index 8bf0cf938..e60763efb 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.3.0 + 4.4.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index f7a658991..0e03453df 100644 --- a/TODO.md +++ b/TODO.md @@ -40,11 +40,6 @@ let players = Player.filter(...) // Returns a request that filters on column A or column B depending on the argument players.update(...) // Runs the expected UPDATE statement ``` -- [ ] Database.usePassphrase(_:) - - [X] Deprecate change(passphrase:), and provide an alternative solution - - [X] Introduce Database.usePassphrase(_:). - - [X] Make Database.usePassphrase(_:) a no-op if DatabaseConfiguration._passphrase is not nil, as support for the deprecated change(passphrase:). - - [X] Deprecate DatabaseConfiguration.passphrase ## Unsure if necessary