From f67f9ebd4b26192498b90c6d96ad8318e57851bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 15:56:12 +0200 Subject: [PATCH 01/51] Add a sanity transaction assertion --- GRDB/Core/TransactionObserver.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 663d9b7f8..695b91e5c 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -496,6 +496,7 @@ class DatabaseObservationBroker { /// Remove transaction observers that have stopped observing transaction, /// and uninstall SQLite update hooks if there is no remaining observers. private func databaseDidEndTransaction() { + assert(!database.isInsideTransaction) transactionObservations = transactionObservations.filter(\.isObserving) // Undo disableUntilNextTransaction(transactionObserver:) From 20f693c508148aad8f437abd154e3d9d62bd9430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 15:56:41 +0200 Subject: [PATCH 02/51] Disable two SQLCipher tests until we understand what is happening --- Tests/GRDBTests/TransactionObserverTests.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index ed07f14a9..a5df7e16e 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -185,9 +185,14 @@ class TransactionObserverTests: GRDBTestCase { try assertTransaction(start: "SAVEPOINT test", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) - try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) + + #if !SQLITE_HAS_CODEC + // These tests fail with SQLCipher 4 (both debug and release configuration) + // TODO: is it GRDB or SQLCipher? + try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit) + #endif // explicit rollback try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback) From 668c1d632e9b1220960484527502b07cf6876e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 17:07:02 +0200 Subject: [PATCH 03/51] f67f9ebd4b26192498b90c6d96ad8318e57851bc did spot an oddity This is a temp fix --- GRDB/Core/TransactionObserver.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 695b91e5c..a60bda7a1 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -283,6 +283,17 @@ class DatabaseObservationBroker { } } + switch transactionState { + case .none: + break + default: + // May happen after "PRAGMA journal_mode = WAL" executed with a + // SelectStatement. + // TODO: Maybe this state machine should be run for *all* statements, + // not ony update statements. + transactionState = .none + } + if observesRowDeletion { return TruncateOptimizationBlocker() } else { From 91ed7d762bc7ed8c10143d9ec0f24987365c2617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 09:18:15 +0200 Subject: [PATCH 04/51] Setup busy handler as soon as possible --- GRDB/Core/Database.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index fbe6a3605..e27682996 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -211,9 +211,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// This method must be called after database initialization func setup() throws { + setupBusyMode() setupDoubleQuotedStringLiterals() try setupForeignKeys() - setupBusyMode() setupDefaultFunctions() setupDefaultCollations() setupAuthorizer() From 5f88a400d51a691f00615bd4000450b85421a737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 10:08:19 +0200 Subject: [PATCH 05/51] DatabasePool.checkpoint(_:) is unavailable --- GRDB/Core/DatabasePool.swift | 18 ------------------ GRDB/Fixit/GRDB-5.0.swift | 3 +++ 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 2cab90a07..bf4d43f63 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -167,24 +167,6 @@ public final class DatabasePool: DatabaseWriter { } } -extension DatabasePool { - - // MARK: - WAL Checkpoints - - /// Runs a WAL checkpoint - /// - /// See https://www.sqlite.org/wal.html and - /// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) for - /// more information. - /// - /// - parameter kind: The checkpoint mode (default passive) - public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { - try writer.sync { db in - try db.checkpoint(kind) - } - } -} - extension DatabasePool { // MARK: - Memory management diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index f240beeff..caffee00c 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -86,6 +86,9 @@ extension DatabaseMigrator { } extension DatabasePool { + @available(*, unavailable, message: "Use pool.writeWithoutTransaction { $0.checkpoint() } instead") + public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { preconditionFailure() } + #if os(iOS) @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } From 56f6984f9d076bd89a0b6fa8a7a8a368f216b204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 10:08:54 +0200 Subject: [PATCH 06/51] Introduce Database.checkpoint(_:on:) --- GRDB/Core/Database.swift | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index e27682996..da30e4bad 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -621,11 +621,34 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - // MARK: - Checkpoints + // MARK: - WAL Checkpoints - func checkpoint(_ kind: Database.CheckpointMode) throws { - let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil) - guard code == SQLITE_OK else { + /// Runs a WAL checkpoint. + /// + /// See https://www.sqlite.org/wal.html and + /// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for + /// more information. + /// + /// - parameter kind: The checkpoint mode (default passive) + /// - parameter dbName: The database name (default "main") + /// - returns: A tuple: + /// - `logCount`: the total number of frames in the log file + /// - `checkpointCount`: the total number of checkpointed frames in the + /// log file + @discardableResult + public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws + -> (logCount: Int, checkpointCount: Int) + { + SchedulingWatchdog.preconditionValidQueue(self) + var logCount: CInt = -1 + var checkpointCount: CInt = -1 + let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue, &logCount, &checkpointCount) + switch code { + case SQLITE_OK: + return (logCount: Int(logCount), checkpointCount: Int(checkpointCount)) + case SQLITE_MISUSE: + throw DatabaseError(resultCode: code) + default: throw DatabaseError(resultCode: code, message: lastErrorMessage) } } From 6f3ec89bcd0dbb8404dc11830102ec108b100310 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 10:09:24 +0200 Subject: [PATCH 07/51] Update checkpointing tests --- Tests/GRDBTests/DatabasePoolConcurrencyTests.swift | 8 ++++---- Tests/GRDBTests/DatabaseSnapshotTests.swift | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 73e31caab..842da567e 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -442,8 +442,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { defer { s2.signal() } try dbPool.writeWithoutTransaction { db in try db.execute(sql: "DELETE FROM items") + try db.checkpoint() } - try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } @@ -538,8 +538,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { defer { s2.signal() } try dbPool.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + try db.checkpoint() } - try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } @@ -759,8 +759,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { defer { s2.signal() } try dbPool.writeWithoutTransaction { db in try db.execute(sql: "DELETE FROM items") + try db.checkpoint() } - try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } @@ -803,8 +803,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { defer { s2.signal() } try dbPool.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + try db.checkpoint() } - try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index dc7bdb8e2..df3c8cb4a 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -270,7 +270,7 @@ class DatabaseSnapshotTests: GRDBTestCase { let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() - try? dbPool.checkpoint(.passive) // ignore if error or not, that's not the point + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) @@ -281,7 +281,7 @@ class DatabaseSnapshotTests: GRDBTestCase { let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() - try? dbPool.checkpoint(.full) // ignore if error or not, that's not the point + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) @@ -292,7 +292,7 @@ class DatabaseSnapshotTests: GRDBTestCase { let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() - try? dbPool.checkpoint(.restart) // ignore if error or not, that's not the point + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) @@ -303,7 +303,7 @@ class DatabaseSnapshotTests: GRDBTestCase { let counter = try Counter(dbPool: dbPool) try dbPool.write(counter.increment) let snapshot = try dbPool.makeSnapshot() - try? dbPool.checkpoint(.truncate) // ignore if error or not, that's not the point + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) try dbPool.write(counter.increment) try XCTAssertEqual(snapshot.read(counter.value), 1) From 3e5a21b49b249fec93e8c646d39c525c45bd155e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 10:09:48 +0200 Subject: [PATCH 08/51] Tests for Database.checkpoint(_:on:) --- Tests/GRDBTests/DatabaseTests.swift | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 14e735724..7db71fbc2 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -345,4 +345,34 @@ class DatabaseTests : GRDBTestCase { try db.execute(sql: "INSERT INTO t DEFAULT VALUES") } } + + func testCheckpoint() throws { + do { + // Not a WAL database + let dbQueue = try makeDatabaseQueue() + let result = try dbQueue.inDatabase { + try $0.checkpoint() + } + XCTAssertEqual(result.logCount, -1) + XCTAssertEqual(result.checkpointCount, -1) + } + do { + // WAL database + let dbPool = try makeDatabasePool() + let result = try dbPool.writeWithoutTransaction { + try $0.checkpoint() + } + XCTAssertGreaterThanOrEqual(result.logCount, 0) + XCTAssertGreaterThanOrEqual(result.checkpointCount, 0) + } + do { + // WAL database + TRUNCATE + let dbPool = try makeDatabasePool() + let result = try dbPool.writeWithoutTransaction { + try $0.checkpoint(.truncate) + } + XCTAssertEqual(result.logCount, 0) + XCTAssertEqual(result.checkpointCount, 0) + } + } } From 3a42a4bf9f98481a3bb4d65e5379e1fe0116257b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 10:18:52 +0200 Subject: [PATCH 09/51] Rename checkpoint tuple members --- GRDB/Core/Database.swift | 16 ++++++++-------- Tests/GRDBTests/DatabaseTests.swift | 12 ++++++------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index da30e4bad..6ffbe95e0 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -632,20 +632,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// - parameter kind: The checkpoint mode (default passive) /// - parameter dbName: The database name (default "main") /// - returns: A tuple: - /// - `logCount`: the total number of frames in the log file - /// - `checkpointCount`: the total number of checkpointed frames in the - /// log file + /// - `walFrameCount`: the total number of frames in the log file + /// - `checkpointedFrameCount`: the total number of checkpointed frames + /// in the log file @discardableResult public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws - -> (logCount: Int, checkpointCount: Int) + -> (walFrameCount: Int, checkpointedFrameCount: Int) { SchedulingWatchdog.preconditionValidQueue(self) - var logCount: CInt = -1 - var checkpointCount: CInt = -1 - let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue, &logCount, &checkpointCount) + var walFrameCount: CInt = -1 + var checkpointedFrameCount: CInt = -1 + let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue, &walFrameCount, &checkpointedFrameCount) switch code { case SQLITE_OK: - return (logCount: Int(logCount), checkpointCount: Int(checkpointCount)) + return (walFrameCount: Int(walFrameCount), checkpointedFrameCount: Int(checkpointedFrameCount)) case SQLITE_MISUSE: throw DatabaseError(resultCode: code) default: diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 7db71fbc2..6bb8f265a 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -353,8 +353,8 @@ class DatabaseTests : GRDBTestCase { let result = try dbQueue.inDatabase { try $0.checkpoint() } - XCTAssertEqual(result.logCount, -1) - XCTAssertEqual(result.checkpointCount, -1) + XCTAssertEqual(result.walFrameCount, -1) + XCTAssertEqual(result.checkpointedFrameCount, -1) } do { // WAL database @@ -362,8 +362,8 @@ class DatabaseTests : GRDBTestCase { let result = try dbPool.writeWithoutTransaction { try $0.checkpoint() } - XCTAssertGreaterThanOrEqual(result.logCount, 0) - XCTAssertGreaterThanOrEqual(result.checkpointCount, 0) + XCTAssertGreaterThanOrEqual(result.walFrameCount, 0) + XCTAssertGreaterThanOrEqual(result.checkpointedFrameCount, 0) } do { // WAL database + TRUNCATE @@ -371,8 +371,8 @@ class DatabaseTests : GRDBTestCase { let result = try dbPool.writeWithoutTransaction { try $0.checkpoint(.truncate) } - XCTAssertEqual(result.logCount, 0) - XCTAssertEqual(result.checkpointCount, 0) + XCTAssertEqual(result.walFrameCount, 0) + XCTAssertEqual(result.checkpointedFrameCount, 0) } } } From 3103e6e373f7c52eee0ddba47ddaf6d4cec291be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 15:55:46 +0200 Subject: [PATCH 10/51] Fix Swiftlint warning --- GRDB/Core/Database.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 6ffbe95e0..da522e3f4 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -642,7 +642,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib SchedulingWatchdog.preconditionValidQueue(self) var walFrameCount: CInt = -1 var checkpointedFrameCount: CInt = -1 - let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue, &walFrameCount, &checkpointedFrameCount) + let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue, + &walFrameCount, &checkpointedFrameCount) switch code { case SQLITE_OK: return (walFrameCount: Int(walFrameCount), checkpointedFrameCount: Int(checkpointedFrameCount)) From e31f7a4763b63a2cd4bec73e4abb8796c2b2ed36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Jun 2020 16:39:13 +0200 Subject: [PATCH 11/51] CHANGELOG --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be6021f2c..705dfa9f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 5.x Releases @@ -70,9 +68,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +- [#795](https://github.com/groue/GRDB.swift/pull/795): **Breaking Change** Enhanced support for WAL Checkpoints ## 5.0.0-beta.4 From e8235f8d6a06370708e8520a632e9ce85bc4d735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 11 Jun 2020 12:49:22 +0200 Subject: [PATCH 12/51] Database.columnsForUniqueKey(_:in:) does not hit the database for empty column sequences --- GRDB/Core/Database+Schema.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 7e9f6beba..2ec6381e8 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -344,14 +344,18 @@ extension Database { throws -> [String]? where T.Iterator.Element == String { - // Check primaryKey first, so that we fail early if the table does not exist let lowercasedColumns = Set(columns.map { $0.lowercased() }) + if lowercasedColumns.isEmpty { + // Don't hit the database for trivial case + return nil + } // Assume "rowid" is a primary key if lowercasedColumns == ["rowid"] { return ["rowid"] } + // Check primaryKey. let primaryKey = try self.primaryKey(tableName) if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) { return primaryKey.columns From b15999e4c9980ad588633ff9407655ebb2ba5702 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Jun 2020 12:45:12 +0200 Subject: [PATCH 13/51] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 4fa161dad..db818196c 100644 --- a/TODO.md +++ b/TODO.md @@ -16,6 +16,7 @@ ## Features +- [ ] Handle SQLITE_LIMIT_VARIABLE_NUMBER in deleteAll(_:keys:) and similar APIs. https://www.sqlite.org/limits.html - [ ] Subqueries: request.isEmpty / request.exists - [ ] Subqueries: request.count - [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767) From 8d44ad7256bb3215d622ed87ec81ee47a1862496 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Jun 2020 14:19:13 +0200 Subject: [PATCH 14/51] Database.maximumStatementArgumentCount --- GRDB/Core/Database.swift | 17 +++++++++++++++++ Tests/GRDBTests/DatabaseTests.swift | 7 +++++++ 2 files changed, 24 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index da522e3f4..88b205c45 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -380,6 +380,23 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } + // MARK: - Limits + + /// The maximum number of arguments accepted by an SQLite statement. + /// + /// For example, requests such as the one below must make sure the `ids` + /// array does not contain more than `maximumStatementArgumentCount` + /// elements: + /// + /// let ids: [Int] = ... + /// Player.deleteAll(keys: ids) + /// + /// See https://www.sqlite.org/limits.html + /// and `SQLITE_LIMIT_VARIABLE_NUMBER`. + public var maximumStatementArgumentCount: Int { + Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) + } + // MARK: - Functions /// Add or redefine an SQL function. diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 6bb8f265a..e8af602aa 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -375,4 +375,11 @@ class DatabaseTests : GRDBTestCase { XCTAssertEqual(result.checkpointedFrameCount, 0) } } + + func testMaximumStatementArgumentCount() throws { + let dbQueue = try makeDatabaseQueue() + let count = dbQueue.read { $0.maximumStatementArgumentCount } + // 999 should be safe: https://www.sqlite.org/limits.html + XCTAssertGreaterThanOrEqual(count, 999) + } } From a95b3264dea143604442ed93e21040b7cb2e3af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Jun 2020 14:20:29 +0200 Subject: [PATCH 15/51] Fix documentation --- GRDB/Core/Database.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 88b205c45..ee94e4be0 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -389,7 +389,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// elements: /// /// let ids: [Int] = ... - /// Player.deleteAll(keys: ids) + /// try dbQueue.write { db in + /// try Player.deleteAll(db, keys: ids) + /// } /// /// See https://www.sqlite.org/limits.html /// and `SQLITE_LIMIT_VARIABLE_NUMBER`. From 45f5ece534a3f74e0b144688078a5ed4c730e4f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Jun 2020 14:22:47 +0200 Subject: [PATCH 16/51] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 705dfa9f4..342f4f27c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - [#795](https://github.com/groue/GRDB.swift/pull/795): **Breaking Change** Enhanced support for WAL Checkpoints +- New: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement. ## 5.0.0-beta.4 From 372996deb320e00cf23a7d149b6246edb4b612f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 13 Jun 2020 13:34:10 +0200 Subject: [PATCH 17/51] TODO # Conflicts: # TODO.md --- GRDB/Core/DatabasePool.swift | 1 + TODO.md | 1 + 2 files changed, 2 insertions(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index bf4d43f63..b803f258b 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -908,6 +908,7 @@ extension DatabasePool: DatabaseReader { guard let db = db else { return } if observer.isCompleted { return } do { + #warning("TODO: can we use snapshots in order to avoid this safety fetch, if we can prove database was not changed since initial fetch?") // Don't miss eventual changes between the // initial fetch and the writer access. if let value = try observer.fetchValue(db) { diff --git a/TODO.md b/TODO.md index db818196c..336508b23 100644 --- a/TODO.md +++ b/TODO.md @@ -17,6 +17,7 @@ ## Features - [ ] Handle SQLITE_LIMIT_VARIABLE_NUMBER in deleteAll(_:keys:) and similar APIs. https://www.sqlite.org/limits.html +- [ ] Concurrent migrator / or not - [ ] Subqueries: request.isEmpty / request.exists - [ ] Subqueries: request.count - [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767) From f1e65fbb2cd9360340016778922b8433127e9083 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 13 Jun 2020 17:11:47 +0200 Subject: [PATCH 18/51] Optimization of ValueObservation with DatabasePool thanks to SQLITE_ENABLE_SNAPSHOT The difficulty is that system does not contain the expected declarations, even when SQLite is compiled with SQLITE_ENABLE_SNAPSHOT :-( Since snapshots are not exposed in any public API, we don't bother dealing with availability checks. We just add the missing declarations, and rely on the linker in order to spot eventual errors. This commit is likely to break Linux builds, though. --- GRDB.xcodeproj/project.pbxproj | 4 +- GRDB/Core/Database.swift | 20 +++++ GRDB/Core/DatabasePool.swift | 55 +++++++++++--- GRDBCustom.xcodeproj/project.pbxproj | 28 +++---- Makefile | 12 +-- SQLiteCustom/grdb_config.h | 49 +++++++++++++ Sources/CSQLite/shim.h | 24 ++++++ Support/GRDBDeploymentTarget.xcconfig | 4 - Support/grdb_config.h | 54 +++++++++++--- Tests/GRDBTests/ValueObservationTests.swift | 81 +++++++++++++++++++++ 10 files changed, 283 insertions(+), 48 deletions(-) create mode 100644 SQLiteCustom/grdb_config.h diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d222458ad..fddc1c8fb 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -2331,10 +2331,10 @@ 567DAF141EAB61ED00FC0928 /* grdb_config.h */, DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */, DC3773F819C8CBB3004FCF85 /* GRDB.h */, + 56C48E731C9A9923005DF1D9 /* module.modulemap */, + DC3773F719C8CBB3004FCF85 /* Info.plist */, 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */, 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */, - DC3773F719C8CBB3004FCF85 /* Info.plist */, - 56C48E731C9A9923005DF1D9 /* module.modulemap */, ); name = "Supporting Files"; path = ../Support; diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ee94e4be0..e2a18e103 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -485,6 +485,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib finally: endReadOnly) } + // MARK: - Snapshots + + /// Exposes sqlite3_snapshot_get. + /// + /// Returns a snapshot that must be freed with `sqlite3_snapshot_free`. + func makeSnapshot() throws -> UnsafeMutablePointer { + var snapshot: UnsafeMutablePointer? + let code = withUnsafeMutablePointer(to: &snapshot) { + sqlite3_snapshot_get(sqliteConnection, "main", $0) + } + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + if let snapshot = snapshot { + return snapshot + } else { + throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? + } + } + // MARK: - Authorizer func withAuthorizer(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b803f258b..d2cee5042 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -900,23 +900,60 @@ extension DatabasePool: DatabaseReader { guard let self = self else { return } if observer.isCompleted { return } do { - let initialValue = try observer.fetchInitialValue(dbResult.get()) + let db = try dbResult.get() + + // Grab a snaphot of the state of the database when we + // perform the initial fetch. + // + // Since not all SQLite version support snapshotting, + // ignore errors. + var initialSnapshot = try? db.makeSnapshot() + + let initialValue = try observer.fetchInitialValue(db) observer.notifyChange(initialValue) // Now wait for the writer self._weakAsyncWriteWithoutTransaction { db in + defer { + if let initialSnapshot = initialSnapshot { + sqlite3_snapshot_free(initialSnapshot) + } + } + guard let db = db else { return } if observer.isCompleted { return } + do { - #warning("TODO: can we use snapshots in order to avoid this safety fetch, if we can prove database was not changed since initial fetch?") - // Don't miss eventual changes between the - // initial fetch and the writer access. - if let value = try observer.fetchValue(db) { - observer.notifyChange(value) + // Transaction is needed for snapshotting + try db.inTransaction(.deferred) { + var fetchNeeded = true + if initialSnapshot != nil { + // Grab a snaphot of the current state of the + // database. If it did not change since + // initial snapshot, then we do not need to + // perform a second fetch. + if let secondSnapshot = try? db.makeSnapshot() { + // Compare snapshots + let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) + assert(cmp <= 0, "Unexpected snapshot ordering") + fetchNeeded = cmp < 0 + sqlite3_snapshot_free(secondSnapshot) + } + + // Early free before the above defer { } + sqlite3_free(initialSnapshot) + initialSnapshot = nil + } + + if fetchNeeded, let value = try observer.fetchValue(db) { + observer.notifyChange(value) + } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) + + return .commit } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) } catch { observer.notifyErrorAndComplete(error) } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 865cb54ee..b9b54b162 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -313,8 +313,6 @@ 56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; - 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; - 567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */; }; @@ -426,6 +424,8 @@ 56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; }; 56C0539E22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; }; 56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; + 56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; }; 56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; }; 56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; }; @@ -905,7 +905,6 @@ 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; - 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; @@ -994,7 +993,6 @@ 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = ""; }; - 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; 56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = ""; }; 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = ""; }; 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Pattern.swift; sourceTree = ""; }; @@ -1008,9 +1006,8 @@ 56C0538E22ACEECD0029D27D /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = ""; }; 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = ""; }; - 56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = ""; }; - 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; 56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; + 56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = ""; }; 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = ""; }; 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; @@ -1821,13 +1818,9 @@ DC37743319C8CFCE004FCF85 /* Supporting Files */ = { isa = PBXGroup; children = ( - 567DAF141EAB61ED00FC0928 /* grdb_config.h */, DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */, DC3773F819C8CBB3004FCF85 /* GRDB.h */, - 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */, - 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */, DC3773F719C8CBB3004FCF85 /* Info.plist */, - 56C48E731C9A9923005DF1D9 /* module.modulemap */, ); name = "Supporting Files"; path = ../Support; @@ -1845,15 +1838,16 @@ F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */ = { isa = PBXGroup; children = ( - EED476F41CFD174D0026A4EC /* Customize */, + 56C9EB9A2495324700FE5D55 /* grdb_config.h */, + 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */, + F3BA7FF11CFB23D3003DC1BA /* GRDB.h */, + F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */, + F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */, F3BA7FEE1CFB23B7003DC1BA /* GRDB.xcconfig */, F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */, 56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */, - F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */, - F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */, - F3BA7FF11CFB23D3003DC1BA /* GRDB.h */, - 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */, F3BA7FF31CFB23E4003DC1BA /* SQLiteLib.xcodeproj */, + EED476F41CFD174D0026A4EC /* Customize */, ); name = GRDBCustomSQLite; sourceTree = ""; @@ -1874,9 +1868,9 @@ buildActionMask = 2147483647; files = ( F3BA80381CFB2932003DC1BA /* GRDB.h in Headers */, + 56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */, 56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */, F3BA803A1CFB293A003DC1BA /* sqlite3.h in Headers */, - 567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */, EED476F31CFD172C0026A4EC /* GRDBCustomSQLite-USER.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1886,9 +1880,9 @@ buildActionMask = 2147483647; files = ( F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */, + 56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */, 56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */, F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */, - 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */, EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Makefile b/Makefile index a9d9a4ab6..caca9ca11 100644 --- a/Makefile +++ b/Makefile @@ -115,7 +115,7 @@ test_framework_GRDBOSX_maxSwift: -scheme GRDBOSX \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ - 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) @@ -126,7 +126,7 @@ ifdef MIN_SWIFT_VERSION -scheme GRDBOSX \ SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ - 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) endif @@ -150,7 +150,7 @@ test_framework_GRDBiOS_maxTarget_maxSwift: -destination $(MAX_IOS_DESTINATION) \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ - 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) @@ -162,7 +162,7 @@ ifdef MIN_SWIFT_VERSION -destination $(MAX_IOS_DESTINATION) \ SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ - 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) endif @@ -186,7 +186,7 @@ test_framework_GRDBtvOS_maxTarget_maxSwift: -destination $(MAX_TVOS_DESTINATION) \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ - 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) @@ -198,7 +198,7 @@ ifdef MIN_SWIFT_VERSION -destination $(MAX_TVOS_DESTINATION) \ SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ - 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) endif diff --git a/SQLiteCustom/grdb_config.h b/SQLiteCustom/grdb_config.h new file mode 100644 index 000000000..860796fbd --- /dev/null +++ b/SQLiteCustom/grdb_config.h @@ -0,0 +1,49 @@ +#ifndef grdb_config_h +#define grdb_config_h + +typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); + +/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic +/// function that can't be used from Swift. +static inline void registerErrorLogCallback(errorLogCallback callback) { + sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); +} + +#if SQLITE_VERSION_NUMBER >= 3029000 +/// Wrapper around sqlite3_db_config() which is a variadic function that can't +/// be used from Swift. +static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); +} + +/// Wrapper around sqlite3_db_config() which is a variadic function that can't +/// be used from Swift. +static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0); + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0); +} +#else +static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } +#endif + +/* Expose missing APIs for easier GRDB development*/ +#ifndef SQLITE_ENABLE_SNAPSHOT +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return SQLITE_MISUSE; +} +SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot* ppSnapshot) { } +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return 0; +} +#endif /* SQLITE_ENABLE_SNAPSHOT */ + +#endif /* grdb_config_h */ diff --git a/Sources/CSQLite/shim.h b/Sources/CSQLite/shim.h index be4cd9cf9..d08d75324 100644 --- a/Sources/CSQLite/shim.h +++ b/Sources/CSQLite/shim.h @@ -26,3 +26,27 @@ static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif + +/* Expose missing APIs for easier GRDB development*/ +#ifndef SQLITE_ENABLE_SNAPSHOT +/* Expose APIs that are missing from system */ +typedef struct sqlite3_snapshot { + unsigned char hidden[48]; +} sqlite3_snapshot; +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot +); +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot *pSnapshot +); +SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2 +); +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); +#endif /* SQLITE_ENABLE_SNAPSHOT */ diff --git a/Support/GRDBDeploymentTarget.xcconfig b/Support/GRDBDeploymentTarget.xcconfig index a88f9e56d..58994c0a3 100644 --- a/Support/GRDBDeploymentTarget.xcconfig +++ b/Support/GRDBDeploymentTarget.xcconfig @@ -2,7 +2,3 @@ IPHONEOS_DEPLOYMENT_TARGET = 10.0 MACOSX_DEPLOYMENT_TARGET = 10.10 TVOS_DEPLOYMENT_TARGET = 9.0 WATCHOS_DEPLOYMENT_TARGET = 2.0 - -//// Compile with all opt-in APIs -//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 -//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK diff --git a/Support/grdb_config.h b/Support/grdb_config.h index 7fc823001..28547f01a 100644 --- a/Support/grdb_config.h +++ b/Support/grdb_config.h @@ -1,17 +1,10 @@ #ifndef grdb_config_h #define grdb_config_h -#if defined(COCOAPODS) - #if defined(GRDBCIPHER) - #include - #else - #include - #endif +#ifdef GRDBCIPHER + #include #else - // Assume custom SQLite build otherwize - #if !defined(SQLITE_VERSION_NUMBER) - #include - #endif + #include #endif typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); @@ -62,4 +55,45 @@ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); #endif /* GRDB_SQLITE_ENABLE_PREUPDATE_HOOK */ +/* Expose missing APIs for easier GRDB development*/ +#ifndef SQLITE_ENABLE_SNAPSHOT +#ifdef GRDBCIPHER +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return SQLITE_MISUSE; +} +SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot* ppSnapshot) { } +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return 0; +} +#else +/* Expose APIs that are missing from system */ +typedef struct sqlite3_snapshot { + unsigned char hidden[48]; +} sqlite3_snapshot; +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot +); +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot *pSnapshot +); +SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2 +); +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); +#endif +#endif /* SQLITE_ENABLE_SNAPSHOT */ + #endif /* grdb_config_h */ diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 179ad4a87..44130bbab 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -99,6 +99,87 @@ class ValueObservationTests: GRDBTestCase { XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked } + func testDisallowedSnapshotOptimization() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + // Force DatabasePool to perform two initial fetches, because between + // its first read access, and its write access that installs the + // transaction observer, some write did happen. + var needsChange = true + let observation = ValueObservation.tracking { db -> Int in + if needsChange { + needsChange = false + try dbPool.write { db in + try db.execute(sql: """ + INSERT INTO t DEFAULT VALUES; + DELETE FROM t; + """) + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! + } + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(observedCounts, [0, 0]) + } + } + + func testAllowedSnapshotOptimization() throws { + try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") + + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + // Allow pool to perform a single initial fetch, because between + // its first read access, and its write access that installs the + // transaction observer, no write did happen. + var needsChange = true + let observation = ValueObservation.tracking { db -> Int in + if needsChange { + needsChange = false + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { + try! dbPool.write { db in + try db.execute(sql: """ + INSERT INTO t DEFAULT VALUES; + """) + } + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! + } + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, [0, 1]) + } + } + // MARK: - Cancellation func testCancellableLifetime() throws { From 8b800ecbe113f9741d28a0f45df8c520027f72dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 13 Jun 2020 20:19:00 +0200 Subject: [PATCH 19/51] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 342f4f27c..13418907b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#795](https://github.com/groue/GRDB.swift/pull/795): **Breaking Change** Enhanced support for WAL Checkpoints - New: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement. +- Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. ## 5.0.0-beta.4 From 842846dbc4650e8a7023993a95560e5205384f60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 05:36:12 +0200 Subject: [PATCH 20/51] Documentation --- GRDB/Core/Database.swift | 24 +++++++++++++++++++++--- GRDB/Core/DatabasePool.swift | 10 +++++----- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index e2a18e103..169eacab3 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -487,15 +487,33 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Snapshots - /// Exposes sqlite3_snapshot_get. - /// /// Returns a snapshot that must be freed with `sqlite3_snapshot_free`. - func makeSnapshot() throws -> UnsafeMutablePointer { + /// + /// See https://www.sqlite.org/c3ref/snapshot.html + func takeVersionSnapshot() throws -> UnsafeMutablePointer { + // We have a linker/C-interop difficulty here: + // + // - Not all SQLite versions ship with the sqlite3_snapshot_get function. + // - Not all iOS/macOS versions ship a header that contains + // the declaration for sqlite3_snapshot_get(), even when SQLite is + // actually compiled with SQLITE_ENABLE_SNAPSHOT. + // + // This makes it really difficult to deal with system SQLite, custom + // SQLite builds, SQLCipher, and SPM. + // + // To avoid those problems, we add missing declarations, and sometimes + // shim implementations, in the following header files: + // + // - SQLiteCustom/grdb_config.h + // - Sources/CSQLite/shim.h + // - Support/grdb_config.h var snapshot: UnsafeMutablePointer? let code = withUnsafeMutablePointer(to: &snapshot) { sqlite3_snapshot_get(sqliteConnection, "main", $0) } guard code == SQLITE_OK else { + // Don't grab `lastErrorMessage`, because sqlite3_snapshot_get + // may be a shim (see above). throw DatabaseError(resultCode: code) } if let snapshot = snapshot { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index d2cee5042..3be9ed4a9 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -868,7 +868,7 @@ extension DatabasePool: DatabaseReader { if scheduler.immediateInitialValue() { do { - // Fetch the initial value without waiting for the writer. + // Fetch the initial value let initialValue = try unsafeReentrantRead(observer.fetchInitialValue) onChange(initialValue) @@ -894,7 +894,6 @@ extension DatabasePool: DatabaseReader { onError(error) } } else { - // Fetch the initial value without waiting for the writer. _weakAsyncRead { [weak self] dbResult in guard let dbResult = dbResult else { return } guard let self = self else { return } @@ -905,10 +904,11 @@ extension DatabasePool: DatabaseReader { // Grab a snaphot of the state of the database when we // perform the initial fetch. // - // Since not all SQLite version support snapshotting, + // Since not all SQLite versions support snapshotting, // ignore errors. - var initialSnapshot = try? db.makeSnapshot() + var initialSnapshot = try? db.takeVersionSnapshot() + // Fetch the initial value let initialValue = try observer.fetchInitialValue(db) observer.notifyChange(initialValue) @@ -932,7 +932,7 @@ extension DatabasePool: DatabaseReader { // database. If it did not change since // initial snapshot, then we do not need to // perform a second fetch. - if let secondSnapshot = try? db.makeSnapshot() { + if let secondSnapshot = try? db.takeVersionSnapshot() { // Compare snapshots let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) assert(cmp <= 0, "Unexpected snapshot ordering") From 0dee6425d1d81a5e6e489e4132c202b0cc50d250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 05:36:33 +0200 Subject: [PATCH 21/51] Fix free function --- GRDB/Core/DatabasePool.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 3be9ed4a9..75650ea0b 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -941,7 +941,7 @@ extension DatabasePool: DatabaseReader { } // Early free before the above defer { } - sqlite3_free(initialSnapshot) + sqlite3_snapshot_free(initialSnapshot) initialSnapshot = nil } From eacf48fef30cd1c262a337e7b5d9286c30920762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 06:34:08 +0200 Subject: [PATCH 22/51] More snapshot-based optimization of ValueObservation with DatabasePool This time, for the .immediate scheduler. --- GRDB/Core/Database.swift | 10 +++ GRDB/Core/DatabasePool.swift | 87 ++++++++++++-------- Tests/GRDBTests/ValueObservationTests.swift | 91 ++++++++++++++++++++- 3 files changed, 154 insertions(+), 34 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 169eacab3..ee5cfb156 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -523,6 +523,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } + func wasChanged(since initialSnapshot: UnsafeMutablePointer) throws -> Bool { + let secondSnapshot = try takeVersionSnapshot() + defer { + sqlite3_snapshot_free(secondSnapshot) + } + let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) + assert(cmp <= 0, "Unexpected snapshot ordering") + return cmp < 0 + } + // MARK: - Authorizer func withAuthorizer(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 75650ea0b..d46a01cc7 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -868,19 +868,55 @@ extension DatabasePool: DatabaseReader { if scheduler.immediateInitialValue() { do { - // Fetch the initial value - let initialValue = try unsafeReentrantRead(observer.fetchInitialValue) + // Grab a snapshot of the state of the database and perform + // the initial fetch. + var initialValue: Reducer.Value! + var initialSnapshot: UnsafeMutablePointer? + + try unsafeReentrantRead { db in + // Transaction is needed for snapshotting + if db.isInsideTransaction { + initialSnapshot = try? db.takeVersionSnapshot() + initialValue = try observer.fetchInitialValue(db) + } else { + try db.inTransaction(.deferred) { + initialSnapshot = try? db.takeVersionSnapshot() + initialValue = try observer.fetchInitialValue(db) + return .commit + } + } + } + onChange(initialValue) // Now wait for the writer _weakAsyncWriteWithoutTransaction { db in + defer { + if let initialSnapshot = initialSnapshot { + sqlite3_snapshot_free(initialSnapshot) + } + } + guard let db = db else { return } if observer.isCompleted { return } + do { - // Don't miss eventual changes between the - // initial fetch and the writer access. - if let value = try observer.fetchValue(db) { - observer.notifyChange(value) + // Transaction is needed for snapshotting + try db.inTransaction(.deferred) { + var fetchNeeded = true + if let initialSnapshot = initialSnapshot { + do { + fetchNeeded = try db.wasChanged(since: initialSnapshot) + } catch { + } + } + + // Don't miss eventual changes between the + // initial fetch and the writer access. + if fetchNeeded, let value = try observer.fetchValue(db) { + observer.notifyChange(value) + } + return .commit } // Now we can start observation @@ -898,18 +934,15 @@ extension DatabasePool: DatabaseReader { guard let dbResult = dbResult else { return } guard let self = self else { return } if observer.isCompleted { return } + do { let db = try dbResult.get() - // Grab a snaphot of the state of the database when we - // perform the initial fetch. - // - // Since not all SQLite versions support snapshotting, - // ignore errors. + // Grab a snapshot of the state of the database and perform + // the initial fetch. var initialSnapshot = try? db.takeVersionSnapshot() - - // Fetch the initial value let initialValue = try observer.fetchInitialValue(db) + observer.notifyChange(initialValue) // Now wait for the writer @@ -927,33 +960,23 @@ extension DatabasePool: DatabaseReader { // Transaction is needed for snapshotting try db.inTransaction(.deferred) { var fetchNeeded = true - if initialSnapshot != nil { - // Grab a snaphot of the current state of the - // database. If it did not change since - // initial snapshot, then we do not need to - // perform a second fetch. - if let secondSnapshot = try? db.takeVersionSnapshot() { - // Compare snapshots - let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) - assert(cmp <= 0, "Unexpected snapshot ordering") - fetchNeeded = cmp < 0 - sqlite3_snapshot_free(secondSnapshot) + if let initialSnapshot = initialSnapshot { + do { + fetchNeeded = try db.wasChanged(since: initialSnapshot) + } catch { } - - // Early free before the above defer { } - sqlite3_snapshot_free(initialSnapshot) - initialSnapshot = nil } + // Don't miss eventual changes between the + // initial fetch and the writer access. if fetchNeeded, let value = try observer.fetchValue(db) { observer.notifyChange(value) } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) - return .commit } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) } catch { observer.notifyErrorAndComplete(error) } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 44130bbab..47f43c207 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -99,7 +99,9 @@ class ValueObservationTests: GRDBTestCase { XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked } - func testDisallowedSnapshotOptimization() throws { + // MARK: - Snapshot Optimization + + func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") @@ -127,6 +129,7 @@ class ValueObservationTests: GRDBTestCase { var observedCounts: [Int] = [] let cancellable = observation.start( in: dbPool, + scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in observedCounts.append(count) @@ -138,7 +141,47 @@ class ValueObservationTests: GRDBTestCase { } } - func testAllowedSnapshotOptimization() throws { + func testDisallowedSnapshotOptimizationWithImmediateScheduler() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + // Force DatabasePool to perform two initial fetches, because between + // its first read access, and its write access that installs the + // transaction observer, some write did happen. + var needsChange = true + let observation = ValueObservation.tracking { db -> Int in + if needsChange { + needsChange = false + try dbPool.write { db in + try db.execute(sql: """ + INSERT INTO t DEFAULT VALUES; + DELETE FROM t; + """) + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! + } + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .immediate, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(observedCounts, [0, 0]) + } + } + + func testAllowedSnapshotOptimizationWithAsyncScheduler() throws { try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") let dbPool = try makeDatabasePool() @@ -169,6 +212,50 @@ class ValueObservationTests: GRDBTestCase { var observedCounts: [Int] = [] let cancellable = observation.start( in: dbPool, + scheduling: .async(onQueue: .main), + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, [0, 1]) + } + } + + func testAllowedSnapshotOptimizationWithImmediateScheduler() throws { + try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") + + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + // Allow pool to perform a single initial fetch, because between + // its first read access, and its write access that installs the + // transaction observer, no write did happen. + var needsChange = true + let observation = ValueObservation.tracking { db -> Int in + if needsChange { + needsChange = false + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { + try! dbPool.write { db in + try db.execute(sql: """ + INSERT INTO t DEFAULT VALUES; + """) + } + } + } + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! + } + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in observedCounts.append(count) From 510daa84a7b5a8928bdfdc43b2a79b21314e05c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 06:36:53 +0200 Subject: [PATCH 23/51] This is hard --- GRDB/Core/DatabasePool.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index d46a01cc7..0315b8362 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -866,6 +866,7 @@ extension DatabasePool: DatabaseReader { onError: onError, onChange: onChange) + // TODO: what about checkpoints that invalidate snapshots??? if scheduler.immediateInitialValue() { do { // Grab a snapshot of the state of the database and perform From 9215f88e7f4e0472771a08bcee889cfb3887c97e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 10:47:27 +0200 Subject: [PATCH 24/51] Documentation, cleanup, and checkpoint prevention --- GRDB/Core/DatabasePool.swift | 199 ++++++++++++++----------------- GRDB/Core/DatabaseSnapshot.swift | 9 +- 2 files changed, 98 insertions(+), 110 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 0315b8362..94abe37b2 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -866,131 +866,112 @@ extension DatabasePool: DatabaseReader { onError: onError, onChange: onChange) - // TODO: what about checkpoints that invalidate snapshots??? + // Starting a concurrent observation means that we'll fetch the initial + // value right away, without waiting for an access to the writer queue, + // and the opportunity to install a transaction observer. + // + // This is how DatabasePool can start an observation and promptly notify + // an initial value, even when there is a long-running write transaction + // in the background. + // + // We thus have to deal with the fact that between this initial fetch, + // and the beginning of transaction tracking, any number of untracked + // writes may occur. + // + // We must notify changes that happen during this untracked window. But + // how do we spot them, since we're not tracking database changes yet? + // + // A safe solution is to always perform a second fetch. We may fetch the + // same initial value, if no change did happen. But we don't miss + // possible changes. + // + // We can avoid this second fetch when SQLite is compiled with the + // SQLITE_ENABLE_SNAPSHOT option: + // + // 1. Perform the initial fetch in a DatabaseSnapshot. The snapshot + // acquires a lock that will prevent checkpointing until we get a writer + // access, so that we can reliably compare database versions with + // `sqlite3_snapshot`: https://www.sqlite.org/c3ref/snapshot.html. + // + // 2. Get a writer access, and compare the versions of the initial + // snapshot, and the current state of the database: if versions are + // identical, we can avoid the second fetch. If they are not, we perform + // the second fetch, even if the actual changes are unrelated to the + // tracked database region (we have no way to know). + // + // 3. Install the transaction observer. + if scheduler.immediateInitialValue() { do { - // Grab a snapshot of the state of the database and perform - // the initial fetch. - var initialValue: Reducer.Value! - var initialSnapshot: UnsafeMutablePointer? - - try unsafeReentrantRead { db in - // Transaction is needed for snapshotting - if db.isInsideTransaction { - initialSnapshot = try? db.takeVersionSnapshot() - initialValue = try observer.fetchInitialValue(db) - } else { - try db.inTransaction(.deferred) { - initialSnapshot = try? db.takeVersionSnapshot() - initialValue = try observer.fetchInitialValue(db) - return .commit - } - } - } - + let initialSnapshot = try makeSnapshot() + let initialValue = try initialSnapshot.read(observer.fetchInitialValue) onChange(initialValue) - - // Now wait for the writer - _weakAsyncWriteWithoutTransaction { db in - defer { - if let initialSnapshot = initialSnapshot { - sqlite3_snapshot_free(initialSnapshot) - } - } - - guard let db = db else { return } - if observer.isCompleted { return } - - do { - // Transaction is needed for snapshotting - try db.inTransaction(.deferred) { - var fetchNeeded = true - if let initialSnapshot = initialSnapshot { - do { - fetchNeeded = try db.wasChanged(since: initialSnapshot) - } catch { - } - } - - // Don't miss eventual changes between the - // initial fetch and the writer access. - if fetchNeeded, let value = try observer.fetchValue(db) { - observer.notifyChange(value) - } - return .commit - } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - observer.notifyErrorAndComplete(error) - } - } + add(observer: observer, from: initialSnapshot) } catch { observer.cancel() onError(error) } } else { - _weakAsyncRead { [weak self] dbResult in - guard let dbResult = dbResult else { return } - guard let self = self else { return } - if observer.isCompleted { return } - - do { - let db = try dbResult.get() + let label = configuration.identifier( + defaultLabel: "GRDB.DatabasePool", + purpose: "ValueObservation") + configuration + .makeDispatchQueue(label: label) + .async { [weak self] in + guard let self = self else { return } + if observer.isCompleted { return } - // Grab a snapshot of the state of the database and perform - // the initial fetch. - var initialSnapshot = try? db.takeVersionSnapshot() - let initialValue = try observer.fetchInitialValue(db) - - observer.notifyChange(initialValue) - - // Now wait for the writer - self._weakAsyncWriteWithoutTransaction { db in - defer { - if let initialSnapshot = initialSnapshot { - sqlite3_snapshot_free(initialSnapshot) - } - } - - guard let db = db else { return } - if observer.isCompleted { return } - - do { - // Transaction is needed for snapshotting - try db.inTransaction(.deferred) { - var fetchNeeded = true - if let initialSnapshot = initialSnapshot { - do { - fetchNeeded = try db.wasChanged(since: initialSnapshot) - } catch { - } - } - - // Don't miss eventual changes between the - // initial fetch and the writer access. - if fetchNeeded, let value = try observer.fetchValue(db) { - observer.notifyChange(value) - } - return .commit - } - - // Now we can start observation - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - observer.notifyErrorAndComplete(error) - } + do { + let initialSnapshot = try self.makeSnapshot() + let initialValue = try initialSnapshot.read(observer.fetchInitialValue) + observer.notifyChange(initialValue) + self.add(observer: observer, from: initialSnapshot) + } catch { + observer.notifyErrorAndComplete(error) } - } catch { - observer.notifyErrorAndComplete(error) - } } } return observer } + // Support for _addConcurrent(observation:) + private func add( + observer: ValueObserver, + from initialSnapshot: DatabaseSnapshot) + { + _weakAsyncWriteWithoutTransaction { db in + guard let db = db else { return } + if observer.isCompleted { return } + + do { + // Transaction is needed for version snapshotting + try db.inTransaction(.deferred) { + var fetchNeeded = true + withExtendedLifetime(initialSnapshot) { + if let initialVersion = initialSnapshot.version { + do { + fetchNeeded = try db.wasChanged(since: initialVersion) + } catch { + // ignore: we'll just re-fetch + } + } + } + + if fetchNeeded, let value = try observer.fetchValue(db) { + observer.notifyChange(value) + } + return .commit + } + + // Now we can start observation + db.add(transactionObserver: observer, extent: .observerLifetime) + } catch { + observer.notifyErrorAndComplete(error) + } + } + } + // MARK: - Custom FTS5 Tokenizers #if SQLITE_ENABLE_FTS5 diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 483b8de79..85175047f 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -14,6 +14,9 @@ public class DatabaseSnapshot: DatabaseReader { serializedDatabase.configuration } + /// Not nil iff SQLite was compiled with `SQLITE_ENABLE_SNAPSHOT`. + private(set) var version: UnsafeMutablePointer? + init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = configuration configuration.readonly = true @@ -33,12 +36,16 @@ public class DatabaseSnapshot: DatabaseReader { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } try db.beginSnapshotTransaction() + version = try? db.takeVersionSnapshot() } } deinit { // Leave snapshot isolation - serializedDatabase.sync { db in + serializedDatabase.reentrantSync { db in + if let version = version { + sqlite3_snapshot_free(version) + } try? db.commit() } } From ec0e8672beaba533d3a25c3f4c6bda4826993ac8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 11:03:24 +0200 Subject: [PATCH 25/51] Documentation, cleanup --- GRDB/Core/DatabasePool.swift | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 94abe37b2..9896121cc 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -947,14 +947,23 @@ extension DatabasePool: DatabaseReader { do { // Transaction is needed for version snapshotting try db.inTransaction(.deferred) { - var fetchNeeded = true - withExtendedLifetime(initialSnapshot) { - if let initialVersion = initialSnapshot.version { - do { - fetchNeeded = try db.wasChanged(since: initialVersion) - } catch { - // ignore: we'll just re-fetch - } + // Keep DatabaseSnaphot alive until we have compared + // database versions. It prevents database checkpointing, + // and keeps versions (`sqlite3_snapshot`) valid + // and comparable. + let fetchNeeded: Bool = withExtendedLifetime(initialSnapshot) { + // Version is nil if SQLite is not compiled with + // SQLITE_ENABLE_SNAPSHOT, or if the DatabaseSnaphot + // could not grab its version. In this case, we don't + // care, and just fetch a fresh value. + guard let initialVersion = initialSnapshot.version else { + return true + } + do { + return try db.wasChanged(since: initialVersion) + } catch { + // ignore: we'll just re-fetch + return true } } From 70714768d915e0bb87c897cd2403170d1d3c54bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 13:39:24 +0200 Subject: [PATCH 26/51] Always use snapshots apis through grdb_xxx shims --- CHANGELOG.md | 2 +- GRDB.swift.podspec | 2 +- GRDB/Core/Database.swift | 28 ++--- GRDB/Core/DatabaseSnapshot.swift | 2 +- SQLiteCustom/grdb_config.h | 52 ++++++++- Sources/CSQLite/shim.h | 73 +++++++++++-- Support/SQLCipher_config.h | 93 ++++++++++++++++ Support/grdb_config.h | 77 +++++++++---- Tests/GRDBTests/ValueObservationTests.swift | 113 ++++++++++++++------ 9 files changed, 349 insertions(+), 93 deletions(-) create mode 100644 Support/SQLCipher_config.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 13418907b..8e691c005 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,7 +72,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#795](https://github.com/groue/GRDB.swift/pull/795): **Breaking Change** Enhanced support for WAL Checkpoints - New: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement. -- Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. +- 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. ## 5.0.0-beta.4 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 3eedb8337..fe5d05ec4 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -23,7 +23,7 @@ Pod::Spec.new do |s| end s.subspec 'SQLCipher' do |ss| - ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h' + ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h' ss.framework = 'Foundation' ss.dependency 'SQLCipher', '>= 3.4.0' ss.xcconfig = { diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ee5cfb156..b277b177b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -487,33 +487,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Snapshots - /// Returns a snapshot that must be freed with `sqlite3_snapshot_free`. + /// Returns a snapshot that must be freed with `grdb_snapshot_free`. /// /// See https://www.sqlite.org/c3ref/snapshot.html func takeVersionSnapshot() throws -> UnsafeMutablePointer { - // We have a linker/C-interop difficulty here: - // - // - Not all SQLite versions ship with the sqlite3_snapshot_get function. - // - Not all iOS/macOS versions ship a header that contains - // the declaration for sqlite3_snapshot_get(), even when SQLite is - // actually compiled with SQLITE_ENABLE_SNAPSHOT. - // - // This makes it really difficult to deal with system SQLite, custom - // SQLite builds, SQLCipher, and SPM. - // - // To avoid those problems, we add missing declarations, and sometimes - // shim implementations, in the following header files: - // - // - SQLiteCustom/grdb_config.h - // - Sources/CSQLite/shim.h - // - Support/grdb_config.h var snapshot: UnsafeMutablePointer? let code = withUnsafeMutablePointer(to: &snapshot) { - sqlite3_snapshot_get(sqliteConnection, "main", $0) + grdb_snapshot_get(sqliteConnection, "main", $0) } guard code == SQLITE_OK else { - // Don't grab `lastErrorMessage`, because sqlite3_snapshot_get - // may be a shim (see above). + // Don't grab `lastErrorMessage`, because grdb_snapshot_get may be a + // shim that does not call the missing sqlite3_snapshot_get. throw DatabaseError(resultCode: code) } if let snapshot = snapshot { @@ -526,9 +510,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib func wasChanged(since initialSnapshot: UnsafeMutablePointer) throws -> Bool { let secondSnapshot = try takeVersionSnapshot() defer { - sqlite3_snapshot_free(secondSnapshot) + grdb_snapshot_free(secondSnapshot) } - let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot) + let cmp = grdb_snapshot_cmp(initialSnapshot, secondSnapshot) assert(cmp <= 0, "Unexpected snapshot ordering") return cmp < 0 } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 85175047f..636d9df75 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -44,7 +44,7 @@ public class DatabaseSnapshot: DatabaseReader { // Leave snapshot isolation serializedDatabase.reentrantSync { db in if let version = version { - sqlite3_snapshot_free(version) + grdb_snapshot_free(version) } try? db.commit() } diff --git a/SQLiteCustom/grdb_config.h b/SQLiteCustom/grdb_config.h index 860796fbd..fce1c888d 100644 --- a/SQLiteCustom/grdb_config.h +++ b/SQLiteCustom/grdb_config.h @@ -28,17 +28,59 @@ static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif -/* Expose missing APIs for easier GRDB development*/ -#ifndef SQLITE_ENABLE_SNAPSHOT -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( +/* + Snapshots + ========= + + We have a linker/C-interop difficulty here: + + - Not all SQLite versions ship with the sqlite3_snapshot_get function. + - Not all iOS/macOS versions ship a header that contains + the declaration for sqlite3_snapshot_get(), even when SQLite is + actually compiled with SQLITE_ENABLE_SNAPSHOT. + + This makes it really difficult to deal with system SQLite, custom + SQLite builds, SQLCipher, and SPM. + + To avoid those problems, we add grdb_snapshot_xxx shim functions in the + following header files: + + - SQLiteCustom/grdb_config.h + - Sources/CSQLite/shim.h + - Support/grdb_config.h + */ +#ifdef SQLITE_ENABLE_SNAPSHOT +static inline int grdb_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return sqlite3_snapshot_get(db, zSchema, ppSnapshot); +} + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { + sqlite3_snapshot_free(ppSnapshot); +} + +static inline int grdb_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return sqlite3_snapshot_cmp(p1, p2); +} +#else +static inline int grdb_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot) { return SQLITE_MISUSE; } -SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot* ppSnapshot) { } -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { +} + +static inline int grdb_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2) { diff --git a/Sources/CSQLite/shim.h b/Sources/CSQLite/shim.h index d08d75324..76fbfa496 100644 --- a/Sources/CSQLite/shim.h +++ b/Sources/CSQLite/shim.h @@ -27,26 +27,81 @@ static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif -/* Expose missing APIs for easier GRDB development*/ -#ifndef SQLITE_ENABLE_SNAPSHOT -/* Expose APIs that are missing from system */ +/* + Snapshots + ========= + + We have a linker/C-interop difficulty here: + + - Not all SQLite versions ship with the sqlite3_snapshot_get function. + - Not all iOS/macOS versions ship a header that contains + the declaration for sqlite3_snapshot_get(), even when SQLite is + actually compiled with SQLITE_ENABLE_SNAPSHOT. + + This makes it really difficult to deal with system SQLite, custom + SQLite builds, SQLCipher, and SPM. + + To avoid those problems, we add grdb_snapshot_xxx shim functions in the + following header files: + + - SQLiteCustom/grdb_config.h + - Sources/CSQLite/shim.h + - Support/grdb_config.h + */ +#ifdef SQLITE_ENABLE_SNAPSHOT +static inline int grdb_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return sqlite3_snapshot_get(db, zSchema, ppSnapshot); +} + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { + sqlite3_snapshot_free(ppSnapshot); +} + +static inline int grdb_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return sqlite3_snapshot_cmp(p1, p2); +} +#else +// Assume snapshot apis *are* defined, but not exposed. typedef struct sqlite3_snapshot { unsigned char hidden[48]; } sqlite3_snapshot; + SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( - sqlite3 *db, - const char *zSchema, - sqlite3_snapshot *pSnapshot -); + SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); + SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); + +static inline int grdb_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return sqlite3_snapshot_get(db, zSchema, ppSnapshot); +} + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { + sqlite3_snapshot_free(ppSnapshot); +} + +static inline int grdb_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return sqlite3_snapshot_cmp(p1, p2); +} #endif /* SQLITE_ENABLE_SNAPSHOT */ diff --git a/Support/SQLCipher_config.h b/Support/SQLCipher_config.h new file mode 100644 index 000000000..9942c1bae --- /dev/null +++ b/Support/SQLCipher_config.h @@ -0,0 +1,93 @@ +#ifndef grdb_config_h +#define grdb_config_h + +#include + +typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); + +/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic +/// function that can't be used from Swift. +static inline void registerErrorLogCallback(errorLogCallback callback) { + sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); +} + +#if SQLITE_VERSION_NUMBER >= 3029000 +/// Wrapper around sqlite3_db_config() which is a variadic function that can't +/// be used from Swift. +static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); +} + +/// Wrapper around sqlite3_db_config() which is a variadic function that can't +/// be used from Swift. +static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0); + sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0); +} +#else +static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } +#endif + +/* + Snapshots + ========= + + We have a linker/C-interop difficulty here: + + - Not all SQLite versions ship with the sqlite3_snapshot_get function. + - Not all iOS/macOS versions ship a header that contains + the declaration for sqlite3_snapshot_get(), even when SQLite is + actually compiled with SQLITE_ENABLE_SNAPSHOT. + + This makes it really difficult to deal with system SQLite, custom + SQLite builds, SQLCipher, and SPM. + + To avoid those problems, we add grdb_snapshot_xxx shim functions in the + following header files: + + - SQLiteCustom/grdb_config.h + - Sources/CSQLite/shim.h + - Support/grdb_config.h + */ +#ifdef SQLITE_ENABLE_SNAPSHOT +static inline int grdb_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return sqlite3_snapshot_get(db, zSchema, ppSnapshot); +} + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { + sqlite3_snapshot_free(ppSnapshot); +} + +static inline int grdb_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return sqlite3_snapshot_cmp(p1, p2); +} +#else +static inline int grdb_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return SQLITE_MISUSE; +} + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { +} + +static inline int grdb_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return 0; +} +#endif /* SQLITE_ENABLE_SNAPSHOT */ + +#endif /* grdb_config_h */ diff --git a/Support/grdb_config.h b/Support/grdb_config.h index 28547f01a..ad42371d1 100644 --- a/Support/grdb_config.h +++ b/Support/grdb_config.h @@ -1,11 +1,7 @@ #ifndef grdb_config_h #define grdb_config_h -#ifdef GRDBCIPHER - #include -#else - #include -#endif +#include typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); @@ -55,45 +51,82 @@ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); #endif /* GRDB_SQLITE_ENABLE_PREUPDATE_HOOK */ -/* Expose missing APIs for easier GRDB development*/ -#ifndef SQLITE_ENABLE_SNAPSHOT -#ifdef GRDBCIPHER -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( +/* + Snapshots + ========= + + We have a linker/C-interop difficulty here: + + - Not all SQLite versions ship with the sqlite3_snapshot_get function. + - Not all iOS/macOS versions ship a header that contains + the declaration for sqlite3_snapshot_get(), even when SQLite is + actually compiled with SQLITE_ENABLE_SNAPSHOT. + + This makes it really difficult to deal with system SQLite, custom + SQLite builds, SQLCipher, and SPM. + + To avoid those problems, we add grdb_snapshot_xxx shim functions in the + following header files: + + - SQLiteCustom/grdb_config.h + - Sources/CSQLite/shim.h + - Support/grdb_config.h + */ +#ifdef SQLITE_ENABLE_SNAPSHOT +static inline int grdb_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot) { - return SQLITE_MISUSE; + return sqlite3_snapshot_get(db, zSchema, ppSnapshot); } -SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot* ppSnapshot) { } -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { + sqlite3_snapshot_free(ppSnapshot); +} + +static inline int grdb_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2) { - return 0; + return sqlite3_snapshot_cmp(p1, p2); } #else -/* Expose APIs that are missing from system */ +// Assume snapshot apis *are* defined, but not exposed. typedef struct sqlite3_snapshot { unsigned char hidden[48]; } sqlite3_snapshot; + SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( - sqlite3 *db, - const char *zSchema, - sqlite3_snapshot *pSnapshot -); + SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); + SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); -#endif -#endif /* SQLITE_ENABLE_SNAPSHOT */ +static inline int grdb_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot) +{ + return sqlite3_snapshot_get(db, zSchema, ppSnapshot); +} + +static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) { + sqlite3_snapshot_free(ppSnapshot); +} + +static inline int grdb_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2) +{ + return sqlite3_snapshot_cmp(p1, p2); +} +#endif /* SQLITE_ENABLE_SNAPSHOT */ #endif /* grdb_config_h */ diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 47f43c207..f51a26416 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -101,6 +101,23 @@ class ValueObservationTests: GRDBTestCase { // MARK: - Snapshot Optimization + private func isSnapshotEnabled(_ dbPool: DatabasePool) throws -> Bool { + // Testing Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT") + // is... not enough: on iOS 10.3.1, SQLITE_ENABLE_SNAPSHOT is not + // exposed, and yet, sqlite3_snaphost_get() works :shrug: + // + // So let's perform a runtime check: + try dbPool.read { db in + do { + let version = try db.takeVersionSnapshot() + grdb_snapshot_free(version) + return true + } catch { + return false + } + } + } + func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in @@ -182,8 +199,6 @@ class ValueObservationTests: GRDBTestCase { } func testAllowedSnapshotOptimizationWithAsyncScheduler() throws { - try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") - let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") @@ -207,26 +222,42 @@ class ValueObservationTests: GRDBTestCase { return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! } - let expectation = self.expectation(description: "") - expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] - let cancellable = observation.start( - in: dbPool, - scheduling: .async(onQueue: .main), - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - observedCounts.append(count) - expectation.fulfill() - }) - withExtendedLifetime(cancellable) { - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 1]) + if try isSnapshotEnabled(dbPool) { + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .async(onQueue: .main), + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, [0, 1]) + } + } else { + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 3 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .async(onQueue: .main), + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, [0, 0, 1]) + } } } func testAllowedSnapshotOptimizationWithImmediateScheduler() throws { - try XCTSkipUnless(Database.sqliteCompileOptions.contains("ENABLE_SNAPSHOT"), "Snapshots not enabled") - let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") @@ -250,20 +281,38 @@ class ValueObservationTests: GRDBTestCase { return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")! } - let expectation = self.expectation(description: "") - expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] - let cancellable = observation.start( - in: dbPool, - scheduling: .immediate, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - observedCounts.append(count) - expectation.fulfill() - }) - withExtendedLifetime(cancellable) { - waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 1]) + if try isSnapshotEnabled(dbPool) { + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .immediate, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, [0, 1]) + } + } else { + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 3 + var observedCounts: [Int] = [] + let cancellable = observation.start( + in: dbPool, + scheduling: .immediate, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { count in + observedCounts.append(count) + expectation.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 2, handler: nil) + XCTAssertEqual(observedCounts, [0, 0, 1]) + } } } From 7068a4f14953818c1a71eb4e5f958824800608cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 17:03:24 +0200 Subject: [PATCH 27/51] Update the demo app for better alignment with "Good Practices for Designing Record Types" --- CHANGELOG.md | 4 + .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 123 ++++++++++++++++-- .../GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 11 +- .../GRDBDemoiOS/GRDBDemoiOS/Player.swift | 46 ++++--- .../PlayerEditionViewController.swift | 5 +- .../GRDBDemoiOS/PlayersViewController.swift | 82 +++--------- Documentation/DemoApps/GRDBDemoiOS/README.md | 7 +- 7 files changed, 178 insertions(+), 100 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e691c005..c0506685f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - 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. +### 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. + ## 5.0.0-beta.4 diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 0aa715f38..cc5ba1e1f 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -1,26 +1,123 @@ 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 } + // MARK: - Database Access: Writes + + /// Saves (insert or update) a player in the database + func savePlayer(_ player: inout Player) throws { + try dbQueue.write { db in + try player.save(db) + } + } + + /// Deletes one player + func deletePlayer(_ player: Player) throws { + try dbQueue.write { db in + _ = try player.delete(db) + } + } + + /// Deletes all players + func deleteAllPlayers() throws { + try dbQueue.write { db in + _ = try Player.deleteAll(db) + } + } + + /// Refreshes 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: - Database Access: Reads + + /// Tracks changes in the number of players + func observePlayerCount( + onError: @escaping (Error) -> Void, + onChange: @escaping (Int) -> Void) + -> DatabaseCancellable + { + ValueObservation + .tracking { db in try Player.fetchCount(db) } + .start( + in: dbQueue, + scheduling: .immediate, + onError: onError, + onChange: onChange) + } + + /// Tracks changes in players ordered by name + func observePlayersOrderedByName( + onError: @escaping (Error) -> Void, + onChange: @escaping ([Player]) -> Void) + -> DatabaseCancellable + { + ValueObservation + .tracking { db in try Player.all().orderedByName().fetchAll(db) } + .start( + in: dbQueue, + scheduling: .immediate, + onError: onError, + onChange: onChange) + } + + /// Tracks changes in players ordered by score + func observePlayersOrderedByScore( + onError: @escaping (Error) -> Void, + onChange: @escaping ([Player]) -> Void) + -> DatabaseCancellable + { + ValueObservation + .tracking { db in try Player.all().orderedByScore().fetchAll(db) } + .start( + in: dbQueue, + scheduling: .immediate, + onError: onError, + onChange: onChange) + } + + // MARK: - Private + /// 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 diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 3df9947f3..d863c8c41 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 chosing 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/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 57994da4f..f786ff067 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -1,23 +1,23 @@ import GRDB -// A plain Player struct +/// The Player struct struct Player { - // Prefer Int64 for auto-incremented database ids - var id: Int64? + var id: Int64? // Use Int64 for auto-incremented database ids var name: String var score: Int } -// Hashable conformance supports tableView diffing +/// Hashable conformance supports tableView diffing extension Player: Hashable { } // MARK: - Persistence -// Turn Player into a Codable Record. -// See https://github.com/groue/GRDB.swift/blob/master/README.md#records +/// Make Player a Codable Record. +/// +/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records extension Player: Codable, FetchableRecord, MutablePersistableRecord { // Define database columns from CodingKeys - private enum Columns { + fileprivate enum Columns { static let id = Column(CodingKeys.id) static let name = Column(CodingKeys.name) static let score = Column(CodingKeys.score) @@ -29,17 +29,33 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { } } -// MARK: - Database access +// MARK: - Player Requests -// Define some useful player requests. -// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests -extension Player { - static func orderedByName() -> QueryInterfaceRequest { - Player.order(Columns.name) +/// Define some player requests used by the application. +/// +/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests +/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md +extension DerivableRequest where RowDecoder == Player { + /// A request of players ordered by name + /// + /// For example: + /// + /// let players = try dbQueue.read { db in + /// try Player.all().orderedByName().fetchAll(db) + /// } + func orderedByName() -> Self { + order(Player.Columns.name) } - static func orderedByScore() -> QueryInterfaceRequest { - Player.order(Columns.score.desc, Columns.name) + /// A request of players ordered by score + /// + /// For example: + /// + /// let players = try dbQueue.read { db in + /// try Player.all().orderedByScore().fetchAll(db) + /// } + func orderedByScore() -> Self { + order(Player.Columns.score.desc, Player.Columns.name) } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift index cd8eb1bcd..f59459f20 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift @@ -112,10 +112,7 @@ extension PlayerEditionViewController: UITextFieldDelegate { } player.name = nameTextField.text ?? "" player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 + try! appDatabase.savePlayer(&player) self.player = player - - try! dbQueue.inDatabase { db in - try player.save(db) - } } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index 950fdbf57..743d3b250 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -18,14 +18,6 @@ class PlayersViewController: UITableViewController { configureTableView() } } - private var playersRequest: QueryInterfaceRequest { - switch playerOrdering { - case .byName: - return Player.orderedByName() - case .byScore: - return Player.orderedByScore() - } - } override func viewDidLoad() { super.viewDidLoad() @@ -71,13 +63,7 @@ class PlayersViewController: UITableViewController { } private func configureTitle() { - // Track changes in the number of players - let observation = ValueObservation.tracking { db in - try Player.fetchCount(db) - } - playerCountCancellable = observation.start( - in: dbQueue, - scheduling: .immediate, + playerCountCancellable = appDatabase.observePlayerCount( onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] count in guard let self = self else { return } @@ -90,19 +76,22 @@ class PlayersViewController: UITableViewController { } private func configureTableView() { - // Track changes in the list of players - let request = self.playersRequest - let observation = ValueObservation.tracking { db in - try request.fetchAll(db) + switch playerOrdering { + case .byName: + playersCancellable = appDatabase.observePlayersOrderedByName( + onError: { error in fatalError("Unexpected error: \(error)") }, + onChange: { [weak self] players in + guard let self = self else { return } + self.updateTableView(players) + }) + case .byScore: + playersCancellable = appDatabase.observePlayersOrderedByScore( + onError: { error in fatalError("Unexpected error: \(error)") }, + onChange: { [weak self] players in + guard let self = self else { return } + self.updateTableView(players) + }) } - playersCancellable = observation.start( - in: dbQueue, - scheduling: .immediate, - onError: { error in fatalError("Unexpected error: \(error)") }, - onChange: { [weak self] players in - guard let self = self else { return } - self.updateTableView(players) - }) } private func updateTableView(_ players: [Player]) { @@ -187,9 +176,7 @@ extension PlayersViewController { override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Delete the player let player = players[indexPath.row] - try! dbQueue.write { db in - _ = try player.delete(db) - } + try! appDatabase.deletePlayer(player) } private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { @@ -219,48 +206,19 @@ extension PlayersViewController { @IBAction func deletePlayers() { setEditing(false, animated: true) - try! dbQueue.write { db in - _ = try Player.deleteAll(db) - } + try! appDatabase.deleteAllPlayers() } @IBAction func refresh() { setEditing(false, animated: true) - refreshPlayers() + try! appDatabase.refreshPlayers() } @IBAction func stressTest() { setEditing(false, animated: true) for _ in 0..<50 { DispatchQueue.global().async { - self.refreshPlayers() - } - } - } - - private func refreshPlayers() { - 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() { - player.score = Player.randomScore() - try player.update(db) - } + try! appDatabase.refreshPlayers() } } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md index 59a415eee..a27039665 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -8,6 +8,7 @@ Demo Application - how to setup a database in an iOS app - how to define a simple [Codable Record](../../../README.md#codable-records) - how to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation). +- how to apply the recommendedations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). **Files of interest:** @@ -17,15 +18,15 @@ Demo Application - [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift) - `AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema. + `AppDatabase` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes. - [Player.swift](GRDBDemoiOS/Player.swift) - `Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). + `Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application. - [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift) - `PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../../README.md#valueobservation). + `PlayersViewController` displays a list of players. - [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift) From 0f70af7a22418562ada0c902cf222e2deb183b42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 17:05:56 +0200 Subject: [PATCH 28/51] Fix typo --- Documentation/DemoApps/GRDBDemoiOS/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md index a27039665..a97756497 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -5,10 +5,10 @@ Demo Application **This demo application shows you:** -- how to setup a database in an iOS app -- how to define a simple [Codable Record](../../../README.md#codable-records) -- how to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation). -- how to apply the recommendedations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). +- How to setup a database in an iOS app. +- How to define a simple [Codable Record](../../../README.md#codable-records). +- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation). +- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md). **Files of interest:** From cf9b9206bdbcd18e5af37dff0ac95c944f20101b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 17:06:36 +0200 Subject: [PATCH 29/51] Fix typo --- .../DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index d863c8c41..834856c3e 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -14,7 +14,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } private func setupDatabase(_ application: UIApplication) throws { - // AppDelegate is responsible for chosing the location of the database file. + // 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) From ffe40dbf7937fa29bd9677bcfac0172a9f804b73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 17:10:24 +0200 Subject: [PATCH 30/51] Fix indentation --- .../GRDBDemoiOS/PlayersViewController.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index 743d3b250..dedcc3e09 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -81,16 +81,16 @@ class PlayersViewController: UITableViewController { playersCancellable = appDatabase.observePlayersOrderedByName( onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] players in - guard let self = self else { return } - self.updateTableView(players) - }) + guard let self = self else { return } + self.updateTableView(players) + }) case .byScore: playersCancellable = appDatabase.observePlayersOrderedByScore( onError: { error in fatalError("Unexpected error: \(error)") }, onChange: { [weak self] players in - guard let self = self else { return } - self.updateTableView(players) - }) + guard let self = self else { return } + self.updateTableView(players) + }) } } From 023a04aff9045e4e87aa3f0007f1bc4873e37058 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:25:22 +0200 Subject: [PATCH 31/51] Associations FAQ --- Documentation/AssociationsBasics.md | 2 + README.md | 157 +++++++++++++++++++++++++++- 2 files changed, 157 insertions(+), 2 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index d21cf4f71..1470225b2 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -39,6 +39,7 @@ GRDB Associations - [Aggregate Operations] - [Isolation of Multiple Aggregates] - [DerivableRequest Protocol] +- **[FAQ]** - [Known Issues] @@ -2468,3 +2469,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/README.md b/README.md index 76b27c4c5..b155ecf87 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,8 @@ Documentation **GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). +#### [FAQ] + #### Reference - [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) @@ -313,7 +315,7 @@ Documentation - :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) -**[FAQ](#faq)** +**[FAQ]** **[Sample Code](#sample-code)** @@ -7278,17 +7280,36 @@ try writer.asyncWriteWithoutTransaction { db in FAQ === +**[FAQ: Opening Connections](#faq-opening-connections)** + - [How do I create a database in my application?](#how-do-i-create-a-database-in-my-application) - [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) - [How do I close a database connection?](#how-do-i-close-a-database-connection) + +**[FAQ: SQL](#faq-sql)** + - [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) + +**[FAQ: General](#faq-general)** + - [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution) +- [What Are Experimental Features?](#what-are-experimental-features) + +**[FAQ: Associations](#faq-associations)** + +- [How to I filter records and only keep those that are associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) +- [How to I filter records and only keep those that are NOT associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) +- [How to I select only one column of an associated record?](#how-to-i-select-only-one-column-of-an-associated-record) + +**[FAQ: Errors](#faq-errors)** + - [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred) - [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized) - [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries) -- [What Are Experimental Features?](#what-are-experimental-features) +## FAQ: Opening Connections + ### How do I create a database in my application? This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) instead. @@ -7337,6 +7358,8 @@ Database connections are managed by [database queues](#database-queues) and [poo Database accesses that run in background threads postpone the closing of connections. +## FAQ: SQL + ### How do I print a request as SQL? When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed. @@ -7382,6 +7405,8 @@ db.trace { event in > :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. +## FAQ: General + ### How do I monitor the duration of database statements execution? Use the `trace(options:_:)` method, with the `.profile` option: @@ -7408,6 +7433,133 @@ try dbQueue.read { db in ``` +## FAQ: Associations + +### How to I filter records and only keep those that are associated to another record? + +Let's say you have two record types, `Book` and `Author`, and you want to only fetch books that have an author, and discard anonymous books. + +We start by defining the association between books and authors: + +```swift +struct Book: TableRecord { + ... + let author = belongsTo(Author.self) +} +struct Author: TableRecord { + ... +} +``` + +And then we can write our request and only fetch books that have an author, discarding anonymous ones: + +```swift +let books: [Book] = try dbQueue.read { db in + // SELECT book.* FROM book + // JOIN author ON author.id = book.authorID + let request = Book.joining(required: Book.author) + return try request.fetchAll(db) +} +``` + +Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on book columns. Instead, we just need to express that it is "required that a book can be joined to its author". + +See [How to I filter records and only keep those that are NOT associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question. + + +### How to I filter records and only keep those that are NOT associated to another record? + +Let's say you have two record types, `Book` and `Author`, and you want to only fetch anonymous books that do not have any author. + +We start by defining the association between books and authors: + +```swift +struct Book: TableRecord { + ... + let author = belongsTo(Author.self) +} +struct Author: TableRecord { + ... +} +``` + +And then we can write our request and only fetch anonymous books that have an author: + +```swift +let books: [Book] = try dbQueue.read { db in + // SELECT book.* FROM book + // LEFT JOIN author ON author.id = book.authorID + // WHERE author.rowid IS NULL + let authorAlias = TableAlias() + let request = Book + .joining(optional: Book.author.aliased(authorAlias)) + .filter(authorAlias[Column.rowID] == nil) + return try request.fetchAll(db) +} +``` + +This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure that their `Column.rowID` (another name for their primary key) is nil, which is another way to say it does not exist: the book has no author. + +See [How to I filter records and only keep those that are associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) above for the opposite question. + + +### How to I select only one column of an associated record? + +Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full author records: + +We start by defining the association between books and authors: + +```swift +struct Book: Decodable, TableRecord { + ... + let author = belongsTo(Author.self) +} +struct Author: TableRecord { + ... + enum Columns { + static let name = Column(CodingKeys.name) + } +} +``` + +And then we can write our request and the ad-hoc record that decodes it: + +```swift +struct BookInfo: Decodable, FetchableRecord { + var book: Book + var authorName: String? // nil when the book is anonymous + + static func all() -> QueryInterfaceRequest { + // SELECT book.*, author.name AS authorName + // FROM book + // LEFT JOIN author ON author.id = book.authorID + let authorAlias = TableAlias() + let authorName = authorAlias[Author.Columns.name].forKey(CodingKeys.authorName) + return Book + .annotated(with: authorName) + .joining(optional: Book.author.aliased(authorAlias)) + .asRequest(of: BookInfo.self) + } +} + +let bookInfos: [BookInfo] = try dbQueue.read { db in + BookInfo.all().fetchAll(db) +} +``` + +By using a TableAlias, you can refer to an author column from a request of books. + +By defining the request as a static method of BookInfo, you have access to the private `CodingKeys.authorName`, and a compiler-checked SQL column name. + +By using the `annotated(with:)` method, you append the author name to the top-level selection that can be decoded by the ad-hoc record. + +By using the `joining()` method, you make sure no author column is selected, but the one declared in `annotated(with:)`. + +By using `asRequest(of:)`, you enhance the type-safety of your request. + + +## FAQ: Errors + ### Generic parameter 'T' could not be inferred You may get this error when using the `read` and `write` methods of database queues and pools: @@ -7595,3 +7747,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Combine]: https://developer.apple.com/documentation/combine [Demo Application]: Documentation/DemoApps/GRDBDemoiOS/README.md [Sharing a Database]: Documentation/SharingADatabase.md +[FAQ]: #faq From 2c6ca91985b97abc05b92f619ab37a9a218958c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:28:16 +0200 Subject: [PATCH 32/51] Fix inner links --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b155ecf87..59bb8dd66 100644 --- a/README.md +++ b/README.md @@ -262,7 +262,10 @@ Documentation **GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). -#### [FAQ] + +#### Frequently Asked Questions + +- [FAQ]: [Opening Connections](#faq-opening-connections), [Associations](#faq-associations), etc. #### Reference From 1f5cc801e13524c4e51d3eb3a9eb7f6fca471212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:29:38 +0200 Subject: [PATCH 33/51] Fix typos --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 59bb8dd66..52580652c 100644 --- a/README.md +++ b/README.md @@ -7300,9 +7300,9 @@ FAQ **[FAQ: Associations](#faq-associations)** -- [How to I filter records and only keep those that are associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) -- [How to I filter records and only keep those that are NOT associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) -- [How to I select only one column of an associated record?](#how-to-i-select-only-one-column-of-an-associated-record) +- [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-associated-to-another-record) +- [How do I filter records and only keep those that are NOT associated to another record?](#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?](#how-do-i-select-only-one-column-of-an-associated-record) **[FAQ: Errors](#faq-errors)** @@ -7438,7 +7438,7 @@ try dbQueue.read { db in ## FAQ: Associations -### How to I filter records and only keep those that are associated to another record? +### How do I filter records and only keep those that are associated to another record? Let's say you have two record types, `Book` and `Author`, and you want to only fetch books that have an author, and discard anonymous books. @@ -7467,10 +7467,10 @@ let books: [Book] = try dbQueue.read { db in Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on book columns. Instead, we just need to express that it is "required that a book can be joined to its author". -See [How to I filter records and only keep those that are NOT associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question. +See [How do I filter records and only keep those that are NOT associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question. -### How to I filter records and only keep those that are NOT associated to another record? +### How do I filter records and only keep those that are NOT associated to another record? Let's say you have two record types, `Book` and `Author`, and you want to only fetch anonymous books that do not have any author. @@ -7503,10 +7503,10 @@ let books: [Book] = try dbQueue.read { db in This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure that their `Column.rowID` (another name for their primary key) is nil, which is another way to say it does not exist: the book has no author. -See [How to I filter records and only keep those that are associated to another record?](#how-to-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) above for the opposite question. +See [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-associated-to-another-record) above for the opposite question. -### How to I select only one column of an associated record? +### How do I select only one column of an associated record? Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full author records: From 7662e53dce8d4223b101865075d1c047e82a7163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:31:29 +0200 Subject: [PATCH 34/51] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52580652c..9bd0146d8 100644 --- a/README.md +++ b/README.md @@ -7486,7 +7486,7 @@ struct Author: TableRecord { } ``` -And then we can write our request and only fetch anonymous books that have an author: +And then we can write our request and only fetch anonymous books that don't have any author: ```swift let books: [Book] = try dbQueue.read { db in From 9608b5edd584620a63927724af1d2ede8b7824be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:32:36 +0200 Subject: [PATCH 35/51] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9bd0146d8..a7b460e6f 100644 --- a/README.md +++ b/README.md @@ -7508,7 +7508,7 @@ See [How do I filter records and only keep those that are associated to another ### How do I select only one column of an associated record? -Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full author records: +Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full author records. We start by defining the association between books and authors: From 280c9f01557e1a020ced8d49dec0f8224c20685a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:33:49 +0200 Subject: [PATCH 36/51] Fix sample code --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a7b460e6f..118a8e7b2 100644 --- a/README.md +++ b/README.md @@ -7449,6 +7449,7 @@ struct Book: TableRecord { ... let author = belongsTo(Author.self) } + struct Author: TableRecord { ... } @@ -7481,6 +7482,7 @@ struct Book: TableRecord { ... let author = belongsTo(Author.self) } + struct Author: TableRecord { ... } @@ -7517,7 +7519,8 @@ struct Book: Decodable, TableRecord { ... let author = belongsTo(Author.self) } -struct Author: TableRecord { + +struct Author: Decodable, TableRecord { ... enum Columns { static let name = Column(CodingKeys.name) From efc12c2ef93ef36908b14be103e05527d6f8cc58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:39:31 +0200 Subject: [PATCH 37/51] CHANGELOG --- CHANGELOG.md | 8 +++++++- Documentation/AssociationsBasics.md | 10 ++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0506685f..5cb973a70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,7 +76,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ### 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. +- 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) + ## 5.0.0-beta.4 diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 1470225b2..b057948dd 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -39,8 +39,14 @@ GRDB Associations - [Aggregate Operations] - [Isolation of Multiple Aggregates] - [DerivableRequest Protocol] -- **[FAQ]** -- [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 From 5c697659b43e72b6aa227f54bb5de02565b9c6ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:49:22 +0200 Subject: [PATCH 38/51] Foster SQLITE_ENABLE_SNAPSHOT in the "Custom SQLite Builds" guide --- CHANGELOG.md | 1 + Documentation/CustomSQLiteBuilds.md | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cb973a70..dc303b845 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,6 +83,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [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/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. From 82feed42c2b94648c522c856e62bdbe5d128e1cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:50:46 +0200 Subject: [PATCH 39/51] Fix wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 118a8e7b2..643b7a997 100644 --- a/README.md +++ b/README.md @@ -7466,7 +7466,7 @@ let books: [Book] = try dbQueue.read { db in } ``` -Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on book columns. Instead, we just need to express that it is "required that a book can be joined to its author". +Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on any column. Instead, we just need to express that it is "required that a book can be joined to its author". See [How do I filter records and only keep those that are NOT associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question. From c0cf3c052500459bd61480dcd747906a58bba0fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:51:38 +0200 Subject: [PATCH 40/51] Fix wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 643b7a997..5e0d1f6c6 100644 --- a/README.md +++ b/README.md @@ -7466,7 +7466,7 @@ let books: [Book] = try dbQueue.read { db in } ``` -Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on any column. Instead, we just need to express that it is "required that a book can be joined to its author". +Note how this request does not use the `filter` method. Indeed, we don't have any condition to express on any column. Instead, we just need to "require that a book can be joined to its author". See [How do I filter records and only keep those that are NOT associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) below for the opposite question. From ae7cdb1f5b87b68a12fa1df2bb575c7a31e42c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Jun 2020 20:58:04 +0200 Subject: [PATCH 41/51] Precision --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e0d1f6c6..7ffd34ce7 100644 --- a/README.md +++ b/README.md @@ -7510,7 +7510,7 @@ See [How do I filter records and only keep those that are associated to another ### How do I select only one column of an associated record? -Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full author records. +Let's say you have two record types, `Book` and `Author`, and you want to fetch all books with their author name, but not the full associated author records. We start by defining the association between books and authors: From ab97ceb78442251cc055605716ae11c9a8271287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 13:58:48 +0200 Subject: [PATCH 42/51] TableRecord.primaryKey --- .../Association/AssociationAggregate.swift | 15 ++--- .../SQL/SQLExpression+QueryInterface.swift | 65 +++++++++++++++++++ GRDB/QueryInterface/SQL/SQLExpression.swift | 19 ------ GRDB/QueryInterface/SQL/SQLRelation.swift | 12 ---- .../SQLGeneration/SQLQueryGenerator.swift | 4 +- GRDB/Record/TableRecord.swift | 26 ++++++++ Tests/GRDBTests/TableRecordTests.swift | 30 +++++++++ 7 files changed, 130 insertions(+), 41 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 8efb69e43..e43b741c9 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -38,10 +38,9 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - let expression = DatabasePromise { db in - let primaryKey = try db.primaryKeyExpression(self.databaseTableName) - return SQLExpressionCountDistinct(primaryKey) - } + let expression = SQLExpressionCountDistinct( + SQLPrimaryKeyExpression( + tableName: self.databaseTableName)) return makeAggregate(expression).forKey("\(key.singularizedName)Count") } @@ -61,10 +60,10 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - let expression = DatabasePromise { db in - let primaryKey = try db.primaryKeyExpression(self.databaseTableName) - return SQLExpressionIsEmpty(SQLExpressionCountDistinct(primaryKey)) - } + let expression = SQLExpressionIsEmpty( + SQLExpressionCountDistinct( + SQLPrimaryKeyExpression( + tableName: self.databaseTableName))) return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 8b35d73f9..92c667759 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -779,3 +779,68 @@ struct SQLExpressionCollate: SQLExpression { SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) } } + +// MARK: - SQLPrimaryKeyExpression + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// SQLPrimaryKeyExpression is the primary key of a table. +/// +/// For tables that have no explicit primary key, SQLPrimaryKeyExpression is the +/// `rowid` column. +/// +/// For tables whose primary key spans several columns, the current +/// implementation of SQLPrimaryKeyExpression also is the `rowid` column. Future +/// GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html). +/// +/// For example: +/// +/// struct Player: TableRecord { ... } +/// +/// let player = dbQueue.read { db in +/// try Player.filter(Player.primaryKey == 12).fetchOne(db) +/// } +public struct SQLPrimaryKeyExpression: SQLExpression { + let tableName: String + + /// Support for SQLPrimaryKeyExpression and SQLQualifiedPrimaryKeyExpression + fileprivate static func primaryKeyColumn(_ db: Database, tableName: String) throws -> Column { + let columns = try db.primaryKey(tableName).columns + if columns.count == 1 { + return Column(columns[0]) + } else { + return Column.rowID + } + } + + public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try SQLPrimaryKeyExpression + .primaryKeyColumn(context.db, tableName: tableName) + .expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + } + + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLQualifiedPrimaryKeyExpression(tableName: tableName, alias: alias) + } +} + +struct SQLQualifiedPrimaryKeyExpression: SQLExpression { + let tableName: String + let alias: TableAlias + + func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + GRDBPrecondition( + tableName.lowercased() == alias.tableName.lowercased(), + "Table names don't match: \(tableName) and \(alias.tableName)") + + return try SQLPrimaryKeyExpression + .primaryKeyColumn(context.db, tableName: tableName) + .qualifiedExpression(with: alias) + .expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + // Never requalify + self + } +} diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 63abe460c..b56342be2 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -169,22 +169,3 @@ struct SQLExpressionNot: SQLExpression { SQLExpressionNot(expression.qualifiedExpression(with: alias)) } } - -// MARK: - - -extension Database { - /// Returns an expression for the primary key of this table. - /// - /// When the table as a primary key made of several columns, we return - /// the rowid column. Eventually we'll support - /// [row values](https://www.sqlite.org/rowvalue.html) and be able to deal - /// with WITHOUT ROWID tables. - func primaryKeyExpression(_ tableName: String) throws -> SQLExpression { - let columns = try primaryKey(tableName).columns - if columns.count == 1 { - return Column(columns[0]) - } else { - return Column.rowID - } - } -} diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index d7e65e1a0..2f19e5d3b 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -184,18 +184,6 @@ struct SQLRelation { } } } - - /// Returns nil if there is no way to express the primary key of the - /// relation as an expression. - func primaryKeyExpression(_ db: Database) throws -> SQLExpression? { - switch source { - case .subquery: - // No primary key for subquery - return nil - case let .table(tableName: tableName, alias: _): - return try db.primaryKeyExpression(tableName) - } - } } extension SQLRelation: Refinable { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 28c55b80a..45eb49e36 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -347,7 +347,7 @@ struct SQLQueryGenerator: Refinable { } let context = SQLGenerationContext(db) - let primaryKey = try db.primaryKeyExpression(tableName) + let primaryKey = SQLPrimaryKeyExpression(tableName: tableName) var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false) @@ -451,7 +451,7 @@ struct SQLQueryGenerator: Refinable { } let context = SQLGenerationContext(db) - let primaryKey = try db.primaryKeyExpression(tableName) + let primaryKey = SQLPrimaryKeyExpression(tableName: tableName) // UPDATE table... var sql = "UPDATE " diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 2eb623df6..740f5311d 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -140,6 +140,32 @@ extension TableRecord { } } +extension TableRecord { + // MARK: - Primary Key + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The primary key of the table. + /// + /// For example: + /// + /// struct Player: TableRecord { ... } + /// + /// let player = dbQueue.read { db in + /// try Player.filter(Player.primaryKey == 12).fetchOne(db) + /// } + /// + /// For tables that have no explicit primary key, this property returns the + /// `rowid` column. + /// + /// For tables whose primary key spans several columns, the current + /// implementation also returns the `rowid` column. Future GRDB versions + /// may return a [row value](https://www.sqlite.org/rowvalue.html). + public static var primaryKey: SQLPrimaryKeyExpression { + SQLPrimaryKeyExpression(tableName: databaseTableName) + } +} + /// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation /// /// This cache mitigates the cost of the calculation by storing the name for later retrieval diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index 80ad7bcf6..73a379c00 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -125,4 +125,34 @@ class TableRecordTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"") } } + + func testPrimaryKey() throws { + struct IntegerPrimaryKeyRecord: TableRecord { } + struct UUIDRecord: TableRecord { } + struct RowIDRecord: TableRecord { } + struct CompoundPrimaryKeyRecord: TableRecord { } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE integerPrimaryKeyRecord (id INTEGER PRIMARY KEY); + CREATE TABLE uuidRecord (uuid TEXT PRIMARY KEY); + CREATE TABLE rowIDRecord (name TEXT); + CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b)); + """) + + try assertEqualSQL(db, IntegerPrimaryKeyRecord.order(IntegerPrimaryKeyRecord.primaryKey), """ + SELECT * FROM "integerPrimaryKeyRecord" ORDER BY "id" + """) + try assertEqualSQL(db, UUIDRecord.order(UUIDRecord.primaryKey), """ + SELECT * FROM "uuidRecord" ORDER BY "uuid" + """) + try assertEqualSQL(db, RowIDRecord.order(RowIDRecord.primaryKey), """ + SELECT * FROM "rowIDRecord" ORDER BY "rowid" + """) + try assertEqualSQL(db, CompoundPrimaryKeyRecord.order(CompoundPrimaryKeyRecord.primaryKey), """ + SELECT * FROM "compoundPrimaryKeyRecord" ORDER BY "rowid" + """) + } + } } From 47cf3b0108eba884f32a7738e3d5557dece30147 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 14:09:15 +0200 Subject: [PATCH 43/51] Update FAQ sample code with TableRecord.primaryKey, and add tests for FAQ --- README.md | 10 ++-- .../AssociationBelongsToSQLTests.swift | 60 +++++++++++++++++++ 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7ffd34ce7..0ba1313bc 100644 --- a/README.md +++ b/README.md @@ -7447,7 +7447,7 @@ We start by defining the association between books and authors: ```swift struct Book: TableRecord { ... - let author = belongsTo(Author.self) + static let author = belongsTo(Author.self) } struct Author: TableRecord { @@ -7480,7 +7480,7 @@ We start by defining the association between books and authors: ```swift struct Book: TableRecord { ... - let author = belongsTo(Author.self) + static let author = belongsTo(Author.self) } struct Author: TableRecord { @@ -7494,11 +7494,11 @@ And then we can write our request and only fetch anonymous books that don't have let books: [Book] = try dbQueue.read { db in // SELECT book.* FROM book // LEFT JOIN author ON author.id = book.authorID - // WHERE author.rowid IS NULL + // WHERE author.id IS NULL let authorAlias = TableAlias() let request = Book .joining(optional: Book.author.aliased(authorAlias)) - .filter(authorAlias[Column.rowID] == nil) + .filter(authorAlias[Author.primaryKey] == nil) return try request.fetchAll(db) } ``` @@ -7517,7 +7517,7 @@ We start by defining the association between books and authors: ```swift struct Book: Decodable, TableRecord { ... - let author = belongsTo(Author.self) + static let author = belongsTo(Author.self) } struct Author: Decodable, TableRecord { diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 5cd87f78c..c795076ed 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -1127,4 +1127,64 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } } } + + // Test for the "How do I filter records and only keep those that are + // associated to another record?" FAQ + func testRecordsFilteredByExistingAssociatedRecord() throws { + struct Book: TableRecord { + static let author = belongsTo(Author.self) + } + + struct Author: TableRecord { + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorID", .integer).references("author") + } + + let request = Book.joining(required: Book.author) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + JOIN "author" ON "author"."id" = "book"."authorID" + """) + } + } + + // Test for the "How do I filter records and only keep those that are NOT + // associated to another record?" FAQ + func testRecordsFilteredByNonExistingAssociatedRecord() throws { + struct Book: TableRecord { + static let author = belongsTo(Author.self) + } + + struct Author: TableRecord { + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorID", .integer).references("author") + } + + let authorAlias = TableAlias() + let request = Book + .joining(optional: Book.author.aliased(authorAlias)) + .filter(authorAlias[Author.primaryKey] == nil) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + LEFT JOIN "author" ON "author"."id" = "book"."authorID" \ + WHERE "author"."id" IS NULL + """) + } + } } From 86a84394732f81ce6727452eca0d8437944a1969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 14:14:09 +0200 Subject: [PATCH 44/51] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0ba1313bc..3b2e35656 100644 --- a/README.md +++ b/README.md @@ -7503,7 +7503,7 @@ let books: [Book] = try dbQueue.read { db in } ``` -This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure that their `Column.rowID` (another name for their primary key) is nil, which is another way to say it does not exist: the book has no author. +This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure that the `Author.primaryKey` is nil, which is another way to say it does not exist: the book has no author. See [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-associated-to-another-record) above for the opposite question. From c4ab23761ebcac6e4199814d17a833c9cdb177da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 17:02:00 +0200 Subject: [PATCH 45/51] QueryInterfaceRequest.selectPrimaryKey(as:) --- .../Request/QueryInterfaceRequest.swift | 24 +++++ .../TableRecord+QueryInterfaceRequest.swift | 25 +++++ README.md | 52 +++++++--- .../RecordMinimalPrimaryKeyRowIDTests.swift | 77 ++++++++------- .../RecordMinimalPrimaryKeySingleTests.swift | 75 ++++++++------ .../RecordPrimaryKeyHiddenRowIDTests.swift | 97 +++++++++++-------- .../RecordPrimaryKeyMultipleTests.swift | 74 ++++++++------ .../GRDBTests/RecordPrimaryKeyNoneTests.swift | 29 ++++-- .../RecordPrimaryKeyRowIDTests.swift | 83 +++++++++------- .../RecordPrimaryKeySingleTests.swift | 81 +++++++++------- ...leWithReplaceConflictResolutionTests.swift | 77 ++++++++------- 11 files changed, 428 insertions(+), 266 deletions(-) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index fb763ed10..0d7a12a62 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -192,6 +192,30 @@ extension QueryInterfaceRequest: SelectionRequest { public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { map(\.query) { $0.annotated(with: selection) } } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates a request which selects the primary key of the table. + /// + /// For example: + /// + /// struct Player: TableRecord { ... } + /// + /// let playerIds = dbQueue.read { db in + /// try Player.all().selectPrimaryKey(as: Int64.self).fetchAll(db) + /// } + /// + /// For tables that have no explicit primary key, the request selects the + /// `rowid` column. + /// + /// For tables whose primary key spans several columns, the current + /// implementation also returns a request that selects the `rowid` column. + /// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html). + public func selectPrimaryKey(as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + select(SQLPrimaryKeyExpression(tableName: databaseTableName), as: RowDecoder.self) + } } extension QueryInterfaceRequest: FilteredRequest { diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 3c074e33a..95810f4c8 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -126,6 +126,31 @@ extension TableRecord { all().select(literal: sqlLiteral, as: type) } + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates a request which selects the primary key of the table. + /// + /// For example: + /// + /// struct Player: TableRecord { ... } + /// + /// let playerIds = dbQueue.read { db in + /// try Player.selectPrimaryKey(as: Int64.self).fetchAll(db) + /// } + /// + /// For tables that have no explicit primary key, the request selects the + /// `rowid` column. + /// + /// For tables whose primary key spans several columns, the current + /// implementation also returns a request that selects the `rowid` column. + /// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html). + public static func selectPrimaryKey( + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().selectPrimaryKey(as: type) + } + /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player diff --git a/README.md b/README.md index 3b2e35656..601c25512 100644 --- a/README.md +++ b/README.md @@ -3633,6 +3633,7 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.none()` | [TableRecord] | ² | | `Type.select(...)` | [TableRecord] | ² | | `Type.select(..., as:...)` | [TableRecord] | ² | +| `Type.selectPrimaryKey(as:...)` | [TableRecord] | ² | | `Type.annotated(with:...)` | [TableRecord] | ² | | `Type.filter(...)` | [TableRecord] | ² | | `Type.matching(...)` | [TableRecord] | ² | @@ -3641,9 +3642,11 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.including(required:)` | [TableRecord] | ² | | `Type.joining(optional:)` | [TableRecord] | ² | | `Type.joining(required:)` | [TableRecord] | ² | +| `Type.group(...)` | [TableRecord] | ² | +| `Type.groupByPrimaryKey()` | [TableRecord] | ² | +| `Type.having(...)` | [TableRecord] | ² | | `Type.order(...)` | [TableRecord] | ² | | `Type.orderByPrimaryKey()` | [TableRecord] | ² | -| `Type.having(...)` | [TableRecord] | ² | | `Type.limit(...)` | [TableRecord] | ² | | **[Record Comparison]** | | | | `record.databaseEquals(...)` | [EncodableRecord] | | @@ -4117,19 +4120,6 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.order(scoreColumn).order(nameColumn) ``` -- `orderByPrimaryKey()` sorts by primary key: - - ```swift - // SELECT * FROM player ORDER BY id - Player.orderByPrimaryKey() - - // SELECT * FROM country ORDER BY code - Country.orderByPrimaryKey() - - // SELECT * FROM citizenship ORDER BY citizenId, countryCode - Citizenship.orderByPrimaryKey() - ``` - - `reversed()` reverses the eventual orderings. ```swift @@ -4163,6 +4153,40 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.including(required: Player.team) ``` +- Other requests that involve the primary key: + + - `selectPrimaryKey(as:)` selects the primary key. + + ```swift + // SELECT id FROM player + Player.selectPrimaryKey(as: Int64.self) + ``` + + It is equivalent to: + + ```swift + // SELECT id FROM player + Player.select(Player.primaryKey, as: Int64.self) + ``` + + > :point_up: **Note**: `selectPrimaryKey` and `primaryKey` are [experimental](#what-are-experimental-features) and currently pick the `rowid` column for tables that have a composite primary key that spans several columns. Future GRDB version may change this behavior. + + - `orderByPrimaryKey()` sorts by primary key. + + ```swift + // SELECT * FROM player ORDER BY id + Player.orderByPrimaryKey() + + // SELECT * FROM country ORDER BY code + Country.orderByPrimaryKey() + + // SELECT * FROM citizenship ORDER BY citizenId, countryCode + Citizenship.orderByPrimaryKey() + ``` + + - `groupByPrimaryKey()` groups rows by primary key. + + You can refine requests by chaining those methods: ```swift diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 0d73cdf26..8a3b880ac 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -58,7 +58,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -70,7 +70,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -84,7 +84,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -97,10 +97,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -116,7 +116,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -128,7 +128,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -145,10 +145,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyInsertsARowAndSetsPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -161,7 +161,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -173,7 +173,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -185,7 +185,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -198,10 +198,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -211,7 +211,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -224,7 +224,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -236,8 +236,8 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -268,7 +268,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -295,7 +295,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -307,7 +307,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } } - + // MARK: - Fetch With Key Request @@ -390,7 +390,18 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } - + + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = MinimalRowID.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"id\" FROM \"minimalRowIDs\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -416,7 +427,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -439,7 +450,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -459,7 +470,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -529,10 +540,10 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { } } } - - + + // MARK: - Exists - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -541,7 +552,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -550,7 +561,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 8cb37c321..c22f360ea 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -55,7 +55,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -67,7 +67,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -82,7 +82,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -96,10 +96,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -115,7 +115,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -128,7 +128,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -146,10 +146,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -163,7 +163,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -175,7 +175,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -188,7 +188,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -202,10 +202,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -215,7 +215,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -229,7 +229,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -242,8 +242,8 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -276,7 +276,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -305,7 +305,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -318,7 +318,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } } - + // MARK: - Fetch With Key Request @@ -407,6 +407,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = MinimalSingle.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"UUID\" FROM \"minimalSingles\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -434,7 +445,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -459,7 +470,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -480,7 +491,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -555,10 +566,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } } } - - + + // MARK: - Exists - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -567,7 +578,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -577,7 +588,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index ff9c57830..72e267b1d 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -87,7 +87,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testRollbackedInsertWithNilPrimaryKeyDoesNotResetPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() let record = Person(name: "Arthur") @@ -103,7 +103,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { // This is debatable, actually. XCTAssertTrue(record.id != nil) } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -114,7 +114,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testRollbackedInsertWithNotNilPrimaryKeyDoeNotResetPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() let record = Person(id: 123456, name: "Arthur") @@ -125,7 +125,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } XCTAssertEqual(record.id!, 123456) } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -139,7 +139,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -152,10 +152,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -170,7 +170,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -185,7 +185,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -198,7 +198,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -215,10 +215,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyInsertsARowAndSetsPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -231,7 +231,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -242,8 +242,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -257,7 +257,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -270,10 +270,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNilPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -282,7 +282,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -291,7 +291,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -304,7 +304,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -316,8 +316,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -348,7 +348,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -375,7 +375,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -390,7 +390,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } } - + // MARK: - Fetch With Key Request @@ -477,6 +477,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = Person.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"persons\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -502,7 +513,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -525,7 +536,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -548,7 +559,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -621,10 +632,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { } } } - - + + // MARK: - Exists - + func testExistsWithNilPrimaryKeyReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -632,7 +643,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -640,7 +651,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -649,7 +660,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -659,8 +670,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - - + + // MARK: - RowID func testRowIdIsSelectedByDefault() throws { @@ -690,10 +701,10 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try Person.limit(1).fetchOne(db)!.id != nil) } } - - + + // MARK: - FetchedRecordsController - + func testFetchedRecordsController() throws { let dbQueue = try makeDatabaseQueue() let person = Person(name: "Arthur") diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 889549e31..95edea5e0 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -69,7 +69,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -80,7 +80,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -94,7 +94,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -107,10 +107,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -125,7 +125,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -140,7 +140,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -153,7 +153,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -170,10 +170,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -187,7 +187,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -198,7 +198,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -212,7 +212,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -225,10 +225,10 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNilPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -237,7 +237,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -246,7 +246,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -259,7 +259,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -271,8 +271,8 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -303,7 +303,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -330,7 +330,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -344,7 +344,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"citizenships\" WHERE (\"personName\" = '\(record.personName!)') AND (\"countryName\" = '\(record.countryName!)')") } } - + // MARK: - Fetch With Key Request @@ -403,7 +403,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } } } - + func testFetchOneWithKeyRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -430,8 +430,20 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = Citizenship.selectPrimaryKey() + // May change in a future release, when we support SQLite row values. + try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"citizenships\"") + } + } + + // MARK: - Exists - + func testExistsWithNilPrimaryKeyReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -439,7 +451,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -447,7 +459,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -456,7 +468,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 24b4107cb..34b87732a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -67,10 +67,10 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { XCTAssertEqual(names, ["Table", "Table"]) } } - - + + // MARK: - Save - + func testSaveInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -82,8 +82,8 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { XCTAssertEqual(names, ["Table", "Table"]) } } - - + + // MARK: - Fetch With Key func testFetchOneWithKey() throws { @@ -97,7 +97,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"items\" WHERE \"email\" = 'item@example.com'") } } - + // MARK: - Fetch With Key Request @@ -125,6 +125,17 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = Item.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"items\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -154,7 +165,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -181,7 +192,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -202,7 +213,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 1b536885d..4b02512e5 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -84,7 +84,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testRollbackedInsertWithNilPrimaryKeyDoesNotResetPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() let record = Person(name: "Arthur") @@ -100,7 +100,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { // This is debatable, actually. XCTAssertTrue(record.id != nil) } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -111,7 +111,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testRollbackedInsertWithNotNilPrimaryKeyDoeNotResetPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() let record = Person(id: 123456, name: "Arthur") @@ -122,7 +122,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } XCTAssertEqual(record.id!, 123456) } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -136,7 +136,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -149,10 +149,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -182,7 +182,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -195,7 +195,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -212,10 +212,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyInsertsARowAndSetsPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -228,7 +228,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -239,7 +239,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -253,7 +253,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -266,10 +266,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNilPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -278,7 +278,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -287,7 +287,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -300,7 +300,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -312,8 +312,8 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -344,7 +344,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -371,7 +371,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -386,7 +386,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"persons\" WHERE \"id\" = \(record.id!)") } } - + // MARK: - Fetch With Key Request @@ -473,6 +473,17 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = Person.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"id\" FROM \"persons\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -498,7 +509,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -521,7 +532,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -544,7 +555,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -617,10 +628,10 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { } } } - - + + // MARK: - Exists - + func testExistsWithNilPrimaryKeyReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -628,7 +639,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -636,7 +647,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -645,7 +656,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index b169ff3b2..9db1bcf3b 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -62,7 +62,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -73,7 +73,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -87,7 +87,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -100,10 +100,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -118,7 +118,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -133,7 +133,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -146,7 +146,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -163,10 +163,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -180,7 +180,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -191,7 +191,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -205,7 +205,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -218,10 +218,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNilPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -230,7 +230,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -239,7 +239,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -252,7 +252,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -264,8 +264,8 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -296,7 +296,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -323,7 +323,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -336,7 +336,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"pets\" WHERE \"UUID\" = '\(record.UUID!)'") } } - + // MARK: - Fetch With Key Request @@ -421,6 +421,17 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = Pet.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"UUID\" FROM \"pets\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -446,7 +457,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -469,7 +480,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -490,7 +501,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -561,10 +572,10 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { } } } - - + + // MARK: - Exists - + func testExistsWithNilPrimaryKeyReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -572,7 +583,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -580,7 +591,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -589,7 +600,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index b395df4a2..f071f8a91 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -61,7 +61,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -74,7 +74,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertWithNotNilPrimaryKeyThatMatchesARowReplacesARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -89,7 +89,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testInsertAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -103,10 +103,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Update - + func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -122,7 +122,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -135,7 +135,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testUpdateAfterDeleteThrowsRecordNotFound() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -153,10 +153,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - - + + // MARK: - Save - + func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -170,7 +170,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -182,7 +182,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -195,7 +195,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - + func testSaveAfterDeleteInsertsARow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -209,10 +209,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { assert(record, isEncodedIn: row) } } - - + + // MARK: - Delete - + func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -222,7 +222,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertFalse(deleted) } } - + func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -236,7 +236,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertTrue(row == nil) } } - + func testDeleteAfterDeleteDoesNothing() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -249,8 +249,8 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertFalse(deleted) } } - - + + // MARK: - Fetch With Key func testFetchCursorWithKeys() throws { @@ -283,7 +283,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testFetchAllWithKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -312,7 +312,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testFetchOneWithKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -325,7 +325,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"emails\" WHERE \"email\" = '\(record.email!)'") } } - + // MARK: - Fetch With Key Request @@ -388,7 +388,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testFetchOneWithKeyRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -414,6 +414,17 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } + // MARK: - Select Primary Key + + func testSelectPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request: QueryInterfaceRequest = Email.selectPrimaryKey() + try assertEqualSQL(db, request, "SELECT \"email\" FROM \"emails\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { @@ -441,7 +452,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testFetchAllWithPrimaryKeys() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -466,7 +477,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + func testFetchOneWithPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -487,7 +498,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - + // MARK: - Fetch With Primary Key Request @@ -562,10 +573,10 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { } } } - - + + // MARK: - Exists - + func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -574,7 +585,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertFalse(try record.exists(db)) } } - + func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -584,7 +595,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertTrue(try record.exists(db)) } } - + func testExistsAfterDeleteReturnsTrue() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From dd63ddf7f2be3b51e780291501acd6e8e41cf438 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 17:04:16 +0200 Subject: [PATCH 46/51] CHANGELOG --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc303b845..d6c7e1230 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,9 +70,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release -- [#795](https://github.com/groue/GRDB.swift/pull/795): **Breaking Change** 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. +- **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 From 1a1c0cd3d16ac1357385ed9d483545974207a023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 08:13:19 +0200 Subject: [PATCH 47/51] Demo app tweaks --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 14 +- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 205 +++++++-------- .../GRDBDemoiOS/Base.lproj/Main.storyboard | 49 ++-- .../PlayerEditionViewController.swift | 92 +++---- .../PlayerListViewController.swift | 238 ++++++++++++++++++ .../GRDBDemoiOS/PlayersViewController.swift | 10 +- Documentation/DemoApps/GRDBDemoiOS/README.md | 4 +- 7 files changed, 431 insertions(+), 181 deletions(-) create mode 100644 Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerListViewController.swift 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 cc5ba1e1f..8e3e4d8e5 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -13,107 +13,6 @@ final class AppDatabase { try migrator.migrate(dbQueue) } - // MARK: - Database Access: Writes - - /// Saves (insert or update) a player in the database - func savePlayer(_ player: inout Player) throws { - try dbQueue.write { db in - try player.save(db) - } - } - - /// Deletes one player - func deletePlayer(_ player: Player) throws { - try dbQueue.write { db in - _ = try player.delete(db) - } - } - - /// Deletes all players - func deleteAllPlayers() throws { - try dbQueue.write { db in - _ = try Player.deleteAll(db) - } - } - - /// Refreshes 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: - Database Access: Reads - - /// Tracks changes in the number of players - func observePlayerCount( - onError: @escaping (Error) -> Void, - onChange: @escaping (Int) -> Void) - -> DatabaseCancellable - { - ValueObservation - .tracking { db in try Player.fetchCount(db) } - .start( - in: dbQueue, - scheduling: .immediate, - onError: onError, - onChange: onChange) - } - - /// Tracks changes in players ordered by name - func observePlayersOrderedByName( - onError: @escaping (Error) -> Void, - onChange: @escaping ([Player]) -> Void) - -> DatabaseCancellable - { - ValueObservation - .tracking { db in try Player.all().orderedByName().fetchAll(db) } - .start( - in: dbQueue, - scheduling: .immediate, - onError: onError, - onChange: onChange) - } - - /// Tracks changes in players ordered by score - func observePlayersOrderedByScore( - onError: @escaping (Error) -> Void, - onChange: @escaping ([Player]) -> Void) - -> DatabaseCancellable - { - ValueObservation - .tracking { db in try Player.all().orderedByScore().fetchAll(db) } - .start( - in: dbQueue, - scheduling: .immediate, - onError: onError, - onChange: onChange) - } - - // MARK: - Private - /// The DatabaseMigrator that defines the database schema. /// /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md @@ -151,3 +50,107 @@ final class 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/Base.lproj/Main.storyboard b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard index 4fd2097aa..d81633d84 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard @@ -1,8 +1,8 @@ - - + + - + @@ -10,22 +10,21 @@ - - + + - - + - + - + - - + + @@ -40,15 +39,19 @@ + + + + - + - + - - + + @@ -101,7 +104,7 @@ - + @@ -117,7 +120,7 @@ - + @@ -131,27 +134,27 @@ - + - + - + - + @@ -54,6 +55,9 @@ + + + diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift index a4c2de6d9..9c1b15ffd 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift @@ -102,6 +102,13 @@ extension PlayerEditionViewController: UITextFieldDelegate { return false } + @IBAction func textFieldDidChange(_ textField: UITextField) { + // User has edited the player: prevent interactive dismissal + if case .modal = presentation { + isModalInPresentation = true + } + } + private func configureForm() { guard isViewLoaded else { return } From a4443b8ebbbaeba639028bbba9fe5bcc7e167111 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 19:57:50 +0200 Subject: [PATCH 50/51] FAQ Navigation --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 601c25512..b75b12e76 100644 --- a/README.md +++ b/README.md @@ -7337,6 +7337,11 @@ FAQ ## FAQ: Opening Connections +- :arrow_up: [FAQ] +- [How do I create a database in my application?](#how-do-i-create-a-database-in-my-application) +- [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) +- [How do I close a database connection?](#how-do-i-close-a-database-connection) + ### How do I create a database in my application? This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) instead. @@ -7387,6 +7392,9 @@ Database accesses that run in background threads postpone the closing of connect ## FAQ: SQL +- :arrow_up: [FAQ] +- [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) + ### How do I print a request as SQL? When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed. @@ -7434,6 +7442,10 @@ db.trace { event in ## FAQ: General +- :arrow_up: [FAQ] +- [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution) +- [What Are Experimental Features?](#what-are-experimental-features) + ### How do I monitor the duration of database statements execution? Use the `trace(options:_:)` method, with the `.profile` option: @@ -7462,6 +7474,11 @@ try dbQueue.read { db in ## FAQ: Associations +- :arrow_up: [FAQ] +- [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-associated-to-another-record) +- [How do I filter records and only keep those that are NOT associated to another record?](#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?](#how-do-i-select-only-one-column-of-an-associated-record) + ### How do I filter records and only keep those that are associated to another record? Let's say you have two record types, `Book` and `Author`, and you want to only fetch books that have an author, and discard anonymous books. @@ -7590,6 +7607,11 @@ By using `asRequest(of:)`, you enhance the type-safety of your request. ## FAQ: Errors +- :arrow_up: [FAQ] +- [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred) +- [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized) +- [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries) + ### Generic parameter 'T' could not be inferred You may get this error when using the `read` and `write` methods of database queues and pools: From 4e182a511f4c90f89a7896e2a066f774e7b1caeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 15 Jun 2020 20:05:13 +0200 Subject: [PATCH 51/51] v5.0.0-beta.5 --- CHANGELOG.md | 10 ++++++++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 40 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 37 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6c7e1230..d07e9c987 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,13 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. + #### 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 @@ -68,7 +70,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... + + +## 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. diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 8ae389a6e..0b1ce5baa 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 5ec1f99d9..a4572ecbc 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -68,7 +68,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index fe5d05ec4..7645dd754 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.0.0-beta.4' + s.version = '5.0.0-beta.5' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index caca9ca11..8204fe199 100644 --- a/Makefile +++ b/Makefile @@ -394,10 +394,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/v5.0.0-beta.4 \ - --module-version 5.0.0-beta.4 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.5 \ + --module-version 5.0.0-beta.5 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index b75b12e76..3f6821722 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: June 6, 2020 • version 5.0.0-beta.4 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: June 15, 2020 • version 5.0.0-beta.5 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • Swift 5.2+ / Xcode 11.4+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 5.2** | **v5.0.0-beta.4**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)| +| **Swift 5.2** | **v5.0.0-beta.5**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)| | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -269,7 +269,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -482,7 +482,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/Configuration.html) for more details. ## Database Pools @@ -562,7 +562,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -622,7 +622,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/5.0.0-beta.4/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/5.0.0-beta.5/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also 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/5.0.0-beta.4/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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/5.0.0-beta.4/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/5.0.0-beta.5/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/5.0.0-beta.4/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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/5.0.0-beta.4/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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/5.0.0-beta.4/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/5.0.0-beta.5/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/5.0.0-beta.4/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. +Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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). @@ -2420,7 +2420,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/5.0.0-beta.4/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/5.0.0-beta.5/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()`. @@ -2799,7 +2799,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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). @@ -4208,7 +4208,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4814,7 +4814,7 @@ try Player.customRequest().fetchAll(db) // [Player] **To build custom requests**, you can use one of the built-in requests or derive requests from other requests. -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4857,7 +4857,7 @@ try Player.customRequest().fetchAll(db) // [Player] - 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/5.0.0-beta.4/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -5964,7 +5964,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/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/5.0.0-beta.5/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. @@ -5974,7 +5974,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/5.0.0-beta.4/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7071,7 +7071,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.4/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/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: diff --git a/Support/Info.plist b/Support/Info.plist index 88c4274ce..c83aff553 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.0.0-beta.4 + 5.0.0-beta.5 CFBundleSignature ???? CFBundleVersion