diff --git a/CHANGELOG.md b/CHANGELOG.md index 86f9fe9a3..1bf95822e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 4.x Releases +- `4.11.x` Releases - [4.11.0](#4110) - `4.10.x` Releases - [4.10.0](#4100) - `4.9.x` Releases - [4.9.0](#490) - `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481) @@ -67,6 +68,44 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release --> +## 4.11.0 + +Released March 2, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.10.0...v4.11.0) + +### New + +- [#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 +- [#713](https://github.com/groue/GRDB.swift/pull/713): Enhance DatabaseMigrator isolation + +### Breaking Change + +- [#709](https://github.com/groue/GRDB.swift/pull/709): Simplify DatabaseMigrator API + +Database migrations have a new behavior which is a breaking change. However, it is very unlikely to impact your application. + +In previous versions of GRDB, a foreign key violation would immediately prevent a migration from successfully complete. Now, foreign key checks are deferred until the end of each migration. This means that some migrations will change their behavior: + +```swift +// Used to fail, now succeeds +migrator.registerMigration(...) { db in + try violateForeignKeyConstraint(db) + try fixForeignKeyConstraint(db) +} + +// The catch clause is no longer called +migrator.registerMigration(...) { db in + do { + try performChanges(db) + } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT { + // Handle foreign key error + } +} +``` + +If your application happens to define migrations that are impacted by this change, please open an issue so that we find a way to restore the previous behavior. + ## 4.10.0 diff --git a/Documentation/AppGroupContainers.md b/Documentation/AppGroupContainers.md index 1a0d1d176..1ca3683a1 100644 --- a/Documentation/AppGroupContainers.md +++ b/Documentation/AppGroupContainers.md @@ -48,8 +48,10 @@ Since several processes may open the database at the same time, protect the crea private func openDatabase(at databaseURL: URL) throws -> DatabasePool { let dbPool = try DatabasePool(path: databaseURL.path) + // Perform here other database setups, such as defining // the database schema with a DatabaseMigrator. + try migrator.migrate(dbPool) return dbPool } ``` @@ -58,7 +60,8 @@ Since several processes may open the database at the same time, protect the crea ```swift /// Returns an initialized database pool at the shared location databaseURL, - /// or nil if the database was not created yet. + /// or nil if the database is not created yet, or does not have the required + /// schema version. func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? { let coordinator = NSFileCoordinator(filePresenter: nil) var coordinatorError: NSError? @@ -81,7 +84,15 @@ Since several processes may open the database at the same time, protect the crea do { var configuration = Configuration() configuration.readonly = true - return try DatabasePool(path: databaseURL.path, configuration: configuration) + let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration) + + // Check here if the database schema is correct, for example + // with a DatabaseMigrator. + if try migrator.hasCompletedMigrations(in: dbPool) { + return dbPool + } else { + return nil + } } catch { if FileManager.default.fileExists(atPath: databaseURL.path) { throw error diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 5f28de852..f95ce9c3b 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -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: diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 672c383c0..3df9947f3 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -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) } } diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift index 553c57dd8..979ebeb7b 100644 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -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 { - 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) + } +} diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift new file mode 100644 index 000000000..144b4cb64 --- /dev/null +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift @@ -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: 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? { + 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 { + /// 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 +{ } diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift deleted file mode 100644 index 3ba6899f7..000000000 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift +++ /dev/null @@ -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( - left lSeq: LeftSequence, - right rSeq: RightSequence, - leftKey: @escaping (LeftSequence.Element) -> Key, - rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence> -{ - return AnySequence { () -> AnyIterator> 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 { - /// 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) -} diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index ca51511ec..259648c60 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -152,7 +152,7 @@ Such literal expressions can be returned by Swift functions: ```swift func date(_ value: SQLExpressible) -> SQLExpression { - SQLLiteral("DATE(\(lhs.sqlExpression))").sqlExpression + SQLLiteral("DATE(\(value))").sqlExpression } // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 1b0ce9495..cef26d10a 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.10.0' + s.version = '4.11.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 6b69b7737..2b770dc67 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -10,13 +10,6 @@ extension Database { // MARK: - Database Schema - func withSchemaCache(_ schemaCache: DatabaseSchemaCache, _ block: () throws -> T) rethrows -> T { - var oldCache = self.schemaCache - defer { self.schemaCache = oldCache } - self.schemaCache = schemaCache - return try block() - } - /// Clears the database schema cache. /// /// You may need to clear the cache manually if the database schema is diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index bbe0bf3c2..0e6d18ef5 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1080,16 +1080,53 @@ public final class Database { publicStatementCache.clear() } + // MARK: - Erasing + + func erase() throws { + #if SQLITE_HAS_CODEC + // SQLCipher does not support the backup API: + // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 + // So we'll drop all database objects one after the other. + + // Prevent foreign keys from messing with drop table statements + let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")! + if foreignKeysEnabled { + try execute(sql: "PRAGMA foreign_keys = OFF") + } + + try throwingFirstError( + execute: { + // Remove all database objects, one after the other + try inTransaction { + let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" + while let row = try Row.fetchOne(self, sql: sql) { + let type: String = row["type"] + let name: String = row["name"] + try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") + } + return .commit + } + }, + finally: { + // Restore foreign keys if needed + if foreignKeysEnabled { + try execute(sql: "PRAGMA foreign_keys = ON") + } + }) + #else + try DatabaseQueue().backup(to: self) + #endif + } + // MARK: - Backup - static func backup( - from dbFrom: Database, + func backup( to dbDest: Database, afterBackupInit: (() -> Void)? = nil, afterBackupStep: (() -> Void)? = nil) throws { - guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { + guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 50653f20f..991e2f111 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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. @@ -58,7 +54,7 @@ public final class DatabasePool: DatabaseWriter { writer = try SerializedDatabase( path: path, configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabasePool", purpose: "writer") @@ -101,7 +97,7 @@ public final class DatabasePool: DatabaseWriter { let reader = try SerializedDatabase( path: path, configuration: self.readerConfiguration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabasePool", purpose: "reader.\(readerCount)") reader.sync { self.setupDatabase($0) } @@ -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 } @@ -367,9 +372,8 @@ extension DatabasePool: DatabaseReader { // See DatabasePoolTests.testReadMethodIsolationOfBlock(). try db.inTransaction(.deferred) { // Reset the schema cache before running user code in snapshot isolation - result = try db.withSchemaCache(SimpleDatabaseSchemaCache()) { - try block(db) - } + db.clearSchemaCache() + result = try block(db) return .commit } return result! @@ -415,9 +419,8 @@ extension DatabasePool: DatabaseReader { try db.beginTransaction(.deferred) // Reset the schema cache before running user code in snapshot isolation - db.withSchemaCache(SimpleDatabaseSchemaCache()) { - block(.success(db)) - } + db.clearSchemaCache() + block(.success(db)) } catch { block(.failure(error)) } @@ -459,10 +462,9 @@ extension DatabasePool: DatabaseReader { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") return try readerPool.get { reader in try reader.sync { db in - // No schema cache when snapshot isolation is not established - return try db.withSchemaCache(EmptyDatabaseSchemaCache()) { - try block(db) - } + // Reset the schema cache + db.clearSchemaCache() + return try block(db) } } } @@ -500,10 +502,9 @@ extension DatabasePool: DatabaseReader { } else { return try readerPool.get { reader in try reader.sync { db in - // No schema cache when snapshot isolation is not established - return try db.withSchemaCache(EmptyDatabaseSchemaCache()) { - try block(db) - } + // Reset the schema cache + db.clearSchemaCache() + return try block(db) } } } @@ -555,11 +556,12 @@ extension DatabasePool: DatabaseReader { // Release the writer queue isolationSemaphore.signal() - // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - // Fetch and release the future - futureResult = DatabaseResult { try block(db) } + futureResult = DatabaseResult { + // Reset the schema cache before running user code in snapshot isolation + db.clearSchemaCache() + return try block(db) + } futureSemaphore.signal() } } catch { @@ -659,10 +661,9 @@ extension DatabasePool: DatabaseReader { isolationSemaphore.signal() // Reset the schema cache before running user code in snapshot isolation - db.withSchemaCache(SimpleDatabaseSchemaCache()) { - // Fetch and release the future - block(.success(db)) - } + db.clearSchemaCache() + + block(.success(db)) } } catch { isolationSemaphore.signal() @@ -726,9 +727,12 @@ 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. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// Updates are guaranteed an exclusive access to the database. They wait + /// until all pending writes and reads are completed. They postpone all + /// other writes and reads until they are completed. /// /// This method is *not* reentrant. /// diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 99c3928a8..0c8e82819 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -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 @@ -39,10 +36,16 @@ public final class DatabaseQueue: DatabaseWriter { writer = try SerializedDatabase( path: path, configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), 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. @@ -57,12 +60,12 @@ public final class DatabaseQueue: DatabaseWriter { writer = try! SerializedDatabase( path: ":memory:", configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabaseQueue") } 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 } @@ -373,6 +379,20 @@ extension DatabaseQueue { return try writer.sync(updates) } + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// Eventual concurrent database accesses are postponed until the updates + /// are completed. + /// + /// This method is *not* reentrant. + /// + /// - 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 writer.sync(updates) + } + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e1564e258..4908ebf82 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -278,18 +278,22 @@ extension DatabaseReader { /// the backup. Those writes may, or may not, be reflected in the backup, /// but they won't trigger any error. public func backup(to writer: DatabaseWriter) throws { - try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil) + try writer.writeWithoutTransaction { dbDest in + try backup(to: dbDest) + } } - func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws { + func backup( + to dbDest: Database, + afterBackupInit: (() -> Void)? = nil, + afterBackupStep: (() -> Void)? = nil) + throws + { try read { dbFrom in - try writer.writeWithoutTransaction { dbDest in - try Database.backup( - from: dbFrom, - to: dbDest, - afterBackupInit: afterBackupInit, - afterBackupStep: afterBackupStep) - } + try dbFrom.backup( + to: dbDest, + afterBackupInit: afterBackupInit, + afterBackupStep: afterBackupStep) } } } diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 4f29cef90..dd7916ec7 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -1,24 +1,5 @@ -/// The protocol for database schema cache. -protocol DatabaseSchemaCache { - mutating func clear() - - var schemaInfo: SchemaInfo? { get set } - - func primaryKey(_ table: String) -> PrimaryKeyInfo? - mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) - - func columns(in table: String) -> [ColumnInfo]? - mutating func set(columns: [ColumnInfo], forTable table: String) - - func indexes(on table: String) -> [IndexInfo]? - mutating func set(indexes: [IndexInfo], forTable table: String) - - func foreignKeys(on table: String) -> [ForeignKeyInfo]? - mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) -} - /// A thread-unsafe database schema cache -struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { +struct DatabaseSchemaCache { var schemaInfo: SchemaInfo? private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] @@ -65,25 +46,3 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { self.foreignKeys[table] = foreignKeys } } - -/// An always empty database schema cache -struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { - func clear() { } - - var schemaInfo: SchemaInfo? { - get { return nil } - set { } - } - - func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } - func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } - - func columns(in table: String) -> [ColumnInfo]? { return nil } - func set(columns: [ColumnInfo], forTable table: String) { } - - func indexes(on table: String) -> [IndexInfo]? { return nil } - func set(indexes: [IndexInfo], forTable table: String) { } - - func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil } - func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { } -} diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index df92854f9..d5427ed6c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -22,7 +22,7 @@ public class DatabaseSnapshot: DatabaseReader { serializedDatabase = try SerializedDatabase( path: path, configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: defaultLabel, purpose: purpose) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 9d39cd503..d3ea94ec7 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -53,6 +53,19 @@ public protocol DatabaseWriter: DatabaseReader { /// - throws: The error thrown by the updates. func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// Updates are guaranteed an exclusive access to the database. They wait + /// until all pending writes and reads are completed. They postpone all + /// other writes and reads until they are completed. + /// + /// This method is *not* reentrant. + /// + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. + func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + #if compiler(>=5.0) /// Asynchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction. @@ -280,40 +293,7 @@ extension DatabaseWriter { /// - precondition: database is not accessed concurrently during the /// execution of this method. public func erase() throws { - #if SQLITE_HAS_CODEC - // SQLCipher does not support the backup API: - // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 - // So we'll drop all database objects one after the other. - try writeWithoutTransaction { db in - // Prevent foreign keys from messing with drop table statements - let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")! - if foreignKeysEnabled { - try db.execute(sql: "PRAGMA foreign_keys = OFF") - } - - try throwingFirstError( - execute: { - // Remove all database objects, one after the other - try db.inTransaction { - let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" - while let row = try Row.fetchOne(db, sql: sql) { - let type: String = row["type"] - let name: String = row["name"] - try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") - } - return .commit - } - }, - finally: { - // Restore foreign keys if needed - if foreignKeysEnabled { - try db.execute(sql: "PRAGMA foreign_keys = ON") - } - }) - } - #else - try DatabaseQueue().backup(to: self) - #endif + try writeWithoutTransaction { try $0.erase() } } // MARK: - Claiming Disk Space @@ -652,6 +632,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { return try base.writeWithoutTransaction(updates) } + /// :nodoc: + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + return try base.barrierWriteWithoutTransaction(updates) + } + #if compiler(>=5.0) /// :nodoc: public func asyncWrite( diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 14a4218f8..88d5f0f24 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -91,73 +91,34 @@ public struct DatabaseMigrator { registerMigration(Migration(identifier: identifier, migrate: migrate)) } - #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter + /// Registers a migration. /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in + /// migrator.registerMigrationWithDeferredForeignKeyCheck("createAuthors") { db in + /// try db.create(table: "author") { t in /// t.autoIncrementedPrimaryKey("id") + /// t.column("creationDate", .datetime) /// t.column("name", .text).notNull() /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") /// } /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// /// - parameters: /// - identifier: The migration identifier. /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. - /// - /// :nodoc: + @available(*, deprecated, renamed: "registerMigration(_:migrate:)") public mutating func registerMigrationWithDeferredForeignKeyCheck( _ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) + registerMigration(identifier, migrate: migrate) } - #else - @available(OSX 10.10, *) - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter - /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text).notNull() - /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") - /// } - /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigrationWithDeferredForeignKeyCheck( - _ identifier: String, - migrate: @escaping (Database) throws -> Void) - { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } - #endif /// Iterate migrations in the same order as they were registered. If a /// migration has not yet been applied, its block is executed in /// a transaction. /// - /// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where - /// migrations should apply. + /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) + /// where migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter) throws { guard let lastMigration = migrations.last else { @@ -170,55 +131,111 @@ public struct DatabaseMigrator { /// provided target. If a migration has not yet been applied, its block is /// executed in a transaction. /// - /// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where - /// migrations should apply. - /// - targetIdentifier: The identifier of a registered migration. + /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) + /// where migrations should apply. + /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { - if eraseDatabaseOnSchemaChange { - // Create a temporary witness database, on disk, just in case - // migrations would involve a lot of data. - let witness = try DatabaseQueue(path: "", configuration: writer.configuration) - - // Erase database if we detect a change in the current schema. - let (currentIdentifier, currentSchema) = try writer.writeWithoutTransaction { db -> (String?, SchemaInfo) in - try setupMigrations(db) - let identifiers = try appliedIdentifiers(db) - let currentIdentifier = migrations - .reversed() - .first { identifiers.contains($0.identifier) }? - .identifier - return try (currentIdentifier, db.schema()) - } - - if let currentIdentifier = currentIdentifier { - let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: currentIdentifier) - return try db.schema() + try writer.barrierWriteWithoutTransaction { db in + if eraseDatabaseOnSchemaChange { + // Fetch information about current database state + var info: (lastAppliedIdentifier: String, schema: SchemaInfo)? + try db.inTransaction(.deferred) { + let identifiers = try appliedIdentifiers(db) + if let lastAppliedIdentifier = migrations + .last(where: { identifiers.contains($0.identifier) })? + .identifier + { + info = try (lastAppliedIdentifier: lastAppliedIdentifier, schema: db.schema()) + } + return .commit } - if currentSchema != witnessSchema { - try writer.erase() + if let info = info { + // Create a temporary witness database (on disk, just in case + // migrations would involve a lot of data). + let witness = try DatabaseQueue(path: "", configuration: writer.configuration) + + // Grab schema of migrated witness database + let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in + try runMigrations(db, upTo: info.lastAppliedIdentifier) + return try db.schema() + } + + // Erase database if we detect a schema change + if info.schema != witnessSchema { + try db.erase() + } } } - } - - // Migrate to target schema - try writer.writeWithoutTransaction { db in - try setupMigrations(db) + + // Migrate to target schema try runMigrations(db, upTo: targetIdentifier) } } /// Returns the set of applied migration identifiers. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - parameter targetIdentifier: The identifier of a registered migration. + /// - throws: An eventual database error. public func appliedMigrations(in reader: DatabaseReader) throws -> Set { + return try reader.read(appliedIdentifiers) + } + + /// Returns true if all migrations are applied. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - throws: An eventual database error. + public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool { + guard let lastMigration = migrations.last else { + return true + } + return try hasCompletedMigrations(in: reader, through: lastMigration.identifier) + } + + /// Returns true if all migrations up to the provided target are applied, + /// and maybe further. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - parameter targetIdentifier: The identifier of a registered migration. + /// - throws: An eventual database error. + public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool { return try reader.read { db in - return try appliedIdentifiers(db) + let appliedIdentifiers = try self.appliedIdentifiers(db) + let unappliedMigrations = self.unappliedMigrations( + upTo: targetIdentifier, + appliedIdentifiers: appliedIdentifiers) + return unappliedMigrations.isEmpty } } - + /// Returns the identifier of the last migration for which all predecessors + /// have been applied. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - returns: An eventual migration identifier. + /// - throws: An eventual database error. + public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? { + return try reader.read { db in + let appliedIdentifiers = try self.appliedIdentifiers(db) + if appliedIdentifiers.isEmpty { + return nil + } + let lastAppliedIdentifier = migrations + .last { appliedIdentifiers.contains($0.identifier) }! + .identifier + let unappliedMigrations = self.unappliedMigrations( + upTo: lastAppliedIdentifier, + appliedIdentifiers: appliedIdentifiers) + if unappliedMigrations.isEmpty { + return lastAppliedIdentifier + } else { + return nil + } + } + } + // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { @@ -228,10 +245,6 @@ public struct DatabaseMigrator { migrations.append(migration) } - private func setupMigrations(_ db: Database) throws { - try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") - } - private func appliedIdentifiers(_ db: Database) throws -> Set { let tableExists = try Bool.fetchOne(db, sql: """ SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name='grdb_migrations') @@ -240,12 +253,14 @@ public struct DatabaseMigrator { return [] } return try Set(String.fetchAll(db, sql: "SELECT identifier FROM grdb_migrations")) + .intersection(migrations.map { $0.identifier }) } - private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { - var prefixMigrations: [Migration] = [] + /// Returns unapplied migration identifier, + private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: Set) -> [Migration] { + var expectedMigrations: [Migration] = [] for migration in migrations { - prefixMigrations.append(migration) + expectedMigrations.append(migration) if migration.identifier == targetIdentifier { break } @@ -253,19 +268,29 @@ public struct DatabaseMigrator { // targetIdentifier must refer to a registered migration GRDBPrecondition( - prefixMigrations.last?.identifier == targetIdentifier, + expectedMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") - // Subsequent migration must not be applied + return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) } + } + + private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { + try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") + let appliedIdentifiers = try self.appliedIdentifiers(db) - if prefixMigrations.count < migrations.count { - let nextIdentifier = migrations[prefixMigrations.count].identifier - GRDBPrecondition( - !appliedIdentifiers.contains(nextIdentifier), - "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") + + // Subsequent migration must not be applied + if let index = migrations.firstIndex(where: { $0.identifier == targetIdentifier }), + migrations[(index + 1)...].contains(where: { appliedIdentifiers.contains($0.identifier) }) + { + fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } - for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { + let unappliedMigrations = self.unappliedMigrations( + upTo: targetIdentifier, + appliedIdentifiers: appliedIdentifiers) + + for migration in unappliedMigrations { try migration.run(db) } } diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 24f44b3e0..4efcb0590 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,36 +1,27 @@ +#if SWIFT_PACKAGE +import CSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// An internal struct that defines a migration. struct Migration { let identifier: String - let disabledForeignKeyChecks: Bool let migrate: (Database) throws -> Void - #if GRDBCUSTOMSQLITE || GRDBCIPHER - init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } - #else init(identifier: String, migrate: @escaping (Database) throws -> Void) { self.identifier = identifier - self.disabledForeignKeyChecks = false self.migrate = migrate } - @available(OSX 10.10, *) - // PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } - #endif - func run(_ db: Database) throws { - if try disabledForeignKeyChecks && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) { - try runWithDisabledForeignKeys(db) + // PRAGMA foreign_key_check and SQLITE_CONSTRAINT_FOREIGNKEY were + // introduced in SQLite 3.7.16 + // http://www.sqlite.org/changes.html#version_3_7_16 + if try sqlite3_libversion_number() >= 3007016 && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) { + try runWithDeferredForeignKeysChecks(db) } else { try runWithoutDisabledForeignKeys(db) } @@ -45,7 +36,7 @@ struct Migration { } } - private func runWithDisabledForeignKeys(_ db: Database) throws { + private func runWithDeferredForeignKeysChecks(_ db: Database) throws { // Support for database alterations described at // https://www.sqlite.org/lang_altertable.html#otheralter // @@ -60,18 +51,26 @@ struct Migration { try migrate(db) try insertAppliedIdentifier(db) - // > 10. If foreign key constraints were originally enabled then run PRAGMA - // > foreign_key_check to verify that the schema change did not break any foreign key - // > constraints. - if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil { + // > 10. If foreign key constraints were originally enabled + // > then run PRAGMA foreign_key_check to verify that the + // > schema change did not break any foreign + // > key constraints. + if try db + .makeSelectStatement(sql: "PRAGMA foreign_key_check") + .makeCursor() + .isEmpty() == false + { // https://www.sqlite.org/pragma.html#pragma_foreign_key_check // // PRAGMA foreign_key_check does not return an error, // but the list of violated foreign key constraints. // - // Let's turn any violation into an SQLITE_CONSTRAINT - // error, and rollback the transaction. - throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed") + // Let's turn any violation into an + // SQLITE_CONSTRAINT_FOREIGNKEY error, and rollback + // the transaction. + throw DatabaseError( + resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, + message: "FOREIGN KEY constraint failed") } // > 11. Commit the transaction started in step 2. @@ -79,7 +78,8 @@ struct Migration { } }, finally: { - // > 12. If foreign keys constraints were originally enabled, reenable them now. + // > 12. If foreign keys constraints were originally enabled, + // > reenable them now. try db.execute(sql: "PRAGMA foreign_keys = ON") }) } diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 9320d24c5..d4de32ea1 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -57,7 +57,16 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT score + \(bonus) FROM player /// """ - public mutating func appendInterpolation(_ expressible: T?) { + /// + /// You can also derive literal expressions from other expressions: + /// + /// func date(_ value: SQLExpressible) -> SQLExpression { + /// SQLLiteral("DATE(\(value))").sqlExpression + /// } + /// + /// // SELECT * FROM player WHERE DATE(createdAt) = '2020-02-25' + /// let request = Player.filter(date(Column("createdAt")) == "2020-02-25") + public mutating func appendInterpolation(_ expressible: SQLExpressible?) { if let expressible = expressible { elements.append(.expression(expressible.sqlExpression)) } else { diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index 1d570786d..815d659db 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -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 diff --git a/LICENSE b/LICENSE index bd480b04b..8318870b1 100644 --- a/LICENSE +++ b/LICENSE @@ -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: diff --git a/Makefile b/Makefile index 011848f91..b47878ecf 100644 --- a/Makefile +++ b/Makefile @@ -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" @@ -459,10 +466,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.10.0 \ - --module-version 4.10.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.11.0 \ + --module-version 4.11.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/4.10/ \ + --root-url http://groue.github.io/GRDB.swift/docs/4.11/ \ --output Documentation/Reference \ --podspec GRDB.swift.podspec else diff --git a/README.md b/README.md index 227b294bc..54957d9c3 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,14 @@ --- -**Latest release**: February 23, 2020 • version 4.10.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) +**Latest release**: March 2, 2020 • version 4.11.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.10.0** | -| **Swift 4.2** | **v4.10.0** | +| **Swift 5** | **v4.11.0** | +| **Swift 4.2** | **v4.11.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) | @@ -263,7 +263,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.10/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.11/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -478,7 +478,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.11/Structs/Configuration.html) for more details. ## Database Pools @@ -559,7 +559,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.11/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -619,7 +619,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.10/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.11/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. @@ -820,7 +820,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.10/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.11/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 @@ -902,7 +902,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.10/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.11/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: @@ -1185,7 +1185,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.10/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1592,7 +1592,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.10/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.11/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1706,7 +1706,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.10/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.11/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1965,7 +1965,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.10/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.11/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). @@ -2427,7 +2427,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.10/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.11/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()`. @@ -2808,7 +2808,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.10/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.10/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.10/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.11/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.11/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.11/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). @@ -4197,7 +4197,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4812,7 +4812,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.10/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.11/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4856,7 +4856,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.10/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.11/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests @@ -4921,6 +4921,8 @@ migrator.registerMigration("v2") { db in **Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`. +**Migrations run with deferred foreign key checks,** starting SQLite 3.7.16+ (iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](#encryption)). This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). + **The memory of applied migrations is stored in the database itself** (in a reserved table). You migrate the database up to the latest version with the `migrate(_:)` method: @@ -4929,24 +4931,35 @@ You migrate the database up to the latest version with the `migrate(_:)` method: try migrator.migrate(dbQueue) // or migrator.migrate(dbPool) ``` -To migrate a database up to a specific version, use `migrate(_:upTo:)`: +Migrate a database up to a specific version: ```swift try migrator.migrate(dbQueue, upTo: "v2") -``` -Migrations can only run forward: - -```swift +// Migrations can only run forward: try migrator.migrate(dbQueue, upTo: "v2") try migrator.migrate(dbQueue, upTo: "v1") -// fatal error: database is already migrated beyond migration "v1" +// ^ fatal error: database is already migrated beyond migration "v1" ``` -Check if a migration has been applied: +Check if consecutive migrations have been applied: ```swift -let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) +if try migrator.hasCompletedMigrations(in: dbQueue) { + // All migrations have been applied, up to the last one. +} +if try migrator.hasCompletedMigrations(in: dbQueue, through: "v2") { + // All migrations have been applied up to "v2", and maybe further. +} +if try migrator.lastCompletedMigration(in: dbQueue) == "v2" { + // All migrations have been applied up to "v2", and no further. +} +``` + +Check which migrations have been applied: + +```swift +let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) // Set if appliedMigrations.contains("v2") { // "v2" migration has been applied } @@ -4986,11 +4999,11 @@ The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database i SQLite does not support many schema changes, and won't let you drop a table column with "ALTER TABLE ... DROP COLUMN ...", for example. -Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the `registerMigrationWithDeferredForeignKeyCheck` function: +Yet any kind of schema change is still possible, by recreating tables: ```swift -// Add a NOT NULL constraint on player.name: -migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in +migrator.registerMigration("AddNotNullCheckOnName") { db in + // Add a NOT NULL constraint on player.name: try db.create(table: "new_player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() @@ -5001,7 +5014,7 @@ migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { } ``` -While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors. +> :point_up: **Note**: This technique requires SQLite 3.7.16+ (iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](#encryption)). ## Joined Queries Support @@ -6390,7 +6403,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.10/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.11/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. @@ -6400,7 +6413,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.10/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.11/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7145,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 @@ -7504,7 +7512,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.10/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.10/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.11/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.11/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: @@ -8188,7 +8196,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. diff --git a/Support/Info.plist b/Support/Info.plist index 6557e2d90..739e62260 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,13 +15,13 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.10.0 + 4.11.0 CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) NSHumanReadableCopyright - Copyright © 2015-2019 Gwendal Roué. + Copyright © 2015-2020 Gwendal Roué. NSPrincipalClass diff --git a/TODO.md b/TODO.md index cb33110ae..e41d29cfa 100644 --- a/TODO.md +++ b/TODO.md @@ -38,6 +38,8 @@ - [ ] FTS: prefix queries - [ ] A way to stop a ValueObservation observer without waiting for deinit - [ ] More schema alterations +- [ ] DatabasePool.databaseSchemaIsLocked = true (should forbid schema changes, and never reset dbPool readers' caches). Or can we invalidate reader's cache automatically from the writer connection? +- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? ## Unsure if necessary diff --git a/Tests/CustomSQLite/CustomSQLite/Info.plist b/Tests/CustomSQLite/CustomSQLite/Info.plist index 6f85d07ad..efe118221 100644 --- a/Tests/CustomSQLite/CustomSQLite/Info.plist +++ b/Tests/CustomSQLite/CustomSQLite/Info.plist @@ -23,7 +23,7 @@ LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright - Copyright © 2019 Gwendal Roué. All rights reserved. + Copyright © 2015-2020 Gwendal Roué. All rights reserved. NSMainStoryboardFile Main NSPrincipalClass diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 38fcd0c4d..896d81323 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -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 { diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 95d5e8e58..729377b05 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -7,6 +7,12 @@ import XCTest class DatabaseMigratorTests : GRDBTestCase { + func testEmptyMigrator() throws { + let migrator = DatabaseMigrator() + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + } + func testMigratorDatabaseQueue() throws { let dbQueue = try makeDatabaseQueue() @@ -141,13 +147,8 @@ class DatabaseMigratorTests : GRDBTestCase { } migrator.registerMigration("foreignKeyError") { db in try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')") - do { - // triggers immediate foreign key error: - try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) - XCTFail("Expected error") - } catch { - throw error - } + // triggers foreign key error: + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) } let dbQueue = try makeDatabaseQueue() @@ -163,8 +164,6 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version - XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") - XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [123, \"bobby\"]: foreign key constraint failed") let names = try dbQueue.inDatabase { db in try String.fetchAll(db, sql: "SELECT name FROM persons") @@ -173,7 +172,65 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testMigrationWithoutForeignKeyChecks() throws { + func testForeignKeyViolation() throws { + #if !GRDBCUSTOMSQLITE && !GRDBCIPHER + guard #available(iOS 8.2, OSX 10.10, *) else { + return + } + #endif + var migrator = DatabaseMigrator() + migrator.registerMigration("createPersons") { db in + try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)") + try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)") + try db.execute(sql: "INSERT INTO persons (name) VALUES ('Arthur')") + let personId = db.lastInsertedRowID + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, 'Bobby')", arguments:[personId]) + } + migrator.registerMigration("removePersonTmpColumn") { db in + // Test the technique described at https://www.sqlite.org/lang_altertable.html#otheralter + try db.execute(sql: "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT)") + try db.execute(sql: "INSERT INTO new_persons SELECT id, name FROM persons") + try db.execute(sql: "DROP TABLE persons") + try db.execute(sql: "ALTER TABLE new_persons RENAME TO persons") + } + migrator.registerMigration("foreignKeyError") { db in + try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')") + // triggers foreign key error: + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) + } + + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch let error as DatabaseError { + // Migration 1 and 2 should be committed. + // Migration 3 should not be committed. + + XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + + try dbQueue.inDatabase { db in + // Arthur inserted (migration 1), Barbara (migration 3) not inserted. + var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + var row = rows.first! + XCTAssertEqual(row["name"] as String, "Arthur") + + // persons table has no "tmp" column (migration 2) + XCTAssertEqual(Array(row.columnNames), ["id", "name"]) + + // Bobby inserted (migration 1), not deleted by migration 2. + rows = try Row.fetchAll(db, sql: "SELECT * FROM pets") + XCTAssertEqual(rows.count, 1) + row = rows.first! + XCTAssertEqual(row["name"] as String, "Bobby") + } + } + } + + func testMigrationWithDeferredForeignKeyChecksDeprecated() throws { #if !GRDBCUSTOMSQLITE && !GRDBCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return @@ -239,6 +296,15 @@ class DatabaseMigratorTests : GRDBTestCase { func testAppliedMigrations() throws { var migrator = DatabaseMigrator() + + // No migration + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) + } + + // One migration + migrator.registerMigration("1") { db in try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") @@ -246,22 +312,167 @@ class DatabaseMigratorTests : GRDBTestCase { t.column("score", .integer) } } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) + } + + // Two migrations migrator.registerMigration("2") { db in try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") } - - // Apply migrator - let dbQueue = try makeDatabaseQueue() - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) - - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) - - try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"]) + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"]) + } } + func testHasCompletedMigrations() throws { + var migrator = DatabaseMigrator() + + // No migration + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) + } + + // One migration + + migrator.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) + } + } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) + } + + // Two migrations + + migrator.registerMigration("2") { db in + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") + } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) + } + } + + func testLastCompletedMigration() throws { + var migrator = DatabaseMigrator() + + // No migration + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) + } + + // One migration + + migrator.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) + } + } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1") + } + + // Two migrations + + migrator.registerMigration("2") { db in + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") + } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1") + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "2") + } + } + + func testMergedMigrators() throws { + // Migrate a database + var oldMigrator = DatabaseMigrator() + oldMigrator.registerMigration("1", migrate: { _ in }) + oldMigrator.registerMigration("3", migrate: { _ in }) + + let dbQueue = try makeDatabaseQueue() + try oldMigrator.migrate(dbQueue) + + try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertEqual(oldMigrator.lastCompletedMigration(in: dbQueue), "3") + + // A source code merge inserts a migration between "1" and "3" + var newMigrator = DatabaseMigrator() + newMigrator.registerMigration("1", migrate: { _ in }) + newMigrator.registerMigration("2", migrate: { _ in }) + newMigrator.registerMigration("3", migrate: { _ in }) + + try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) + try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertNil(newMigrator.lastCompletedMigration(in: dbQueue)) + + // The new source code migrates the database + try newMigrator.migrate(dbQueue) + + try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertEqual(oldMigrator.lastCompletedMigration(in: dbQueue), "3") + + try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "2", "3"]) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertEqual(newMigrator.lastCompletedMigration(in: dbQueue), "3") + } + func testEraseDatabaseOnSchemaChange() throws { // 1st version of the migrator var migrator1 = DatabaseMigrator() diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 790836fc9..29acdc2e4 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -35,7 +35,7 @@ class DatabasePoolBackupTests: GRDBTestCase { } } - // TODO: this test is fragile: understand if somethig is wrong, or not: + // TODO: fix flaky test // @available(OSX 10.10, *) // func testConcurrentWriteDuringBackup() throws { // let source = try makeDatabasePool(filename: "source.sqlite") @@ -58,17 +58,19 @@ class DatabasePoolBackupTests: GRDBTestCase { // } // } // -// try source.backup( -// to: destination, -// afterBackupInit: { -// s1.signal() -// _ = s2.wait(timeout: .distantFuture) -// }, -// afterBackupStep: { -// try! source.write { db in -// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") -// } -// }) +// try destination.writeWithoutTransaction { dbDestination in +// try source.backup( +// to: dbDestination, +// afterBackupInit: { +// s1.signal() +// _ = s2.wait(timeout: .distantFuture) +// }, +// afterBackupStep: { +// try! source.write { db in +// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") +// } +// }) +// } // // try source.read { db in // XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 3) diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 374686e88..90810391d 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -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") diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index b02a5b789..69d1ff40b 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -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. @@ -186,7 +187,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { } } - func testUnsafeReaderHasNoDatabaseCache() throws { + func testUnsafeReaderHasDatabaseCache() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in @@ -205,10 +206,10 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = try db.columns(in: "items") _ = try db.indexes(on: "items") - // Assert that a reader cache is still empty - XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) - XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) - XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) + // Assert that a reader cache is warmed + XCTAssertFalse(db.schemaCache.primaryKey("items") == nil) + XCTAssertFalse(db.schemaCache.columns(in: "items") == nil) + XCTAssertFalse(db.schemaCache.indexes(on: "items") == nil) } } } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index ddb3c3278..a2fe9fd60 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -473,6 +473,33 @@ extension SQLLiteralTests { SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' """) } + + do { + // Here we test that users can define functions that return + // literal expressions. + func date(_ value: SQLExpressible) -> SQLExpression { + return SQLLiteral("DATE(\(value))").sqlExpression + } + let createdAt = Column("createdAt") + let request = Player.filter(date(createdAt) == "2020-01-23") + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } + + do { + // Here we test that users can still define functions that + // return literal expressions with the previously + // supported technique. + func date(_ value: SQLExpressible) -> SQLExpression { + return SQLLiteral("DATE(\(value.sqlExpression))").sqlExpression + } + let createdAt = Column("createdAt") + let request = Player.filter(date(createdAt) == "2020-01-23") + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } } } }