diff --git a/CHANGELOG.md b/CHANGELOG.md index be6021f2c..d07e9c987 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases -- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) +- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) #### 4.x Releases @@ -74,6 +74,26 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release --> +## 5.0.0-beta.5 + +Released June 15, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.4...v5.0.0-beta.5) + +- **Breaking Change** [#795](https://github.com/groue/GRDB.swift/pull/795): Enhanced support for WAL Checkpoints +- **New**: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement. +- **New**: Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. We are now able to avoid fetching the observed value when we can prove that the database wasn't changed between the initial fetch and the beginning of transaction tracking. This optimization avoids duplicate notifications. +- **New**: The query interface now exposes the primary key through `TableRecord.primaryKey`, as well as the `selectPrimaryKey(as:)` method. + +### Documentation Diff + +- The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) was updated for better conformance with the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. + +- A new [FAQ: Associations](README.md#faq-associations) addresses three frequent questions: + - [How do I filter records and only keep those that are associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) + - [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) + - [How do I select only one column of an associated record?](README.md#how-do-i-select-only-one-column-of-an-associated-record) + +- The guide for [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) now recommends enabling the `SQLITE_ENABLE_SNAPSHOT` option. + ## 5.0.0-beta.4 diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index d21cf4f71..b057948dd 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -39,7 +39,14 @@ GRDB Associations - [Aggregate Operations] - [Isolation of Multiple Aggregates] - [DerivableRequest Protocol] -- [Known Issues] + +**[FAQ]** + +- [How do I filter records and only keep those that are associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) +- [How do I filter records and only keep those that are NOT associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) +- [How do I select only one column of an associated record?](../README.md#how-do-i-select-only-one-column-of-an-associated-record) + +**[Known Issues]** ## Associations Benefits @@ -2468,3 +2475,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [persistence methods]: ../README.md#persistence-methods [database observation tools]: ../README.md#database-changes-observation [ValueObservation]: ../README.md#valueobservation +[FAQ]: ../README.md#faq-associations diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 40ca1862f..832a4fd22 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -19,7 +19,9 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal git submodule update --init SQLiteCustom/src ``` -2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`. +2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`. + + It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools). 3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory. @@ -30,7 +32,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```xcconfig // As many -D options as there are custom SQLite compilation options // Note: there is no space between -D and the option name. - CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK + CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5 ``` - `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs. @@ -38,15 +40,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```xcconfig // As many -D options as there are custom SQLite compilation options // Note: there is one space between -D and the option name. - CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK + CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5 ``` - `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags. ```c // As many #define as there are custom SQLite compilation options + #define SQLITE_ENABLE_SNAPSHOT #define SQLITE_ENABLE_FTS5 - #define SQLITE_ENABLE_PREUPDATE_HOOK ``` - `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files. diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 1f1a950fe..5e3075588 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -25,7 +25,7 @@ 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; }; 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; - 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; }; + 56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -181,7 +181,7 @@ 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; 56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; - 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; + 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = ""; }; 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; /* End PBXFileReference section */ @@ -273,15 +273,15 @@ 56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = { isa = PBXGroup; children = ( - 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, + 56B036121E8D9EBE003B6DA4 /* Info.plist */, 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, + 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, 56B0361A1E8D9F38003B6DA4 /* Player.swift */, 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */, - 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */, - 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, + 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */, 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */, 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */, - 56B036121E8D9EBE003B6DA4 /* Info.plist */, + 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, ); path = GRDBDemoiOS; sourceTree = ""; @@ -507,7 +507,7 @@ 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */, 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */, 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */, - 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */, + 56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */, 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 0aa715f38..8e3e4d8e5 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -1,26 +1,22 @@ import GRDB -/// A type responsible for initializing the application database. +/// AppDatabase lets the application access the database. /// -/// See AppDelegate.setupDatabase() -struct AppDatabase { +/// It applies the pratices recommended at +/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md +final class AppDatabase { + private let dbQueue: DatabaseQueue - /// Creates a fully initialized database at path - static func openDatabase(atPath path: String) throws -> DatabaseQueue { - // Connect to the database - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections - let dbQueue = try DatabaseQueue(path: path) - - // Define the database schema + /// Creates an AppDatabase and updates its schema if necessary. + init(_ dbQueue: DatabaseQueue) throws { + self.dbQueue = dbQueue try migrator.migrate(dbQueue) - - return dbQueue } /// The DatabaseMigrator that defines the database schema. /// /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md - static var migrator: DatabaseMigrator { + private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() migrator.registerMigration("createPlayer") { db in @@ -54,3 +50,107 @@ struct AppDatabase { } } +// MARK: - Database Access +// +// This extension defines methods that fulfill application needs, both in terms +// of writes and reads. + +extension AppDatabase { + + // MARK: Writes + + /// Save (insert or update) a player. + func savePlayer(_ player: inout Player) throws { + try dbQueue.write { db in + try player.save(db) + } + } + + /// Delete one player + func deletePlayer(_ player: Player) throws { + try dbQueue.write { db in + _ = try player.delete(db) + } + } + + /// Delete all players + func deleteAllPlayers() throws { + try dbQueue.write { db in + _ = try Player.deleteAll(db) + } + } + + /// Refresh all players (by performing some random changes, for demo purpose). + func refreshPlayers() throws { + try dbQueue.write { db in + if try Player.fetchCount(db) == 0 { + // Insert new random players + for _ in 0..<8 { + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) + } + } else { + // Insert a player + if Bool.random() { + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) + } + // Delete a random player + if Bool.random() { + try Player.order(sql: "RANDOM()").limit(1).deleteAll(db) + } + // Update some players + for var player in try Player.fetchAll(db) where Bool.random() { + try player.updateChanges(db) { + $0.score = Player.randomScore() + } + } + } + } + } + + // MARK: Reads + + /// Tracks changes in the number of players + func observePlayerCount( + onError: @escaping (Error) -> Void, + onChange: @escaping (Int) -> Void) + -> DatabaseCancellable + { + ValueObservation + .tracking(Player.fetchCount) + .start( + in: dbQueue, + onError: onError, + onChange: onChange) + } + + /// Tracks changes in players ordered by name + func observePlayersOrderedByName( + onError: @escaping (Error) -> Void, + onChange: @escaping ([Player]) -> Void) + -> DatabaseCancellable + { + ValueObservation + .tracking(Player.all().orderedByName().fetchAll) + .start( + in: dbQueue, + onError: onError, + onChange: onChange) + } + + /// Tracks changes in players ordered by score + func observePlayersOrderedByScore( + onError: @escaping (Error) -> Void, + onChange: @escaping ([Player]) -> Void) + -> DatabaseCancellable + { + ValueObservation + .tracking(Player.all().orderedByScore().fetchAll) + .start( + in: dbQueue, + onError: onError, + onChange: onChange) + } +} + diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 3df9947f3..834856c3e 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -1,8 +1,8 @@ import UIKit import GRDB -// The shared database queue -var dbQueue: DatabaseQueue! +// The shared application database +var appDatabase: AppDatabase! @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { @@ -14,9 +14,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } private func setupDatabase(_ application: UIApplication) throws { + // AppDelegate is responsible for choosing the location of the database file. + // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections let databaseURL = try FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("db.sqlite") - dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path) + let dbQueue = try DatabaseQueue(path: databaseURL.path) + + // Create the shared application database + appDatabase = try AppDatabase(dbQueue) } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard index 4fd2097aa..8d863c1f6 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard @@ -1,8 +1,8 @@ - - + + - + @@ -10,25 +10,25 @@ - - + + - - + - + - + - - + + + @@ -40,17 +40,24 @@ + + + + - + - + - - + + + + + @@ -101,7 +108,7 @@ - + @@ -117,7 +124,7 @@ - + @@ -131,27 +138,27 @@ - + - + - + - +