Merge branch 'development' into dev/unappliedMigrations

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Gwendal Roué committed 2020-02-29 14:46:50 +01:00
commit 9f46f34d16
17 files changed
+486 -306

No files matched your search

+1
View File
@@ -67,6 +67,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again
- [#710](https://github.com/groue/GRDB.swift/pull/710): Check if all migrations have been applied
- [#712](https://github.com/groue/GRDB.swift/pull/712) by [@pakko972](https://github.com/pakko972): Automatic iOS memory management
### Breaking Change
+1 -1
View File
@@ -2380,7 +2380,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides.
**GRDB**
Copyright (C) 2019 Gwendal Roué
Copyright (C) 2015-2020 Gwendal Roué
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
@@ -18,9 +18,5 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management
dbQueue.setupMemoryManagement(in: application)
}
}
@@ -35,7 +35,7 @@ try dbQueue.inDatabase { db in
}
// Define the Player `Codable` that is a `FetchableRecord` and `MutablePersistableRecord`.
// Define the Player codable record type
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64
var name: String
@@ -54,40 +54,33 @@ struct Player: Codable, FetchableRecord, MutablePersistableRecord {
}
}
extension Player {
static func orderedById() -> QueryInterfaceRequest<Player> {
return order(Columns.id)
}
}
// This is just the container of our incoming JSON
struct PlayersToSync: Codable {
let players: [Player]
}
// Make Player identifiable
extension Player: Identifiable { }
// Synchronizes the players table with a JSON payload
func synchronizePlayers(with jsonString: String, in db: Database) throws {
struct SyncData: Decodable {
let players: [Player]
}
let jsonData = jsonString.data(using: .utf8)!
let dataToSync = try JSONDecoder().decode(PlayersToSync.self, from: jsonData)
let syncData = try JSONDecoder().decode(SyncData.self, from: jsonData)
// Sort new players to sync by id:
let playersToSync = dataToSync.players.sorted { $0.id < $1.id }
// Sort players to sync by id:
let playersToSync = syncData.players.sorted { $0.id < $1.id }
// Sort database players by id:
let players = try Player.orderedById().fetchAll(db)
let players = try Player.orderByPrimaryKey().fetchAll(db)
// Now that both lists are sorted by id, we can compare them with
// the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770).
// SortedDifference (see https://github.com/groue/SortedDifference).
//
// We'll delete, insert or update players, depending on their presence
// in either lists.
for mergeStep in sortedMerge(
for change in SortedDifference(
left: players, // Database players
right: playersToSync, // PlayersToSync players (Decoded)
leftKey: { $0.id }, // The id of a database player
rightKey: { $0.id }) // The id of a PlayersToSync player
right: playersToSync) // PlayersToSync players (Decoded)
{
switch mergeStep {
switch change {
case .left(let player):
// Delete database player without matching JSON player:
try player.delete(db)
@@ -140,3 +133,20 @@ do {
try synchronizePlayers(with: jsonString2, in: db)
}
}
do {
let jsonString3 = """
{
"players": [
{ "id": 2, "name": "Barbara", "score": 3000},
{ "id": 3, "name": "Craig", "score": 500},
{ "id": 4, "name": "Daniel", "score": 1500},
]
}
"""
print("---\nImport \(jsonString3)")
try dbQueue.inDatabase { db in
// SELECT * FROM player ORDER BY id
try synchronizePlayers(with: jsonString3, in: db)
}
}
@@ -0,0 +1,245 @@
// Copyright (C) 2020 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/// Given two sequences (left and right), this sequence tells whether elements
/// are only found on the left, on the right, or on both sides.
public struct SortedDifference<LeftSequence, RightSequence, ID>: Sequence where
LeftSequence: Sequence,
RightSequence: Sequence,
ID: Comparable
{
private let left: LeftSequence
private let right: RightSequence
private let lID: (LeftSequence.Element) -> ID
private let rID: (RightSequence.Element) -> ID
/// Given two sequences (left and right), returns a sequence which tells
/// whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both input sequences do not have to share the same element type, but
/// their elements must share a common comparable id.
///
/// For example:
///
/// // Prints:
/// // - common(Left(id: 1), Right(id: 1))
/// // - left(Left(id: 2))
/// struct Left { var id: Int }
/// struct Right { var id: Int }
/// for change in SortedDifference(
/// left: [Left(id: 1), Left(id: 2)],
/// identifiedBy: { $0.id },
/// right: [Right(id: 1)],
/// identifiedBy: { $0.id })
/// {
/// print(change)
/// }
///
/// - precondition: Both input sequences must be sorted by id.
/// - precondition: Ids must be unique in each sequences.
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
/// - leftID: A function that returns the id of a left element.
/// - rightID: A function that returns the id of a right element.
public init(
left: LeftSequence,
identifiedBy leftID: @escaping (LeftSequence.Element) -> ID,
right: RightSequence,
identifiedBy rightID: @escaping (RightSequence.Element) -> ID)
{
self.left = left
self.right = right
self.lID = leftID
self.rID = rightID
}
public func makeIterator() -> Iterator {
Iterator(
lIterator: left.makeIterator(),
rIterator: right.makeIterator(),
lID: lID,
rID: rID)
}
public struct Iterator: IteratorProtocol {
private var lIterator: LeftSequence.Iterator
private var rIterator: RightSequence.Iterator
private var lOpt: LeftSequence.Element?
private var rOpt: RightSequence.Element?
private let lID: (LeftSequence.Element) -> ID
private let rID: (RightSequence.Element) -> ID
init(
lIterator: LeftSequence.Iterator,
rIterator: RightSequence.Iterator,
lID: @escaping (LeftSequence.Element) -> ID,
rID: @escaping (RightSequence.Element) -> ID)
{
self.lIterator = lIterator
self.rIterator = rIterator
self.lID = lID
self.rID = rID
self.lOpt = self.lIterator.next()
self.rOpt = self.rIterator.next()
}
public mutating func next() -> SortedDifferenceChange<LeftSequence.Element, RightSequence.Element>? {
switch (lOpt, rOpt) {
case let (lElem?, rElem?):
let (lID, rID) = (self.lID(lElem), self.rID(rElem))
if lID > rID {
rOpt = rIterator.next()
return .right(rElem)
} else if lID == rID {
(lOpt, rOpt) = (lIterator.next(), rIterator.next())
return .common(lElem, rElem)
} else {
lOpt = lIterator.next()
return .left(lElem)
}
case let (nil, rElem?):
rOpt = rIterator.next()
return .right(rElem)
case let (lElem?, nil):
lOpt = lIterator.next()
return .left(lElem)
case (nil, nil):
return nil
}
}
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension SortedDifference where
LeftSequence.Element: Identifiable,
RightSequence.Element: Identifiable,
LeftSequence.Element.ID == ID,
RightSequence.Element.ID == ID
{
/// Given two sequences (left and right), returns a sequence which tells
/// whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both input sequences do not have to share the same element type, but
/// their elements must share a common comparable id.
///
/// For example:
///
/// // Prints:
/// // - common(Left(id: 1), Right(id: 1))
/// // - left(Left(id: 2))
/// struct Left: Identifiable { var id: Int }
/// struct Right: Identifiable { var id: Int }
/// for change in SortedDifference(
/// left: [Left(id: 1), Left(id: 2)],
/// right: [Right(id: 1)])
/// {
/// print(change)
/// }
///
/// - precondition: Both input sequences must be sorted by id.
/// - precondition: Ids must be unique in each sequences.
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
public init(left: LeftSequence, right: RightSequence) {
self.init(
left: left,
identifiedBy: { $0.id },
right: right,
identifiedBy: { $0.id })
}
}
extension SortedDifference where
LeftSequence.Element: Comparable,
RightSequence.Element == LeftSequence.Element,
LeftSequence.Element == ID
{
/// Given two sequences (left and right), this sequence tells whether
/// elements are only found on the left, on the right, or on both sides.
///
/// For example:
///
/// // Prints:
/// // - common(1, 1)
/// // - left(2)
/// for change in SortedDifference(left: [1, 2], right: [1]) {
/// print(change)
/// }
///
/// - precondition: Both input sequences must be sorted.
/// - precondition: Both input sequences must contain unique elements.
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
public init(left: LeftSequence, right: RightSequence) {
self.init(
left: left,
identifiedBy: { $0 },
right: right,
identifiedBy: { $0 })
}
}
/// An element of the SortedDifference sequence.
public enum SortedDifferenceChange<Left, Right> {
/// An element only found in the left sequence
case left(Left)
/// An element only found in the right sequence
case right(Right)
/// Left and right elements share a common id
case common(Left, Right)
}
extension SortedDifferenceChange: CustomStringConvertible {
public var description: String {
switch self {
case let .left(lhs):
return "left(\(String(describing: lhs)))"
case let .right(rhs):
return "right(\(String(describing: rhs)))"
case let .common(lhs, rhs):
return "common(\(String(describing: lhs)), \(String(describing: rhs)))"
}
}
}
extension SortedDifferenceChange: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .left(lhs):
return "left(\(String(reflecting: lhs)))"
case let .right(rhs):
return "right(\(String(reflecting: rhs)))"
case let .common(lhs, rhs):
return "common(\(String(reflecting: lhs)), \(String(reflecting: rhs)))"
}
}
}
extension SortedDifferenceChange: Equatable where
Left: Equatable,
Right: Equatable
{ }
@@ -1,88 +0,0 @@
/// Given two sorted sequences (left and right), this function emits "merge steps"
/// which tell whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both sequences do not have to share the same element type. Yet elements must
/// share a common comparable *key*.
///
/// Both sequences must be sorted by this key.
///
/// Keys must be unique in both sequences.
///
/// The example below compare two sequences sorted by integer representation,
/// and prints:
///
/// - Left: 1
/// - Common: 2, 2
/// - Common: 3, 3
/// - Right: 4
///
/// for mergeStep in sortedMerge(
/// left: [1,2,3],
/// right: ["2", "3", "4"],
/// leftKey: { $0 },
/// rightKey: { Int($0)! })
/// {
/// switch mergeStep {
/// case .left(let left):
/// print("- Left: \(left)")
/// case .right(let right):
/// print("- Right: \(right)")
/// case .common(let left, let right):
/// print("- Common: \(left), \(right)")
/// }
/// }
///
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
/// - leftKey: A function that returns the key of a left element.
/// - rightKey: A function that returns the key of a right element.
/// - returns: A sequence of MergeStep
public func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>(
left lSeq: LeftSequence,
right rSeq: RightSequence,
leftKey: @escaping (LeftSequence.Element) -> Key,
rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Element, RightSequence.Element>>
{
return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Element, RightSequence.Element>> in
var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator())
var (lOpt, rOpt) = (lGen.next(), rGen.next())
return AnyIterator {
switch (lOpt, rOpt) {
case (let lElem?, let rElem?):
let (lKey, rKey) = (leftKey(lElem), rightKey(rElem))
if lKey > rKey {
rOpt = rGen.next()
return .right(rElem)
} else if lKey == rKey {
(lOpt, rOpt) = (lGen.next(), rGen.next())
return .common(lElem, rElem)
} else {
lOpt = lGen.next()
return .left(lElem)
}
case (nil, let rElem?):
rOpt = rGen.next()
return .right(rElem)
case (let lElem?, nil):
lOpt = lGen.next()
return .left(lElem)
case (nil, nil):
return nil
}
}
}
}
/**
Support for sortedMerge()
*/
public enum MergeStep<LeftElement, RightElement> {
/// An element only found in the left sequence:
case left(LeftElement)
/// An element only found in the right sequence:
case right(RightElement)
/// Left and right elements share a common key:
case common(LeftElement, RightElement)
}
+15 -10
View File
@@ -24,10 +24,6 @@ public final class DatabasePool: DatabaseWriter {
var databaseSnapshotCount = LockedBox(value: 0)
#if os(iOS)
private weak var application: UIApplication?
#endif
// MARK: - Database Information
/// The path to the database.
@@ -138,10 +134,16 @@ public final class DatabasePool: DatabaseWriter {
}
setupSuspension()
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupAutomaticMemoryManagement()
#endif
}
deinit {
// Undo job done in setupMemoryManagement()
// Undo job done in setupAutomaticMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
@@ -194,8 +196,6 @@ extension DatabasePool {
///
/// This method blocks the current thread until all database accesses
/// are completed.
///
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
// Release writer memory
writer.sync { $0.releaseMemory() }
@@ -207,6 +207,12 @@ extension DatabasePool {
#if os(iOS)
// swiftlint:disable:next line_length
@available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.")
public func setupMemoryManagement(in application: UIApplication) {
// No op.
}
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
@@ -214,8 +220,7 @@ extension DatabasePool {
/// - param application: The UIApplication that will start a background
/// task to let the database pool release its memory when the application
/// enters background.
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
private func setupAutomaticMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
@@ -231,7 +236,7 @@ extension DatabasePool {
@objc
private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
guard let application = notification.object as? UIApplication else {
return
}
+15 -9
View File
@@ -7,9 +7,6 @@ import UIKit
/// A DatabaseQueue serializes access to an SQLite database.
public final class DatabaseQueue: DatabaseWriter {
private var writer: SerializedDatabase
#if os(iOS)
private weak var application: UIApplication?
#endif
// MARK: - Configuration
@@ -43,6 +40,12 @@ public final class DatabaseQueue: DatabaseWriter {
defaultLabel: "GRDB.DatabaseQueue")
setupSuspension()
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupAutomaticMemoryManagement()
#endif
}
/// Opens an in-memory SQLite database.
@@ -62,7 +65,7 @@ public final class DatabaseQueue: DatabaseWriter {
}
deinit {
// Undo job done in setupMemoryManagement()
// Undo job done in setupAutomaticMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
@@ -77,13 +80,17 @@ extension DatabaseQueue {
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
///
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
writer.sync { $0.releaseMemory() }
}
#if os(iOS)
// swiftlint:disable:next line_length
@available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.")
public func setupMemoryManagement(in application: UIApplication) {
// No op.
}
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
@@ -91,8 +98,7 @@ extension DatabaseQueue {
/// - param application: The UIApplication that will start a background
/// task to let the database queue release its memory when the application
/// enters background.
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
private func setupAutomaticMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
@@ -108,7 +114,7 @@ extension DatabaseQueue {
@objc
private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
guard let application = notification.object as? UIApplication else {
return
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (C) 2019 Gwendal Roué
// Copyright (C) 2015-2020 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (C) 2019 Gwendal Roué
Copyright (C) 2015-2020 Gwendal Roué
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+8 -1
View File
@@ -49,7 +49,14 @@ endif
TEST_ACTIONS = clean build build-for-testing test-without-building
# When adding support for an Xcode version, look for available devices with `instruments -s devices`
ifeq ($(XCODEVERSION),11.3)
ifeq ($(XCODEVERSION),11.4)
MAX_SWIFT_VERSION = 5.2
MIN_SWIFT_VERSION = 4.2
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4"
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4"
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2"
else ifeq ($(XCODEVERSION),11.3)
MAX_SWIFT_VERSION = 5.1
MIN_SWIFT_VERSION = 4.2
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.3"
+1 -6
View File
@@ -7158,12 +7158,7 @@ This method blocks the current thread until all current database accesses are co
**The iOS operating system likes applications that do not consume much memory.**
[Database queues](#database-queues) and [pools](#database-pools) can call the `releaseMemory` method for you, when application receives memory warnings, and when application enters background: call the `setupMemoryManagement` method after creating the queue or pool instance:
```
let dbQueue = try DatabaseQueue(...)
dbQueue.setupMemoryManagement(in: UIApplication.shared)
```
[Database queues](#database-queues) and [pools](#database-pools) automatically call the `releaseMemory` method when the application receives a memory warning, and when the application enters background.
## Data Protection
+1 -1
View File
@@ -21,7 +21,7 @@
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2015-2019 Gwendal Roué.</string>
<string>Copyright © 2015-2020 Gwendal Roué.</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
+1 -1
View File
@@ -23,7 +23,7 @@
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2019 Gwendal Roué. All rights reserved.</string>
<string>Copyright © 2015-2020 Gwendal Roué. All rights reserved.</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
@@ -208,54 +208,55 @@ class DatabaseConfigurationTests: GRDBTestCase {
_ = group.wait(timeout: .distantFuture)
}
func testBusyModeTimeoutTooShort() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
var configuration2 = dbQueue1.configuration
configuration2.busyMode = .timeout(0.1)
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let queue = DispatchQueue.global(priority: .default)
let group = DispatchGroup()
queue.async(group: group) {
do {
try dbQueue1.inTransaction(.exclusive) { db in
s2.signal()
queue.asyncAfter(deadline: .now() + 1) {
s1.signal()
}
_ = s1.wait(timeout: .distantFuture)
return .commit
}
} catch {
XCTFail("\(error)")
}
}
queue.async(group: group) {
do {
_ = s2.wait(timeout: .distantFuture)
try dbQueue2.inTransaction(.exclusive) { db in return .commit }
XCTFail("Expected error")
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
} catch {
XCTFail("\(error)")
}
}
_ = group.wait(timeout: .distantFuture)
}
// TODO: fix flaky test
// func testBusyModeTimeoutTooShort() throws {
// let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
// #if GRDBCIPHER_USE_ENCRYPTION
// // Work around SQLCipher bug when two connections are open to the
// // same empty database: make sure the database is not empty before
// // running this test
// try dbQueue1.inDatabase { db in
// try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
// }
// #endif
//
// var configuration2 = dbQueue1.configuration
// configuration2.busyMode = .timeout(0.1)
// let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
//
// let s1 = DispatchSemaphore(value: 0)
// let s2 = DispatchSemaphore(value: 0)
// let queue = DispatchQueue.global(priority: .default)
// let group = DispatchGroup()
//
// queue.async(group: group) {
// do {
// try dbQueue1.inTransaction(.exclusive) { db in
// s2.signal()
// queue.asyncAfter(deadline: .now() + 1) {
// s1.signal()
// }
// _ = s1.wait(timeout: .distantFuture)
// return .commit
// }
// } catch {
// XCTFail("\(error)")
// }
// }
//
// queue.async(group: group) {
// do {
// _ = s2.wait(timeout: .distantFuture)
// try dbQueue2.inTransaction(.exclusive) { db in return .commit }
// XCTFail("Expected error")
// } catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// } catch {
// XCTFail("\(error)")
// }
// }
//
// _ = group.wait(timeout: .distantFuture)
// }
// TODO: fix flaky test. It fails on Xcode 10.0, tvOS 10.0
// func testBusyModeTimeoutTooLong() throws {
@@ -45,82 +45,83 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
XCTAssertEqual(openConnectionCount, 0)
}
func testDatabasePoolReleaseMemoryClosesReaderConnections() throws {
let countQueue = DispatchQueue(label: "GRDB")
var openConnectionCount = 0
var totalOpenConnectionCount = 0
dbConfiguration.SQLiteConnectionDidOpen = {
countQueue.sync {
totalOpenConnectionCount += 1
openConnectionCount += 1
}
}
dbConfiguration.SQLiteConnectionDidClose = {
countQueue.sync {
openConnectionCount -= 1
}
}
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<2 {
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
// Block 1 Block 2 Block3
// SELECT * FROM items
// step
// >
let s1 = DispatchSemaphore(value: 0)
// SELECT * FROM items
// step
// >
let s2 = DispatchSemaphore(value: 0)
// step step
// >
let s3 = DispatchSemaphore(value: 0)
// end end releaseMemory
let block1 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(try cursor.next() != nil)
s3.signal()
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
_ = s1.wait(timeout: .distantFuture)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s2.signal()
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block3 = { () in
_ = s3.wait(timeout: .distantFuture)
dbPool.releaseMemory()
}
let blocks = [block1, block2, block3]
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes
blocks[index]()
}
// Two readers, one writer
XCTAssertEqual(totalOpenConnectionCount, 3)
// Writer is still open
XCTAssertEqual(openConnectionCount, 1)
}
// TODO: fix flaky test
// func testDatabasePoolReleaseMemoryClosesReaderConnections() throws {
// let countQueue = DispatchQueue(label: "GRDB")
// var openConnectionCount = 0
// var totalOpenConnectionCount = 0
//
// dbConfiguration.SQLiteConnectionDidOpen = {
// countQueue.sync {
// totalOpenConnectionCount += 1
// openConnectionCount += 1
// }
// }
//
// dbConfiguration.SQLiteConnectionDidClose = {
// countQueue.sync {
// openConnectionCount -= 1
// }
// }
//
// let dbPool = try makeDatabasePool()
// try dbPool.write { db in
// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
// for _ in 0..<2 {
// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
// }
// }
//
// // Block 1 Block 2 Block3
// // SELECT * FROM items
// // step
// // >
// let s1 = DispatchSemaphore(value: 0)
// // SELECT * FROM items
// // step
// // >
// let s2 = DispatchSemaphore(value: 0)
// // step step
// // >
// let s3 = DispatchSemaphore(value: 0)
// // end end releaseMemory
//
// let block1 = { () in
// try! dbPool.read { db in
// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
// XCTAssertTrue(try cursor.next() != nil)
// s1.signal()
// _ = s2.wait(timeout: .distantFuture)
// XCTAssertTrue(try cursor.next() != nil)
// s3.signal()
// XCTAssertTrue(try cursor.next() == nil)
// }
// }
// let block2 = { () in
// _ = s1.wait(timeout: .distantFuture)
// try! dbPool.read { db in
// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
// XCTAssertTrue(try cursor.next() != nil)
// s2.signal()
// XCTAssertTrue(try cursor.next() != nil)
// XCTAssertTrue(try cursor.next() == nil)
// }
// }
// let block3 = { () in
// _ = s3.wait(timeout: .distantFuture)
// dbPool.releaseMemory()
// }
// let blocks = [block1, block2, block3]
// DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes
// blocks[index]()
// }
//
// // Two readers, one writer
// XCTAssertEqual(totalOpenConnectionCount, 3)
//
// // Writer is still open
// XCTAssertEqual(openConnectionCount, 1)
// }
func testBlocksRetainConnection() throws {
let countQueue = DispatchQueue(label: "GRDB")
@@ -83,44 +83,45 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
}
}
}
func testCachedStatementsAreNotShared() throws {
// This is a regression test.
//
// If cached statements were shared between reader connections, this
// test would crash with fatal error: Database was not used on the
// correct thread.
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (1)")
}
// Block 1 Block 2
// SELECT 1 FROM items WHERE id = 1
// >
let s1 = DispatchSemaphore(value: 0)
// SELECT 1 FROM items WHERE id = 1
let block1 = { () in
try! dbPool.read { db in
let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items")
XCTAssertEqual(try Int.fetchOne(stmt)!, 1)
s1.signal()
}
}
let block2 = { () in
try! dbPool.read { db in
_ = s1.wait(timeout: .distantFuture)
let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items")
XCTAssertEqual(try Int.fetchOne(stmt)!, 1)
}
}
let blocks = [block1, block2]
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
blocks[index]()
}
}
// TODO: fix flaky test
// func testCachedStatementsAreNotShared() throws {
// // This is a regression test.
// //
// // If cached statements were shared between reader connections, this
// // test would crash with fatal error: Database was not used on the
// // correct thread.
// let dbPool = try makeDatabasePool()
// try dbPool.write { db in
// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
// try db.execute(sql: "INSERT INTO items (id) VALUES (1)")
// }
//
// // Block 1 Block 2
// // SELECT 1 FROM items WHERE id = 1
// // >
// let s1 = DispatchSemaphore(value: 0)
// // SELECT 1 FROM items WHERE id = 1
//
// let block1 = { () in
// try! dbPool.read { db in
// let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items")
// XCTAssertEqual(try Int.fetchOne(stmt)!, 1)
// s1.signal()
// }
// }
// let block2 = { () in
// try! dbPool.read { db in
// _ = s1.wait(timeout: .distantFuture)
// let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items")
// XCTAssertEqual(try Int.fetchOne(stmt)!, 1)
// }
// }
// let blocks = [block1, block2]
// DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
// blocks[index]()
// }
// }
func testCacheSnapshotIsolation() throws {
// This test checks that the schema cache follows snapshot isolation.