From 37065fb5038b14caacde0cd94512082a190c1380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 26 Jul 2025 11:06:50 +0200 Subject: [PATCH 01/45] Regression test for #1797 --- Tests/GRDBTests/DatabaseReaderTests.swift | 48 +++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 3eb2c56ae..ca5a10378 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -677,4 +677,52 @@ class DatabaseReaderTests : GRDBTestCase { try await test(AnyDatabaseReader(makeDatabaseQueue())) try await test(AnyDatabaseWriter(makeDatabaseQueue())) } + + // Regression test for https://github.com/groue/GRDB.swift/pull/1797 + func test_cancellation_does_not_impact_other_tasks() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + // Numbers that have the test fail more or less reliably + // (on my machine) unless the #1797 patch is applied. + let repeatCount = 30 + let taskCount = 400 + for _ in 0.. Date: Sat, 30 Aug 2025 09:58:59 -0700 Subject: [PATCH 02/45] Update `GRDB7MigrationGuide.md` reference Signed-off-by: Emmanuel Ferdman --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 72d68eb87..b0428333a 100644 --- a/README.md +++ b/README.md @@ -335,7 +335,7 @@ Documentation - [Unicode](#unicode) - [Memory Management](#memory-management) - [Data Protection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections) -- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/Documentation/GRDB7MigrationGuide.md) +- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) - :bulb: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) - :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) @@ -2194,7 +2194,7 @@ For more information about batch updates, see [Update Requests](#update-requests > **Note**: Upsert apis are available from SQLite 3.35.0+: iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build] or [SQLCipher](#encryption). > -> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks reports the rowid of the inserted or updated row; `willUpdate`, `aroundUdate`, `didUdate` are not called. +> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks reports the rowid of the inserted or updated row; `willUpdate`, `aroundUpdate`, `didUpdate` are not called. [PersistableRecord] provides three upsert methods: @@ -3008,7 +3008,7 @@ try player.insert(db) > // INSERT OR IGNORE INTO player ... RETURNING * > do { > let insertedPlayer = try player.insertAndFetch(db) { -> // Succesful insertion +> // Successful insertion > catch RecordError.recordNotFound { > // Failed insertion due to IGNORE policy > } From b4f3a83755e1754b06d06f5f4b4c2b6e9f621c69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 19:52:00 +0200 Subject: [PATCH 03/45] Remove SwiftLint warning If we don't have warnings about explicit nil initialization, then we have a warning about the name of a disabled rule which is now deprecated. In all cases, we have a warning. So let's just write 2025 Swift, ignore that rule, and call it a day. --- GRDB/Core/Configuration.swift | 8 ++++---- GRDB/Core/Database+Schema.swift | 4 ++-- GRDB/Core/Database+Statements.swift | 2 +- GRDB/Core/Database.swift | 10 +++++----- GRDB/Core/Statement.swift | 2 +- GRDB/Core/TransactionObserver.swift | 2 +- GRDB/FTS/FTS5.swift | 4 ++-- GRDB/FTS/FTS5Tokenizer.swift | 2 +- .../Request/Association/AssociationAggregate.swift | 2 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 6 +++--- Scripts/swiftlint.yml | 1 - 11 files changed, 21 insertions(+), 22 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 067260d62..21cc6dea9 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -87,7 +87,7 @@ public struct Configuration: Sendable { /// with the number of snapshots. /// /// The default configuration label is nil. - public var label: String? = nil + public var label: String? /// A boolean value indicating whether SQLite 3.29+ interprets /// double-quoted strings as string literals when they does not match any @@ -329,7 +329,7 @@ public struct Configuration: Sendable { /// The behavior in case of SQLITE_BUSY error, for read-only connections. /// If nil, GRDB picks a default one. - var readonlyBusyMode: Database.BusyMode? = nil + var readonlyBusyMode: Database.BusyMode? /// The maximum number of concurrent reader connections. /// @@ -387,7 +387,7 @@ public struct Configuration: Sendable { /// ``qos`` property. /// /// The default is nil. - public var targetQueue: DispatchQueue? = nil + public var targetQueue: DispatchQueue? /// The target dispatch queue for write database accesses. /// @@ -395,7 +395,7 @@ public struct Configuration: Sendable { /// by ``targetQueue``. /// /// The default is nil. - public var writeTargetQueue: DispatchQueue? = nil + public var writeTargetQueue: DispatchQueue? #if os(iOS) /// A boolean value indicating whether the database connection releases diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index ff8f9bf1d..acaa303a4 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -571,7 +571,7 @@ extension Database { // We don't use `try makeStatement(sql:)` in order to avoid throwing an // error (this annoys users who set a breakpoint on Swift errors). let sql = "SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)" - var statement: SQLiteStatement? = nil + var statement: SQLiteStatement? let code = sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil) defer { sqlite3_finalize(statement) } return code == SQLITE_OK @@ -743,7 +743,7 @@ extension Database { id: Int, destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] - var previousId: Int? = nil + var previousId: Int? for row in try Row.fetchAll(self, sql: """ PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier)) """) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index f4d98fc14..86b2924e9 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -387,7 +387,7 @@ extension SQLStatementCursor: Cursor { let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0. // Compile next statement - var statementEnd: UnsafePointer? = nil + var statementEnd: UnsafePointer? let statement = try Statement( database: database, statementStart: baseAddress + offset, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index dbf1c2f4b..5dcd55e33 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -169,7 +169,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// connection has been opened is an SQLite misuse, and has no effect. /// /// Related SQLite documentation: - nonisolated(unsafe) public static var logError: LogErrorFunction? = nil { + nonisolated(unsafe) public static var logError: LogErrorFunction? { didSet { if logError != nil { _registerErrorLogCallback { (_, code, message) in @@ -459,7 +459,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection { // See - var sqliteConnection: SQLiteConnection? = nil + var sqliteConnection: SQLiteConnection? let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil) guard code == SQLITE_OK else { // https://www.sqlite.org/c3ref/open.html @@ -1286,7 +1286,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so // that we don't create an infinite loop in checkForSuspensionViolation(from:) - var statement: SQLiteStatement? = nil + var statement: SQLiteStatement? let sql = "PRAGMA journal_mode" sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil) defer { sqlite3_finalize(statement) } @@ -1483,7 +1483,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Now that transaction has begun, we'll rollback in case of error. // But we'll throw the first caught error, so that user knows // what happened. - var firstError: Error? = nil + var firstError: Error? let needsRollback: Bool do { let completion = try operations() @@ -1626,7 +1626,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Now that savepoint has begun, we'll rollback in case of error. // But we'll throw the first caught error, so that user knows // what happened. - var firstError: Error? = nil + var firstError: Error? let needsRollback: Bool do { let completion = try operations() diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index be07f9eaf..1a203f685 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -141,7 +141,7 @@ public final class Statement { let authorizer = database.authorizer authorizer.reset() - var sqliteStatement: SQLiteStatement? = nil + var sqliteStatement: SQLiteStatement? let code = sqlite3_prepare_v3( database.sqliteConnection, statementStart, -1, prepFlags, &sqliteStatement, statementEnd) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index cd536035c..b9a747f8c 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1494,7 +1494,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) -> DatabaseValue? { - var value: SQLiteValue? = nil + var value: SQLiteValue? guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } if let value { return DatabaseValue(sqliteValue: value) diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 26ad268f7..cfce95f2a 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -117,8 +117,8 @@ public struct FTS5 { /// /// Related SQLite documentation: public static func api(_ db: Database) -> UnsafePointer { - var statement: SQLiteStatement? = nil - var api: UnsafePointer? = nil + var statement: SQLiteStatement? + var api: UnsafePointer? let type: StaticString = "fts5_api_ptr" let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil) diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index e4aecc36f..7c25b6a89 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -208,7 +208,7 @@ extension Database { self.xTokenizer = xTokenizer - var tokenizerPointer: OpaquePointer? = nil + var tokenizerPointer: OpaquePointer? let code: CInt if arguments.isEmpty { code = xCreate(contextPointer, nil, 0, &tokenizerPointer) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 5132589be..b39439671 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -636,7 +636,7 @@ public struct AssociationAggregate { fileprivate let preparation: AssociationAggregatePreparation /// The SQL name for the value of this aggregate. See forKey(_:). - var key: String? = nil + var key: String? /// Extends the request with the associated records used to compute the /// aggregate, and returns the aggregated expression. diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 36116c7d5..8c823ea1b 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1592,7 +1592,7 @@ extension SQLExpression { case let .associativeBinary(op, expressions): assert(expressions.count > 1) if op == .and { - var result: Set? = nil + var result: Set? for expression in expressions { if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) { if var rowIDs = result { @@ -2020,8 +2020,8 @@ struct SQLAggregateFunctionInvocation { var name: String var arguments: [SQLExpression] var isDistinct = false - var ordering: SQLOrdering? = nil // SQLite 3.44.0+ - var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+ + var ordering: SQLOrdering? // SQLite 3.44.0+ + var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+ /// A boolean value indicating if a function is known to return a /// JSON value. diff --git a/Scripts/swiftlint.yml b/Scripts/swiftlint.yml index 9245d10d5..c8a223f0b 100644 --- a/Scripts/swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -18,7 +18,6 @@ disabled_rules: - non_optional_string_data_conversion - opening_brace - optional_data_string_conversion - - redundant_optional_initialization - syntactic_sugar - todo - trailing_comma From 3f6961440531965acba9f053b4f51dbc66c62fa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Sep 2025 20:03:39 +0200 Subject: [PATCH 04/45] DatabaseFunction with raw xFunc No use right now, but I was really bugged that we could not use raw sqlite3_result_xxx methods from custom functions. --- GRDB/Core/DatabaseFunction.swift | 62 +++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 17 deletions(-) diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 11387222c..223fded9b 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -82,20 +82,43 @@ public final class DatabaseFunction: Identifiable, Sendable { /// such as `Int`, `String`, `Date`, etc. The array is guaranteed to /// have exactly `argumentCount` elements, provided `argumentCount` is /// not nil. - public init( + public convenience init( _ name: String, argumentCount: Int? = nil, pure: Bool = false, function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) + { + self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in + let arguments = (0.. private class FunctionDefinition { - let compute: (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)? - init(compute: @escaping (CInt, UnsafeMutablePointer?) - throws -> (any DatabaseValueConvertible)?) + let xFunc: XFunc + init(xFunc: @escaping XFunc) { - self.compute = compute + self.xFunc = xFunc } } @@ -283,11 +305,19 @@ public final class DatabaseFunction: Identifiable, Sendable { } } + /// Feeds the `xFunc` parameter of sqlite3_create_function_v2 + /// + typealias XFunc = @Sendable ( + _ argc: CInt, + _ argv: UnsafeMutablePointer, + _ context: OpaquePointer? + ) throws -> Void + /// A function kind: an "SQL function" or an "aggregate". /// See private enum Kind: Sendable { /// A regular function: SELECT f(1) - case function(@Sendable (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) + case function(XFunc) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz case aggregate(@Sendable () -> any DatabaseAggregate) @@ -296,8 +326,8 @@ public final class DatabaseFunction: Identifiable, Sendable { /// var definition: AnyObject { switch self { - case .function(let compute): - return FunctionDefinition(compute: compute) + case .function(let xFunc): + return FunctionDefinition(xFunc: xFunc) case .aggregate(let makeAggregate): return AggregateDefinition(makeAggregate: makeAggregate) } @@ -312,9 +342,7 @@ public final class DatabaseFunction: Identifiable, Sendable { .fromOpaque(sqlite3_user_data(sqliteContext)) .takeUnretainedValue() do { - try DatabaseFunction.report( - result: definition.compute(argc, argv), - in: sqliteContext) + try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext) } catch { DatabaseFunction.report(error: error, in: sqliteContext) } From 8dfbbb50f6b0cd04aabb7b3ed3cbaae0ed965a23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Sep 2025 06:51:01 +0200 Subject: [PATCH 05/45] TODO --- GRDB/Core/DatabasePool.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 4c791a1d9..2fb2d5cc5 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -361,6 +361,7 @@ extension DatabasePool: DatabaseReader { return try await readerPool.get { reader in try await reader.execute { db in defer { + #warning("TODO: when Task is cancelled, this commit fails, and we're still in a transaction") // Ignore commit error, but make sure we leave the transaction try? db.commit() assert(!db.isInsideTransaction) From 4cfa692ddda7f547e202dd2ea51135f4de94d1a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Sep 2025 07:11:57 +0200 Subject: [PATCH 06/45] Fix race condition regarding Task cancellation This complements #1797 by making sure read-only transactions complete correctly, even if the task is cancelled. --- GRDB/Core/Database.swift | 2 +- GRDB/Core/DatabasePool.swift | 28 +++++++++++++++++++------- GRDB/Core/DatabaseQueue.swift | 18 +++++++++++++---- GRDB/Core/DatabaseSnapshot.swift | 9 +++++++-- GRDB/Core/WALSnapshotTransaction.swift | 8 +++++++- 5 files changed, 50 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 5dcd55e33..48eaa905c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1744,7 +1744,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib if isInsideTransaction { try execute(sql: "ROLLBACK TRANSACTION") } - assert(sqlite3_get_autocommit(sqliteConnection) != 0) + assert(!isInsideTransaction) } /// Commits a database transaction. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 2fb2d5cc5..21b5db750 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -361,9 +361,13 @@ extension DatabasePool: DatabaseReader { return try await readerPool.get { reader in try await reader.execute { db in defer { - #warning("TODO: when Task is cancelled, this commit fails, and we're still in a transaction") - // Ignore commit error, but make sure we leave the transaction - try? db.commit() + // Commit or rollback, but make sure we leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } assert(!db.isInsideTransaction) } // The block isolation comes from the DEFERRED transaction. @@ -388,8 +392,13 @@ extension DatabasePool: DatabaseReader { // Second async jump because that's how `Pool.async` has to be used. reader.async { db in defer { - // Ignore commit error, but make sure we leave the transaction - try? db.commit() + // Commit or rollback, but make sure we leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } assert(!db.isInsideTransaction) releaseReader(.reuse) } @@ -552,8 +561,13 @@ extension DatabasePool: DatabaseReader { let (reader, releaseReader) = try readerPool.get() reader.async { db in defer { - // Ignore commit error, but make sure we leave the transaction - try? db.commit() + // Commit or rollback, but make sure we leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } assert(!db.isInsideTransaction) releaseReader(.reuse) } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index d5286d895..b8f32961c 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -248,8 +248,13 @@ extension DatabaseQueue: DatabaseReader { ) { writer.async { db in defer { - // Ignore commit error (we can not notify it), but make sure we leave the transaction - try? db.commit() + // Commit or rollback, but make sure we leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } assert(!db.isInsideTransaction) try? db.endReadOnly() } @@ -297,8 +302,13 @@ extension DatabaseQueue: DatabaseReader { GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.") defer { - // Ignore commit error (we can not notify it), but make sure we leave the transaction - try? db.commit() + // Commit or rollback, but make sure we leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } assert(!db.isInsideTransaction) try? db.endReadOnly() } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 48dd99386..5d6370736 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -113,8 +113,13 @@ public final class DatabaseSnapshot { deinit { // Leave snapshot isolation reader.reentrantSync { db in - // Ignore commit error (we can not notify it), but make sure we leave the transaction - try? db.commit() + // Commit or rollback, but make sure we leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } assert(!db.isInsideTransaction) } } diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index eb6597fe1..9e961bde3 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable { // WALSnapshotTransaction may be deinitialized in the dispatch // queue of its reader: allow reentrancy. let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in - try? db.commit() + // Commit or rollback, but try hard to leave the read-only transaction + // (commit may fail with a CancellationError). + do { + try db.commit() + } catch { + try? db.rollback() + } return db.isInsideTransaction } release(isInsideTransaction) From cd84db38733d713a5e6e596b2cdde2e3ca8d16bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 21:32:35 +0200 Subject: [PATCH 07/45] Xcode 26 upgrade --- .../DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj | 4 +++- .../xcshareddata/xcschemes/GRDBDemo.xcscheme | 2 +- GRDB.xcodeproj/project.pbxproj | 7 ++++++- GRDB.xcodeproj/xcshareddata/xcschemes/GRDB.xcscheme | 2 +- GRDBCustom.xcodeproj/project.pbxproj | 7 ++++++- .../xcshareddata/xcschemes/GRDBCustom.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBProfiling.xcscheme | 2 +- 7 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj index 47782e062..6edc31973 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj @@ -158,7 +158,7 @@ attributes = { BuildIndependentTargetsInParallel = 1; LastSwiftUpdateCheck = 1600; - LastUpgradeCheck = 1600; + LastUpgradeCheck = 2600; TargetAttributes = { 56CFC6432C9F1DC9000B5023 = { CreatedOnToolsVersion = 16.0; @@ -293,6 +293,7 @@ MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -350,6 +351,7 @@ MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_EMIT_LOC_STRINGS = YES; VALIDATE_PRODUCT = YES; diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme index 386a9790f..8946129d7 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme @@ -1,6 +1,6 @@ Date: Tue, 9 Sep 2025 21:58:23 +0200 Subject: [PATCH 08/45] Fix a compiler error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The error was: > use of ‘@import’ in framework header is discouraged, including this header requires -fmodules This commit applies the fix recommended at https://developer.apple.com/documentation/xcode/identifying-and-addressing-framework-module-issues --- SQLiteCustom/GRDB.h | 4 ++-- Support/GRDB.h | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/SQLiteCustom/GRDB.h b/SQLiteCustom/GRDB.h index 00a7454a7..af41eb628 100755 --- a/SQLiteCustom/GRDB.h +++ b/SQLiteCustom/GRDB.h @@ -1,4 +1,4 @@ -@import Foundation; +#import //! Project version number for GRDB. FOUNDATION_EXPORT double GRDB_VersionNumber; @@ -8,4 +8,4 @@ FOUNDATION_EXPORT const unsigned char GRDB_VersionString[]; #import #import -#import "GRDB-Bridging.h" +#import diff --git a/Support/GRDB.h b/Support/GRDB.h index 69ad6ed45..71687094c 100644 --- a/Support/GRDB.h +++ b/Support/GRDB.h @@ -1,4 +1,4 @@ -@import Foundation; +#import //! Project version number for GRDB. FOUNDATION_EXPORT double GRDB_VersionNumber; @@ -7,4 +7,3 @@ FOUNDATION_EXPORT double GRDB_VersionNumber; FOUNDATION_EXPORT const unsigned char GRDB_VersionString[]; #import - From fd7adf7fb3debdd31bf079f473fbc0d82b6914ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 21:35:58 +0200 Subject: [PATCH 09/45] SendableMetatype for compiler >= 6.2 --- GRDB/Utils/Utils.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index d690b9eec..dd7ce059f 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -23,6 +23,14 @@ public func databaseQuestionMarks(count: Int) -> String { repeatElement("?", count: count).joined(separator: ",") } +#if compiler(>=6.2) +/// A synonym for `SendableMetatype` in Swift 6.2, and `Any` otherwise. +public typealias GRDBSendableMetatype = SendableMetatype +#else +/// A synonym for `SendableMetatype` in Swift 6.2, and `Any` otherwise. +public typealias GRDBSendableMetatype = Any +#endif + // MARK: - Internal /// Reserved for GRDB: do not use. From cf1702630f4cfc9fa475b683c3477479e503750b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 21:38:42 +0200 Subject: [PATCH 10/45] DatabaseAggregate is SendableMetatype DatabaseAggregate does not support isolated conformances: it must be able to aggregate values whenever a database access is performed. This can happen in a nonisolated fashion. --- GRDB/Core/DatabaseFunction.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 223fded9b..f6e6a84de 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -492,7 +492,7 @@ public final class DatabaseFunction: Identifiable, Sendable { /// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3 /// } /// ``` -public protocol DatabaseAggregate { +public protocol DatabaseAggregate: GRDBSendableMetatype { /// Creates an aggregate. /// /// A new instance is created for each aggregation. From f435715f7502975c3fc395d7bf59a5f3df7f60cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 21:42:37 +0200 Subject: [PATCH 11/45] ValueReducer is SendableMetatype ValueReducer does not support isolated conformances: it must be able to reduce observed values when needed. This can happen in a nonisolated fashion. --- GRDB/ValueObservation/Reducers/ValueReducer.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/ValueObservation/Reducers/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift index 8c7386693..44411cbfb 100644 --- a/GRDB/ValueObservation/Reducers/ValueReducer.swift +++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift @@ -11,7 +11,7 @@ // which is its `Fetcher`. /// Implementation details of `ValueReducer`. -public protocol _ValueReducer { +public protocol _ValueReducer: GRDBSendableMetatype { /// The Sendable type that fetches database values associatedtype Fetcher: _ValueReducerFetcher From 79ce0ff5f35f03931c845a74b00d474c42fec871 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 22:02:53 +0200 Subject: [PATCH 12/45] Avoid a compiler warning --- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 66816236b..c53cca1c0 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -362,11 +362,13 @@ extension QueryInterfaceRequest: SelectionRequest { public func selectID() -> QueryInterfaceRequest where RowDecoder: Identifiable { - selectWhenConnected { db in - let primaryKey = try db.primaryKey(self.databaseTableName) + let databaseTableName = self.databaseTableName + + return selectWhenConnected { db in + let primaryKey = try db.primaryKey(databaseTableName) GRDBPrecondition( primaryKey.columns.count == 1, - "selectID requires a single-column primary key in the table \(self.databaseTableName)") + "selectID requires a single-column primary key in the table \(databaseTableName)") return [Column(primaryKey.columns[0])] }.asRequest(of: RowDecoder.ID.self) } From f88c7202cda80336ab69fb0301840d04a53d4855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 22:07:54 +0200 Subject: [PATCH 13/45] TableRecord is GRDBSendableMetatype This is required because the value of databaseSelection is not required to be Sendable. This forces TableRecord.relationForAll to postpone the definition of the selection until we access the database - in a nonisolated fashion. --- GRDB/Record/TableRecord.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index c3a98756b..716b4fc0b 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -134,7 +134,7 @@ import Foundation /// - ``select(_:as:)-tjh0`` /// - ``updateAll(_:onConflict:_:)-7vv9x`` /// - ``updateAll(_:onConflict:_:)-7atfw`` -public protocol TableRecord { +public protocol TableRecord: GRDBSendableMetatype { /// A type that defines columns. /// /// For example: From 32ed290a1b048352da42b27848c620a3bc0bc296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 22:10:21 +0200 Subject: [PATCH 14/45] EncodableRecord is GRDBSendableMetatype This allows us to apply the encoding strategies for Data, Date, UUID when we know we need it, i.e. when we know the primary key, and this happens when we access the database - in a nonisolated fashion. --- GRDB/Record/EncodableRecord.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 27f995370..98261bc94 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -39,7 +39,7 @@ import Foundation // For JSONEncoder /// - ``databaseChanges(from:)`` /// - ``databaseChanges(modify:)`` /// - ``databaseEquals(_:)`` -public protocol EncodableRecord { +public protocol EncodableRecord: GRDBSendableMetatype { /// Encodes the record into the provided persistence container. /// /// In your implementation of this method, store in the `container` argument From 1a3842e4bc6fd03144d0891e5b2ee6e7a0121965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 21:47:15 +0200 Subject: [PATCH 15/45] Combine and concurrency: lol --- GRDB/Core/DatabaseRegionObservation.swift | 8 ++++++-- GRDB/Utils/OnDemandFuture.swift | 6 ++++-- GRDB/ValueObservation/ValueObservation.swift | 8 ++++++-- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index ec6319721..246e3627a 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -201,7 +201,11 @@ extension DatabasePublishers { self.observation = observation } - public func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { + public func receive(subscriber: S) + where S: Subscriber & GRDBSendableMetatype, + Failure == S.Failure, + Output == S.Input + { let subscription = DatabaseRegionSubscription( writer: writer, observation: observation, @@ -212,7 +216,7 @@ extension DatabasePublishers { private class DatabaseRegionSubscription: Subscription, @unchecked Sendable - where Downstream: Subscriber, + where Downstream: Subscriber & GRDBSendableMetatype, Downstream.Failure == Error, Downstream.Input == Database { diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index 938750d4a..b12840a1d 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -27,7 +27,7 @@ struct OnDemandFuture: Publisher { self.attemptToFulfill = attemptToFulfill } - func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { + func receive(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input { let subscription = OnDemandFutureSubscription( attemptToFulfill: attemptToFulfill, downstream: subscriber) @@ -35,7 +35,9 @@ struct OnDemandFuture: Publisher { } } -private class OnDemandFutureSubscription: Subscription, @unchecked Sendable { +private class OnDemandFutureSubscription: Subscription, @unchecked Sendable +where Downstream: Subscriber & GRDBSendableMetatype +{ // @unchecked because `state` is protected with `lock`. typealias Promise = @Sendable (Result) -> Void diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 92cfe9864..642c2465b 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -511,7 +511,11 @@ extension DatabasePublishers { self.start = start } - public func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { + public func receive(subscriber: S) + where S: Subscriber & GRDBSendableMetatype, + Failure == S.Failure, + Output == S.Input + { let subscription = ValueSubscription( start: start, downstream: subscriber) @@ -521,7 +525,7 @@ extension DatabasePublishers { private class ValueSubscription: Subscription, @unchecked Sendable - where Downstream: Subscriber, + where Downstream: Subscriber & GRDBSendableMetatype, Downstream.Failure == Error { // @unchecked Sendable because `cancellable` and `state` are From 7ec88b76e091cb3933535c8df4969367e0374ddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 22:18:50 +0200 Subject: [PATCH 16/45] Start an immediate observation In the iOS 26 simulator the demo app would show a flash of missing content. --- .../DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift index 0ea0b85ef..2c1fa4909 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift @@ -56,7 +56,7 @@ import GRDB // Start observing the database. // Previous observation, if any, is cancelled. - cancellable = observation.start(in: appDatabase.reader) { error in + cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in // Handle error } onChange: { [unowned self] players in self.players = players From 6a25b3538e2afaff413a4b0db2e6e14abb065415 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Sep 2025 07:41:42 +0200 Subject: [PATCH 17/45] DocC for GRDBSendableMetatype --- GRDB/Documentation.docc/SwiftConcurrency.md | 6 ++++++ GRDB/Utils/Utils.swift | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/GRDB/Documentation.docc/SwiftConcurrency.md b/GRDB/Documentation.docc/SwiftConcurrency.md index 4fcfc15fa..35ce83c57 100644 --- a/GRDB/Documentation.docc/SwiftConcurrency.md +++ b/GRDB/Documentation.docc/SwiftConcurrency.md @@ -229,5 +229,11 @@ Task { } ``` +## Topics + +### Supporting Types + +- ``GRDBSendableMetatype`` + [demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps [Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/ diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index dd7ce059f..47bb3a16c 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -24,10 +24,12 @@ public func databaseQuestionMarks(count: Int) -> String { } #if compiler(>=6.2) -/// A synonym for `SendableMetatype` in Swift 6.2, and `Any` otherwise. +/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2, +/// and `Any` in previous compiler versions. public typealias GRDBSendableMetatype = SendableMetatype #else -/// A synonym for `SendableMetatype` in Swift 6.2, and `Any` otherwise. +/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2, +/// and `Any` in previous compiler versions. public typealias GRDBSendableMetatype = Any #endif From f3acfecc160ad710ba3526d0b2089de7ed23245e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 13 Sep 2025 12:21:36 +0200 Subject: [PATCH 18/45] DatabaseCollation no longer uses a deprecated String initializer --- GRDB/Core/Database.swift | 2 +- GRDB/Core/DatabaseCollation.swift | 36 ++++++++------- Tests/GRDBTests/DatabaseCollationTests.swift | 46 ++++++++++---------- 3 files changed, 44 insertions(+), 40 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 48eaa905c..e1bc96ee1 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -806,7 +806,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib collationPointer, { (collationPointer, length1, buffer1, length2, buffer2) in let collation = Unmanaged.fromOpaque(collationPointer!).takeUnretainedValue() - return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue) + return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped) }, nil) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 6748874c8..ea4ad3392 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -53,12 +53,21 @@ public final class DatabaseCollation: Identifiable, Sendable { } } + /// Feeds the `xCompare` parameter of sqlite3_create_collation_v2 + /// + typealias XCompare = @Sendable ( + _ length1: CInt, + _ buffer1: UnsafeRawPointer, + _ length2: CInt, + _ buffer2: UnsafeRawPointer + ) -> CInt + /// The identifier of the collation. public var id: ID { ID(name: name) } /// The name of the collation. public let name: String - let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult + let xCompare: XCompare /// Creates a collation. /// @@ -75,21 +84,16 @@ public final class DatabaseCollation: Identifiable, Sendable { /// - parameters: /// - name: The collation name. /// - function: A function that compares two strings. - public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) { + public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) { + self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in + let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self) + let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self) + return CInt(function(string1, string2).rawValue) + }) + } + + init(_ name: String, xCompare: @escaping XCompare) { self.name = name - self.function = { (length1, buffer1, length2, buffer2) in - // Buffers are not C strings: they do not end with \0. - let string1 = String( - bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), - length: Int(length1), - encoding: .utf8, - freeWhenDone: false)! - let string2 = String( - bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), - length: Int(length2), - encoding: .utf8, - freeWhenDone: false)! - return function(string1, string2) - } + self.xCompare = xCompare } } diff --git a/Tests/GRDBTests/DatabaseCollationTests.swift b/Tests/GRDBTests/DatabaseCollationTests.swift index 366659683..0602595fb 100644 --- a/Tests/GRDBTests/DatabaseCollationTests.swift +++ b/Tests/GRDBTests/DatabaseCollationTests.swift @@ -6,38 +6,38 @@ class DatabaseCollationTests: GRDBTestCase { func testDefaultCollations() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT)") - try db.execute(sql: "INSERT INTO strings VALUES (1, '1')") - try db.execute(sql: "INSERT INTO strings VALUES (2, '2')") - try db.execute(sql: "INSERT INTO strings VALUES (3, '10')") - try db.execute(sql: "INSERT INTO strings VALUES (4, 'a')") - try db.execute(sql: "INSERT INTO strings VALUES (5, 'à')") - try db.execute(sql: "INSERT INTO strings VALUES (6, 'A')") - try db.execute(sql: "INSERT INTO strings VALUES (7, 'Z')") - try db.execute(sql: "INSERT INTO strings VALUES (8, 'z')") + try db.execute(sql: """ + CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT); + INSERT INTO strings VALUES (1, '1'); + INSERT INTO strings VALUES (2, '2'); + INSERT INTO strings VALUES (3, '10'); + INSERT INTO strings VALUES (4, 'a'); + INSERT INTO strings VALUES (5, 'à'); + INSERT INTO strings VALUES (6, 'A'); + INSERT INTO strings VALUES (7, 'Z'); + INSERT INTO strings VALUES (8, 'z'); + INSERT INTO strings VALUES (9, ''); + INSERT INTO strings VALUES (10, NULL); + INSERT INTO strings VALUES (11, x'42FF'); -- Invalid UTF8 "B�" + """) - // Swift 4.2 and Swift 4.1 don't sort strings in the same way - if "z" < "à" { - XCTAssertEqual( - try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), - [1,3,2,6,7,4,8,5]) - } else { - XCTAssertEqual( - try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), - [1,3,2,6,7,4,5,8]) - } + // Note that "B�" is always last. We can observe that SQLite + // does not invoke the collation for invalid UTF8 strings. + XCTAssertEqual( + try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), + [10,9,1,3,2,6,7,4,8,5,11]) XCTAssertEqual( try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"), - [1,3,2,4,6,5,7,8]) + [10,9,1,3,2,4,6,5,7,8,11]) XCTAssertEqual( try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCaseInsensitiveCompare.name), id"), - [1,3,2,4,6,5,7,8]) + [10,9,1,3,2,4,6,5,7,8,11]) XCTAssertEqual( try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCompare.name), id"), - [1,3,2,4,6,5,8,7]) + [10,9,1,3,2,4,6,5,8,7,11]) XCTAssertEqual( try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedStandardCompare.name), id"), - [1,2,3,4,6,5,8,7]) + [10,9,1,2,3,4,6,5,8,7,11]) } } From aab2664431432247a5c6df3cc7b89ba75437c14a Mon Sep 17 00:00:00 2001 From: alephao <7674479+alephao@users.noreply.github.com> Date: Tue, 16 Sep 2025 23:30:17 -0300 Subject: [PATCH 19/45] fix: DispatchQueueExecutor sendable conformance on Linux --- GRDB/Core/DispatchQueueActor.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GRDB/Core/DispatchQueueActor.swift b/GRDB/Core/DispatchQueueActor.swift index f0b92d112..3a51d8897 100644 --- a/GRDB/Core/DispatchQueueActor.swift +++ b/GRDB/Core/DispatchQueueActor.swift @@ -43,3 +43,7 @@ private final class DispatchQueueExecutor: SerialExecutor { dispatchPrecondition(condition: .onQueue(queue)) } } + +#if os(Linux) + extension DispatchQueueExecutor: @unchecked Sendable {} +#endif From 30313623ebe06c0890996870e1925ff0acbfef7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Aug 2025 13:30:12 +0200 Subject: [PATCH 20/45] Make DatabaseSchemaID and DatabaseObjectID public This is also a big cleanup opportunity. We need public schema identifiers in order to support the customization of schema introspection. --- GRDB/Core/Database+Schema.swift | 367 ++++++++++-------- GRDB/Core/DatabaseRegion.swift | 4 +- .../DatabaseSchemaIntrospection.md | 2 + .../SQL/SQLForeignKeyRequest.swift | 2 +- 4 files changed, 208 insertions(+), 167 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index acaa303a4..fa08cef1e 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -12,13 +12,13 @@ extension Database { struct SchemaCache { /// The available schema identifiers, in the order of SQLite resolution: /// temp, main, then attached databases. - var schemaIdentifiers: [SchemaIdentifier]? + var schemaIDs: [DatabaseSchemaID]? /// The schema cache for each identifier. - fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:] + fileprivate var schemas: [DatabaseSchemaID: DatabaseSchemaCache] = [:] /// The schema cache for a given identifier - subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested + subscript(schemaID: DatabaseSchemaID) -> DatabaseSchemaCache { // internal so that it can be tested get { schemas[schemaID] ?? DatabaseSchemaCache() } @@ -28,72 +28,11 @@ extension Database { } mutating func clear() { - schemaIdentifiers = nil + schemaIDs = nil schemas.removeAll() } } - /// An SQLite schema. See - enum SchemaIdentifier: Hashable { - /// The main database - case main - - /// The temp database - case temp - - /// An attached database: - case attached(String) - - /// The name of the schema in SQL queries. - /// - /// For example: - /// - /// SELECT * FROM main.player; - /// -- ~~~~ - var sql: String { - switch self { - case .main: return "main" - case .temp: return "temp" - case let .attached(name): return name - } - } - - /// The name of the master sqlite table - var masterTableName: String { // swiftlint:disable:this inclusive_language - switch self { - case .main: return "sqlite_master" - case .temp: return "sqlite_temp_master" - case let .attached(name): return "\(name).sqlite_master" - } - } - - /// The name of the master sqlite table, without the schema name. - var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language - switch self { - case .main, .attached: return "sqlite_master" - case .temp: return "sqlite_temp_master" - } - } - } - - /// The identifier of a database table or view. - struct TableIdentifier { - /// The SQLite schema - var schemaID: SchemaIdentifier - - /// The table or view name - var name: String - - /// Returns the receiver, quoted for safe insertion as an identifier in - /// an SQL query. - /// - /// // SELECT * FROM temp.player - /// db.execute(sql: "SELECT * FROM \(table.quotedDatabaseIdentifier)") - var quotedDatabaseIdentifier: String { - "\(schemaID.sql).\(name.quotedDatabaseIdentifier)" - } - } - // MARK: - Database Schema /// Returns the current schema version (`PRAGMA schema_version`). @@ -145,40 +84,37 @@ extension Database { } } - /// The list of database schemas, in the order of SQLite resolution: - /// temp, main, then attached databases. - func schemaIdentifiers() throws -> [SchemaIdentifier] { - if let schemaIdentifiers = schemaCache.schemaIdentifiers { - return schemaIdentifiers + /// Fetches the list of database schemas, in the order of SQLite + /// resolution: temp, main, then attached databases (as documented at + /// ). + func fetchSchemaIdentifiers() throws -> [DatabaseSchemaID] { + if let schemaIDs = schemaCache.schemaIDs { + return schemaIDs } - var schemaIdentifiers = try Array(Row + var schemaIDs = try Array(Row .fetchCursor(self, sql: "PRAGMA database_list") - .map { row -> SchemaIdentifier in - switch row[1] as String { - case "main": return .main - case "temp": return .temp - case let other: return .attached(other) - } + .map { row -> DatabaseSchemaID in + DatabaseSchemaID(name: row[1] as String) }) // Temp schema shadows all other schemas: put it first - if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) { - schemaIdentifiers.swapAt(tempIdx, 0) + if let tempIdx = schemaIDs.firstIndex(of: .temp) { + schemaIDs.swapAt(tempIdx, 0) } - schemaCache.schemaIdentifiers = schemaIdentifiers - return schemaIdentifiers + schemaCache.schemaIDs = schemaIDs + return schemaIDs } - /// The `SchemaIdentifier` named `schemaName` if it exists. + /// The `DatabaseSchemaID` named `schemaName`, if it exists. /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or /// if no such schema exists. - private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier { - let allIdentifiers = try schemaIdentifiers() - if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) { - return result + private func schemaIdentifier(named schemaName: String) throws -> DatabaseSchemaID { + let schemaIDs = try fetchSchemaIdentifiers() + if let schemaID = schemaIDs.first(where: { $0.name.lowercased() == schemaName.lowercased() }) { + return schemaID } else { throw DatabaseError.noSuchSchema(schemaName) } @@ -187,8 +123,8 @@ extension Database { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Returns information about a table or a view func table(_ tableName: String) throws -> TableInfo? { - for schemaIdentifier in try schemaIdentifiers() { - if let result = try table(for: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + for schemaID in try fetchSchemaIdentifiers() { + if let result = try table(for: DatabaseObjectID(name: tableName, schemaID: schemaID)) { return result } } @@ -196,7 +132,7 @@ extension Database { } /// Returns information about a table or a view - func table(for table: TableIdentifier) throws -> TableInfo? { + func table(for table: DatabaseObjectID) throws -> TableInfo? { // Maybe SQLCipher is too old: check actual version GRDBPrecondition(sqlite3_libversion_number() >= 3037000, "SQLite 3.37+ required") return try _table(for: table) @@ -205,8 +141,8 @@ extension Database { /// Returns information about a table or a view @available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+ func table(_ tableName: String) throws -> TableInfo? { - for schemaIdentifier in try schemaIdentifiers() { - if let result = try table(for: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + for schemaID in try fetchSchemaIdentifiers() { + if let result = try table(for: DatabaseObjectID(name: tableName, schemaID: schemaID)) { return result } } @@ -215,12 +151,12 @@ extension Database { /// Returns information about a table or a view @available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+ - func table(for table: TableIdentifier) throws -> TableInfo? { + func table(for table: DatabaseObjectID) throws -> TableInfo? { try _table(for: table) } #endif /// Returns information about a table or a view - private func _table(for table: TableIdentifier) throws -> TableInfo? { + private func _table(for table: DatabaseObjectID) throws -> TableInfo? { assert(sqlite3_libversion_number() >= 3037000, "SQLite 3.37+ required") SchedulingWatchdog.preconditionValidQueue(self) @@ -229,7 +165,7 @@ extension Database { } guard let tableInfo = try TableInfo - .fetchOne(self, sql: "PRAGMA \(table.schemaID.sql).table_list(\(table.name.quotedDatabaseIdentifier))") + .fetchOne(self, sql: "PRAGMA \(table.schemaID.name).table_list(\(table.name.quotedDatabaseIdentifier))") else { // table does not exist schemaCache[table.schemaID].set(tableInfo: .missing, forTable: table.name) @@ -263,12 +199,12 @@ extension Database { return try exists(type: .table, name: name, in: schemaName) } - return try schemaIdentifiers().contains { + return try fetchSchemaIdentifiers().contains { try exists(type: .table, name: name, in: $0) } } - private func tableExists(_ table: TableIdentifier) throws -> Bool { + private func tableExists(_ table: DatabaseObjectID) throws -> Bool { try exists(type: .table, name: table.name, in: table.schemaID) } @@ -286,7 +222,7 @@ extension Database { // > "sqlite_". tableName.starts(with: "sqlite_") || tableName.starts(with: "pragma_") } - + /// Returns whether a table is an internal GRDB table. /// /// Those are tables whose name begins with `grdb_`. @@ -318,7 +254,7 @@ extension Database { return try exists(type: .view, name: name, in: schemaName) } - return try schemaIdentifiers().contains { + return try fetchSchemaIdentifiers().contains { try exists(type: .view, name: name, in: $0) } } @@ -347,7 +283,7 @@ extension Database { return try exists(type: .trigger, name: name, in: schemaName) } - return try schemaIdentifiers().contains { + return try fetchSchemaIdentifiers().contains { try exists(type: .trigger, name: name, in: $0) } } @@ -362,14 +298,15 @@ extension Database { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or /// if the specified schema does not exist private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool { - if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) { + let schemaIDs = try fetchSchemaIdentifiers() + if let schemaID = schemaIDs.first(where: { $0.name.lowercased() == schemaName.lowercased() }) { return try exists(type: type, name: name, in: schemaID) } else { throw DatabaseError.noSuchSchema(schemaName) } } - private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool { + private func exists(type: SchemaObjectType, name: String, in schemaID: DatabaseSchemaID) throws -> Bool { // SQLite identifiers are case-insensitive, case-preserving: // http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html try schema(schemaID).containsObjectNamed(name, ofType: type) @@ -390,8 +327,9 @@ extension Database { /// } /// ``` /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is nil, known schemas are iterated in + /// SQLite resolution order, and the first matching result is returned. + /// For more information, see . /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if /// the specified schema does not exist, or if no such table exists in @@ -401,8 +339,8 @@ extension Database { return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:)) } - for schemaIdentifier in try schemaIdentifiers() { - if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + for schemaID in try fetchSchemaIdentifiers() { + if let result = try primaryKey(DatabaseObjectID(name: tableName, schemaID: schemaID)) { return result } } @@ -440,7 +378,7 @@ extension Database { } /// Returns nil if table does not exist - private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? { + private func primaryKey(_ table: DatabaseObjectID) throws -> PrimaryKeyInfo? { SchedulingWatchdog.preconditionValidQueue(self) if let primaryKey = schemaCache[table.schemaID].primaryKey(table.name) { @@ -448,7 +386,7 @@ extension Database { } if try !tableExists(table) { - // Views, CTEs, etc. + // Views, CTEs, etc. have no primary key. schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name) return nil } @@ -539,7 +477,7 @@ extension Database { /// Returns whether the table has a rowid column. /// /// - precondition: table exists. - private func tableHasRowID(_ table: TableIdentifier) throws -> Bool { + private func tableHasRowID(_ table: DatabaseObjectID) throws -> Bool { // No need to cache the result, because this information feeds // `PrimaryKeyInfo`, which is cached. @@ -601,8 +539,9 @@ extension Database { /// because the columns contain the primary key or a unique index, use /// ``table(_:hasUniqueKey:)``. /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is nil, known schemas are iterated in + /// SQLite resolution order, and the first matching result is returned. + /// For more information, see . /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if /// the specified schema does not exist, or if no such table or view @@ -613,8 +552,8 @@ extension Database { return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:)) } - for schemaIdentifier in try schemaIdentifiers() { - if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + for schemaID in try fetchSchemaIdentifiers() { + if let result = try indexes(on: DatabaseObjectID(name: tableName, schemaID: schemaID)) { return result } } @@ -622,14 +561,14 @@ extension Database { } /// Returns nil if table does not exist - private func indexes(on table: TableIdentifier) throws -> [IndexInfo]? { + private func indexes(on table: DatabaseObjectID) throws -> [IndexInfo]? { if let indexes = schemaCache[table.schemaID].indexes(on: table.name) { return indexes.value } let indexes = try Row // [seq:0 name:"index" unique:0 origin:"c" partial:0] - .fetchAll(self, sql: "PRAGMA \(table.schemaID.sql).index_list(\(table.name.quotedDatabaseIdentifier))") + .fetchAll(self, sql: "PRAGMA \(table.schemaID.name).index_list(\(table.name.quotedDatabaseIdentifier))") .compactMap { row -> IndexInfo? in let indexName: String = row[1] let unique: Bool = row[2] @@ -638,7 +577,7 @@ extension Database { let indexInfoRows = try Row // [seqno:0 cid:2 name:"column"] .fetchAll(self, sql: """ - PRAGMA \(table.schemaID.sql).index_info(\(indexName.quotedDatabaseIdentifier)) + PRAGMA \(table.schemaID.name).index_info(\(indexName.quotedDatabaseIdentifier)) """) // Sort by rank .sorted(by: { ($0[0] as Int) < ($1[0] as Int) }) @@ -702,8 +641,9 @@ extension Database { /// Returns the foreign keys defined on table named `tableName`. /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is nil, known schemas are iterated in + /// SQLite resolution order, and the first matching result is returned. + /// For more information, see . /// /// For example: /// @@ -725,8 +665,8 @@ extension Database { return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:)) } - for schemaIdentifier in try schemaIdentifiers() { - if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + for schemaID in try fetchSchemaIdentifiers() { + if let result = try foreignKeys(on: DatabaseObjectID(name: tableName, schemaID: schemaID)) { return result } } @@ -734,7 +674,7 @@ extension Database { } /// Returns nil if table does not exist - private func foreignKeys(on table: TableIdentifier) throws -> [ForeignKeyInfo]? { + private func foreignKeys(on table: DatabaseObjectID) throws -> [ForeignKeyInfo]? { if let foreignKeys = schemaCache[table.schemaID].foreignKeys(on: table.name) { return foreignKeys.value } @@ -745,7 +685,7 @@ extension Database { mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? for row in try Row.fetchAll(self, sql: """ - PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier)) + PRAGMA \(table.schemaID.name).foreign_key_list(\(table.name.quotedDatabaseIdentifier)) """) { // row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."] @@ -820,23 +760,23 @@ extension Database { if let schemaName { let schemaID = try schemaIdentifier(named: schemaName) if try exists(type: .table, name: tableName, in: schemaID) { - return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName)) + return try foreignKeyViolations(in: DatabaseObjectID(name: tableName, schemaID: schemaID)) } else { throw DatabaseError.noSuchTable(tableName) } } - for schemaIdentifier in try schemaIdentifiers() { - if try exists(type: .table, name: tableName, in: schemaIdentifier) { - return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) + for schemaID in try fetchSchemaIdentifiers() { + if try exists(type: .table, name: tableName, in: schemaID) { + return try foreignKeyViolations(in: DatabaseObjectID(name: tableName, schemaID: schemaID)) } } throw DatabaseError.noSuchTable(tableName) } - private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor { + private func foreignKeyViolations(in table: DatabaseObjectID) throws -> RecordCursor { try ForeignKeyViolation.fetchCursor(self, sql: """ - PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier)) + PRAGMA \(table.schemaID.name).foreign_key_check(\(table.name.quotedDatabaseIdentifier)) """) } @@ -884,45 +824,48 @@ extension Database { /// such table exists in the main or temp schema, or in an /// attached database. func canonicalTableName(_ tableName: String) throws -> String? { - for schemaIdentifier in try schemaIdentifiers() { + for schemaID in try fetchSchemaIdentifiers() { // Regular tables - if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) { + if let result = try schema(schemaID).canonicalName(tableName, ofType: .table) { return result } // Master table (sqlite_master, sqlite_temp_master) - // swiftlint:disable:next inclusive_language - let masterTableName = schemaIdentifier.unqualifiedMasterTableName - if tableName.lowercased() == masterTableName.lowercased() { - return masterTableName + let schemaTableName = schemaID.unqualifiedSchemaTableName + if tableName.lowercased() == schemaTableName.lowercased() { + return schemaTableName } } return nil } - func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo { + func schema(_ schemaID: DatabaseSchemaID) throws -> SchemaInfo { if let schemaInfo = schemaCache[schemaID].schemaInfo { return schemaInfo } - let schemaInfo = try SchemaInfo(self, masterTableName: schemaID.masterTableName) + let schemaInfo = try SchemaInfo(self, schemaTableName: schemaID.schemaTableName) schemaCache[schemaID].schemaInfo = schemaInfo return schemaInfo } /// Attempts to perform a table introspection function on a given - /// table and schema + /// table and schema. /// /// - parameter tableName: The name of the table to examine /// - parameter schemaName: The name of the schema to check /// - parameter introspector: An introspection function taking a - /// `TableIdentifier` as the only parameter + /// `DatabaseObjectID` as the only parameter. It the result + /// is nil, introspection fails and this method throws + /// `DatabaseError.noSuchTable`. private func introspect( tableNamed tableName: String, inSchemaNamed schemaName: String, - using introspector: (TableIdentifier) throws -> T? + using introspector: (DatabaseObjectID) throws -> T? ) throws -> T { - let schemaIdentifier = try schemaIdentifier(named: schemaName) - if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + let schemaID = try schemaIdentifier(named: schemaName) + let table = DatabaseObjectID(name: tableName, schemaID: schemaID) + + if let result = try introspector(table) { return result } else { throw DatabaseError.noSuchTable(tableName) @@ -934,8 +877,9 @@ extension Database { /// Returns the columns in a table or a view. /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is nil, known schemas are iterated in + /// SQLite resolution order, and the first matching result is returned. + /// For more information, see . /// /// For example: /// @@ -957,16 +901,16 @@ extension Database { return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:)) } - for schemaIdentifier in try schemaIdentifiers() { - if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + for schemaID in try fetchSchemaIdentifiers() { + if let result = try columns(in: DatabaseObjectID(name: tableName, schemaID: schemaID)) { return result } } throw DatabaseError.noSuchTable(tableName) } - /// Returns nil if table does not exist - private func columns(in table: TableIdentifier) throws -> [ColumnInfo]? { + /// Returns nil if table does not exist. + private func columns(in table: DatabaseObjectID) throws -> [ColumnInfo]? { if let columns = schemaCache[table.schemaID].columns(in: table.name) { return columns.value } @@ -1013,10 +957,10 @@ extension Database { // 2 | lastName | TEXT | 0 | NULL | 0 | 0 let columnInfoQuery: String if sqlite3_libversion_number() < 3026000 { - columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))" + columnInfoQuery = "PRAGMA \(table.schemaID.name).table_info(\(table.name.quotedDatabaseIdentifier))" } else { // Use PRAGMA table_xinfo so that we can load generated columns - columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_xinfo(\(table.name.quotedDatabaseIdentifier))" + columnInfoQuery = "PRAGMA \(table.schemaID.name).table_xinfo(\(table.name.quotedDatabaseIdentifier))" } let columns = try ColumnInfo .fetchAll(self, sql: columnInfoQuery) @@ -1110,6 +1054,109 @@ extension Database { } } +/// The identifier of an SQLite schema. +/// +/// For more information, see +public struct DatabaseSchemaID: Hashable, Sendable { + private enum Impl: Hashable { + /// The main database + case main + + /// The temp database + case temp + + /// An attached database: + case attached(String) + } + + private var impl: Impl + + private init(impl: Impl) { + self.impl = impl + } + + init(name: String) { + switch name { + case "main": self = .main + case "temp": self = .temp + case let other: self = .attached(other) + } + } + + /// The identifier of the "main" database schema. + public static let main = DatabaseSchemaID(impl: .main) + + /// The identifier of the "temp" database schema. + public static let temp = DatabaseSchemaID(impl: .temp) + + /// The identifier of an attached database schema. + public static func attached(_ name: String) -> DatabaseSchemaID { + DatabaseSchemaID(impl: .attached(name)) + } + + /// The name of the schema, suitable for inclusion in SQL queries. + /// + /// For example: + /// + /// SELECT * FROM main.player; + /// ~~~~ + public var name: String { + switch impl { + case .main: return "main" + case .temp: return "temp" + case let .attached(name): return name + } + } + + /// The name of the schema sqlite table. + /// + /// For more information, see + public var schemaTableName: String { + switch impl { + case .main: return "sqlite_master" + case .temp: return "sqlite_temp_master" + case let .attached(name): return "\(name).sqlite_master" + } + } + + /// The name of the schema sqlite table, without the schema name. + var unqualifiedSchemaTableName: String { + switch impl { + case .main, .attached: return "sqlite_master" + case .temp: return "sqlite_temp_master" + } + } +} + +/// The identifier of an object in the database (table, view, etc.) +public struct DatabaseObjectID: Hashable, Sendable { + /// The object name. + public var name: String + + /// The SQLite schema. + public var schemaID: DatabaseSchemaID + + public init(name: String, schemaID: DatabaseSchemaID) { + self.name = name + self.schemaID = schemaID + } + + /// Returns a quoted version of the identifier, for safe insertion in + /// an SQL query. + /// + /// For example: + /// + /// ``` + /// let object = DatabaseObjectID(name: "player", schemaID: .temp) + /// + /// // SELECT * FROM temp.player + /// db.execute(sql: "SELECT * FROM \(object.quotedDatabaseIdentifier)") + /// ``` + var quotedDatabaseIdentifier: String { + "\(schemaID.name).\(name.quotedDatabaseIdentifier)" + } +} + /// Information about a column of a database table. /// /// You get `ColumnInfo` instances with the ``Database/columns(in:in:)`` @@ -1480,7 +1527,7 @@ public struct PrimaryKeyInfo: Sendable { return columnInfos } } - + /// When not nil, the name of the column that contains the /// `INTEGER PRIMARY KEY`. public var rowIDColumn: String? { @@ -1587,7 +1634,7 @@ struct TableInfo: FetchableRecord { static let virtual = Kind(rawValue: "virtual") } - var schemaID: Database.SchemaIdentifier + var schemaID: DatabaseSchemaID var name: String var kind: Kind var columnCount: Int @@ -1595,15 +1642,7 @@ struct TableInfo: FetchableRecord { var strict: Bool init(row: Row) throws { - switch row[0] as String { - case "main": - schemaID = .main - case "temp": - schemaID = .temp - case let name: - schemaID = .attached(name) - } - + schemaID = DatabaseSchemaID(name: row[0] as String) name = row[1] kind = Kind(rawValue: row[2]) columnCount = row[3] @@ -1667,10 +1706,10 @@ struct SchemaInfo: Equatable { } extension SchemaInfo { - /// - parameter masterTable: "sqlite_master" or "sqlite_temp_master" - init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language + /// - parameter schemaTableName: "sqlite_master" or "sqlite_temp_master" + init(_ db: Database, schemaTableName: String) throws { objects = try SchemaObject.fetchSet(db, sql: """ - SELECT type, name, tbl_name, sql FROM \(masterTableName) - """) + SELECT type, name, tbl_name, sql FROM \(schemaTableName) + """) } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 271b53f60..9c9dd2da6 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -256,8 +256,8 @@ extension DatabaseRegion { } } else { // full database - return try db.schemaIdentifiers().flatMap { schemaIdentifier in - let schema = try db.schema(schemaIdentifier) + return try db.fetchSchemaIdentifiers().flatMap { schemaID in + let schema = try db.schema(schemaID) return try schema.objects .filter { $0.type == .table } .flatMap { table in diff --git a/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md b/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md index ee114e8c1..12436970a 100644 --- a/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md +++ b/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md @@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k ### Supporting Types +- ``DatabaseSchemaID`` +- ``DatabaseObjectID`` - ``ColumnInfo`` - ``ForeignKeyInfo`` - ``IndexInfo`` diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index f1b38d7b5..a3c5bfe37 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -123,7 +123,7 @@ struct SQLForeignKeyRequest { } private func tableType(_ db: Database, for name: String) throws -> TableType? { - for schemaID in try db.schemaIdentifiers() { + for schemaID in try db.fetchSchemaIdentifiers() { if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) { return TableType(isView: false) } From d040588849633cb498c110115d0d9db2c3c51b8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Aug 2025 13:58:45 +0200 Subject: [PATCH 21/45] Database.fetchPrimitivePrimaryKey(forTable:) This method is necessary for the customization of schema introspection: it must be possible to fallback on the primitive SQLite schema introspection when needed. --- GRDB/Core/Database+Schema.swift | 38 ++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index fa08cef1e..a253d61e8 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -385,11 +385,27 @@ extension Database { return primaryKey.value } - if try !tableExists(table) { - // Views, CTEs, etc. have no primary key. + if let primaryKey = try fetchPrimitivePrimaryKey(forTable: table) { + schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name) + return primaryKey + } else { schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name) return nil } + } + + /// Fetches the primary key for the database table identified + /// by `table`, or returns nil if the database schema does not contain + /// that table. + /// + /// This method relies entirely on SQLite schema introspection. + func fetchPrimitivePrimaryKey(forTable table: DatabaseObjectID) throws -> PrimaryKeyInfo? { + SchedulingWatchdog.preconditionValidQueue(self) + + if try !tableExists(table) { + // Only tables have a primary key. Views, CTE, etc. do not. + return nil + } // https://www.sqlite.org/pragma.html // @@ -414,22 +430,20 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | name | TEXT | 0 | NULL | 0 | // 2 | score | INTEGER | 0 | NULL | 0 | - guard let columns = try self.columns(in: table) else { // table does not exist - schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name) return nil } - let primaryKey: PrimaryKeyInfo let pkColumns = columns .filter { $0.primaryKeyIndex > 0 } .sorted { $0.primaryKeyIndex < $1.primaryKeyIndex } switch pkColumns.count { case 0: - // No explicit primary key => primary key is hidden rowID column - primaryKey = .hiddenRowID + // No explicit primary key => primary key is the hidden rowID column + return .hiddenRowID + case 1: // Single column let pkColumn = pkColumns[0] @@ -455,17 +469,15 @@ extension Database { // FIXME: We ignore the exception, and consider all INTEGER primary // keys as aliases for the rowid: if pkColumn.type.uppercased() == "INTEGER" { - primaryKey = .rowID(pkColumn) + return .rowID(pkColumn) } else { - primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table)) + return try .regular([pkColumn], tableHasRowID: tableHasRowID(table)) } + default: // Multi-columns primary key - primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table)) + return try .regular(pkColumns, tableHasRowID: tableHasRowID(table)) } - - schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name) - return primaryKey } /// Returns whether the column identifies the rowid column From d7d61add23d3cff5cff60fcd309121e95cbd92cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Sep 2025 07:18:37 +0200 Subject: [PATCH 22/45] DatabaseSchemaSource customizes the primary key of database views --- GRDB.xcodeproj/project.pbxproj | 4 + GRDB/Core/Configuration.swift | 10 ++ GRDB/Core/Database+Schema.swift | 125 ++++++++++++++---- GRDB/Core/DatabaseSchemaSource.swift | 63 +++++++++ .../Extension/Configuration.md | 5 + GRDBCustom.xcodeproj/project.pbxproj | 4 + 6 files changed, 188 insertions(+), 23 deletions(-) create mode 100644 GRDB/Core/DatabaseSchemaSource.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index fe7d767db..1a3793b4c 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -81,6 +81,7 @@ 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; }; + 562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; }; 562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; }; 562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; }; 562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; @@ -503,6 +504,7 @@ 56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = ""; }; + 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = ""; }; 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; @@ -1592,6 +1594,7 @@ 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */, 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, + 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2208,6 +2211,7 @@ 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, + 562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */, 56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */, 563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, 564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 21cc6dea9..471177636 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -421,6 +421,16 @@ public struct Configuration: Sendable { /// reveals that a lot of time is spent opening new SQLite connections. public var persistentReadOnlyConnections = false + // MARK: - Database Schema + + /// A custom schema source. + /// + /// The use case for a custom schema source is enabling GRDB features that + /// would not work with the built-in schema introspection that is provided + /// by SQLite. For example, a custom schema source can help record types + /// that read or write in a database view. + public var schemaSource: (any DatabaseSchemaSource)? + // MARK: - Factory Configuration /// Creates a factory configuration. diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index a253d61e8..dfe5a9b19 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -331,6 +331,9 @@ extension Database { /// SQLite resolution order, and the first matching result is returned. /// For more information, see . /// + /// Database views are supported, if the connection is configured with + /// a schema source. See ``Configuration/schemaSource``. + /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if /// the specified schema does not exist, or if no such table exists in /// the main or temp schema, or in an attached database. @@ -385,7 +388,20 @@ extension Database { return primaryKey.value } - if let primaryKey = try fetchPrimitivePrimaryKey(forTable: table) { + var primaryKey: PrimaryKeyInfo? + + if let schemaSource = configuration.schemaSource, + try viewExists(table.name, in: table.schemaID.name), + let primaryKeyColumns = try schemaSource.columnsForPrimaryKey(self, inView: table) + { + primaryKey = try fetchPrimitivePrimaryKey(forView: table, columns: primaryKeyColumns) + } + + if primaryKey == nil { + primaryKey = try fetchPrimitivePrimaryKey(forTable: table) + } + + if let primaryKey { schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name) return primaryKey } else { @@ -471,15 +487,55 @@ extension Database { if pkColumn.type.uppercased() == "INTEGER" { return .rowID(pkColumn) } else { - return try .regular([pkColumn], tableHasRowID: tableHasRowID(table)) + return try .regular([pkColumn], tableHasRowID: fetchTableHasRowID(table)) } default: // Multi-columns primary key - return try .regular(pkColumns, tableHasRowID: tableHasRowID(table)) + return try .regular(pkColumns, tableHasRowID: fetchTableHasRowID(table)) } } + /// Fetches a customized primary key for the database view identified + /// by `view`. + /// + /// Nil is returned in the view does not exist, or if `columns` is empty. + /// + /// - precondition: If the view exists, columns must exist, must + /// identify a unique row, and must be not null. + func fetchPrimitivePrimaryKey( + forView view: DatabaseObjectID, + columns: [String] + ) throws -> PrimaryKeyInfo? { + if columns.isEmpty { + return nil + } + + guard let infos = try fetchPrimitiveColumns(in: view) else { + // View does not exist + return nil + } + + let pkInfos = columns.enumerated().map { index, column in + guard var info = infos.first(where: { $0.name.lowercased() == column.lowercased() }) else { + // The requested column does not exist in the database schema. + // Is it a programmer error, or a runtime error? + // Let's make it a programmer error to start with. + fatalError(""" + No such column in \(view.schemaID.viewNameInErrorMessages(view.name)): \(column) + """) + } + + // Rewrite primaryKeyIndex, and use a 1-based index, as + // documented in https://www.sqlite.org/pragma.html#pragma_table_info + info.primaryKeyIndex = index + 1 + + return info + } + + return .regular(pkInfos, tableHasRowID: false /* views have no rowid */) + } + /// Returns whether the column identifies the rowid column func columnIsRowID(_ column: String, of tableName: String) throws -> Bool { let pk = try primaryKey(tableName) @@ -489,19 +545,16 @@ extension Database { /// Returns whether the table has a rowid column. /// /// - precondition: table exists. - private func tableHasRowID(_ table: DatabaseObjectID) throws -> Bool { - // No need to cache the result, because this information feeds - // `PrimaryKeyInfo`, which is cached. - + private func fetchTableHasRowID(_ table: DatabaseObjectID) throws -> Bool { // Prefer PRAGMA table_list if available #if GRDBCUSTOMSQLITE || GRDBCIPHER // Maybe SQLCipher is too old: check actual version if sqlite3_libversion_number() >= 3037000 { - return try self.table(for: table)!.hasRowID + return try self.table(for: table)!.isWithoutRowIDTable == false } #else if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+ - return try self.table(for: table)!.hasRowID + return try self.table(for: table)!.isWithoutRowIDTable == false } #endif @@ -927,6 +980,30 @@ extension Database { return columns.value } + if var columns = try fetchPrimitiveColumns(in: table) { + // Discard hidden columns, so that the result of this method + // matches the columns in `SELECT *`, and avoids surprises. + columns = columns.filter { + // https://www.sqlite.org/pragma.html#pragma_table_xinfo + $0.hidden != 1 + } + schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name) + return columns + } else { + // Table does not exist + schemaCache[table.schemaID].set(columns: .missing, forTable: table.name) + return nil + } + } + + /// Fetches the columns in the database table identified by `table`, or + /// returns nil if the database schema does not contain that table. + /// + /// This method relies entirely on SQLite schema introspection. Starting + /// SQLite 3.26.0, it returns all columns, including + /// [generated columns](https://www.sqlite.org/gencol.html) and + /// [hidden columns](https://www.sqlite.org/vtab.html#hiddencol). + func fetchPrimitiveColumns(in table: DatabaseObjectID) throws -> [ColumnInfo]? { // https://www.sqlite.org/pragma.html // // > PRAGMA database.table_info(table-name); @@ -976,23 +1053,13 @@ extension Database { } let columns = try ColumnInfo .fetchAll(self, sql: columnInfoQuery) - .filter { - // Purpose: keep generated columns, but discard hidden ones. - // The "hidden" column magic numbers come from the SQLite - // source code. The values 2 and 3 refer to virtual and stored - // generated columns, respectively, and 1 refer to hidden one. - // Search for COLFLAG_HIDDEN in - // https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a - $0.hidden != 1 - } .sorted(by: { $0.cid < $1.cid }) + if columns.isEmpty { // Table does not exist - schemaCache[table.schemaID].set(columns: .missing, forTable: table.name) return nil } - schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name) return columns } @@ -1138,6 +1205,17 @@ public struct DatabaseSchemaID: Hashable, Sendable { case .temp: return "sqlite_temp_master" } } + + func viewNameInErrorMessages(_ viewName: String) -> String { + switch impl { + case .main: + return "view \(viewName)" + case .temp: + return "temporary view \(viewName)" + case .attached(let schemaName): + return "view \(schemaName).\(viewName)" + } + } } /// The identifier of an object in the database (table, view, etc.) @@ -1242,7 +1320,7 @@ public struct ColumnInfo: FetchableRecord, Sendable { /// The one-based index of the column in the primary key. /// /// For columns that are not part of the primary key, it is zero. - public let primaryKeyIndex: Int + public fileprivate(set) var primaryKeyIndex: Int public init(row: Row) { cid = row["cid"] @@ -1650,7 +1728,8 @@ struct TableInfo: FetchableRecord { var name: String var kind: Kind var columnCount: Int - var hasRowID: Bool + /// False for tables with a rowid, and for views. + var isWithoutRowIDTable: Bool var strict: Bool init(row: Row) throws { @@ -1658,7 +1737,7 @@ struct TableInfo: FetchableRecord { name = row[1] kind = Kind(rawValue: row[2]) columnCount = row[3] - hasRowID = !row[4] + isWithoutRowIDTable = row[4] strict = row[5] } } diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift new file mode 100644 index 000000000..7a6d44938 --- /dev/null +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -0,0 +1,63 @@ +/// A type that provides information about the database schema. +/// +/// ## Overview +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// The use case for a custom schema source is enabling GRDB features that +/// would not work with the built-in schema introspection that is provided +/// by SQLite. For example, a custom schema source can help record types +/// that read or write in a database view. +/// +/// You do not interact directly with values of such a type. Instead, you +/// configure a database connection with ``Configuration/schemaSource``, and +/// you call methods on a +/// ``Database`` connection. +public protocol DatabaseSchemaSource: Sendable { + /// Returns the names of the columns for the primary key in the + /// provided database view. + /// + /// Return nil if no customization should happen. Return an empty array + /// to specify that the view has no primary key. The default + /// implementation returns nil. + /// + /// In your implementation, make sure that: + /// + /// - The returned columns exist in the database schema. + /// - The returned columns identify unique rows. + /// - The returned columns do not contain NULL values. + /// + /// For example: + /// + /// ```swift + /// struct MySchemaSource: DatabaseSchemaSource { + /// func columnsForPrimaryKey( + /// _ db: Database, + /// inView view: DatabaseObjectID + /// ) throws -> [String]? { + /// switch table.name { + /// case "player": + /// // Use the email column as the primary key of this view. + /// return ["email"] + /// + /// default: + /// // Do not customize. + /// return nil + /// } + /// } + /// } + /// ``` + func columnsForPrimaryKey( + _ db: Database, + inView view: DatabaseObjectID + ) throws -> [String]? +} + +extension DatabaseSchemaSource { + public func columnsForPrimaryKey( + _ db: Database, + inView view: DatabaseObjectID + ) throws -> [String]? { + nil + } +} diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index 55f0d770d..bdc5f0e4a 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -96,6 +96,7 @@ do { - ``persistentReadOnlyConnections`` - ``prepareDatabase(_:)`` - ``publicStatementArguments`` +- ``schemaSource`` - ``transactionClock`` - ``TransactionClock`` @@ -106,3 +107,7 @@ do { - ``writeQoS`` - ``targetQueue`` - ``writeTargetQueue`` + +### Supporting Types + +- ``DatabaseSchemaSource`` diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 6590d6f98..ada7796c8 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -60,6 +60,7 @@ 5623B61A2AED39C300436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6182AED39C200436239 /* DatabaseQueueTemporaryCopyTests.swift */; }; 56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; }; 562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; }; + 562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */; }; 562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; }; 562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; }; 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; @@ -516,6 +517,7 @@ 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = ""; }; + 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = ""; }; 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; @@ -1597,6 +1599,7 @@ 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */, 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, + 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2029,6 +2032,7 @@ 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */, 5656A8732295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */, 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, From 2b1980364407f755f9afb0de0fa06e417c7077b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 08:39:20 +0200 Subject: [PATCH 23/45] DatabaseSchemaSource tests --- Tests/GRDBTests/PrimaryKeyInfoTests.swift | 105 ++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index efe2ac8da..ba66b2b94 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -242,4 +242,109 @@ class PrimaryKeyInfoTests: GRDBTestCase { XCTAssertTrue(primaryKey.tableHasRowID) } } + + // MARK: - Customization with DatabaseSchemaSource + + func test_custom_schemaSource_nil_result() throws { + struct MySchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + nil + } + } + + dbConfiguration.schemaSource = MySchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)") + try db.execute(sql: "CREATE VIEW playerView as SELECT id AS playerId, name FROM player") + + do { + let primaryKey = try db.primaryKey("player") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["id"]) + XCTAssertEqual(primaryKey.rowIDColumn, "id") + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + + do { + _ = try db.primaryKey("playerView") + XCTFail("Expected Error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: playerView") + XCTAssertEqual(error.description, "SQLite error 1: no such table: playerView") + } + } + } + + func test_custom_schemaSource_empty_result() throws { + struct MySchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + [] + } + } + + dbConfiguration.schemaSource = MySchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)") + try db.execute(sql: "CREATE VIEW playerView as SELECT id AS playerId, name FROM player") + + do { + let primaryKey = try db.primaryKey("player") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["id"]) + XCTAssertEqual(primaryKey.rowIDColumn, "id") + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + + do { + _ = try db.primaryKey("playerView") + XCTFail("Expected Error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: playerView") + XCTAssertEqual(error.description, "SQLite error 1: no such table: playerView") + } + } + } + + func test_custom_schemaSource_custom_primary_key() throws { + struct MySchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["playerId"] + } + } + + dbConfiguration.schemaSource = MySchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)") + try db.execute(sql: "CREATE VIEW playerView as SELECT id AS playerId, name FROM player") + + do { + let primaryKey = try db.primaryKey("player") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["id"]) + XCTAssertEqual(primaryKey.rowIDColumn, "id") + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + + do { + let primaryKey = try db.primaryKey("playerView") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["playerId"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["playerId"]) + XCTAssertNil(primaryKey.rowIDColumn) + XCTAssertFalse(primaryKey.isRowID) + XCTAssertFalse(primaryKey.tableHasRowID) + } + } + } } From 38f5226e95aebd1667cb625ff380fb5a4ab714d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 11:30:53 +0200 Subject: [PATCH 24/45] Database.table(_:hasUniqueKey:) now accept views --- GRDB/Core/Database+Schema.swift | 36 ++++++++++++++++------------ Tests/GRDBTests/IndexInfoTests.swift | 28 ++++++++++++++++++++++ 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index dfe5a9b19..8febc3767 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1067,6 +1067,9 @@ extension Database { /// returns the columns of the unique key, ordered as the matching index (or /// primary key). The case of returned columns is not guaranteed to match /// the case of input columns. + /// + /// This method accepts both tables and views. For views, the primary + /// key returned by the schemaSource is considered as a unique key. func columnsForUniqueKey( _ columns: some Collection, in tableName: String @@ -1077,23 +1080,26 @@ extension Database { return nil } - // Check rowid - let primaryKey = try self.primaryKey(tableName) - if primaryKey.tableHasRowID && lowercasedColumns == ["rowid"] { - return ["rowid"] + // Check primaryKey (ignoring views if the schemaSource does not customize them). + if let primaryKey = try? self.primaryKey(tableName) { + if primaryKey.tableHasRowID && lowercasedColumns == ["rowid"] { + return ["rowid"] + } + + // Check primaryKey + if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) { + return primaryKey.columns + } } - // Check primaryKey - if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) { - return primaryKey.columns - } - - // Check unique indexes - let matchingIndex = try indexes(on: tableName).first { index in - index.isUnique && Set(index.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) - } - if let matchingIndex { - return matchingIndex.columns + // Check unique indexes (ignoring views) + if try tableExists(tableName) { + let matchingIndex = try indexes(on: tableName).first { index in + index.isUnique && Set(index.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) + } + if let matchingIndex { + return matchingIndex.columns + } } // No matching unique key found diff --git a/Tests/GRDBTests/IndexInfoTests.swift b/Tests/GRDBTests/IndexInfoTests.swift index 9ce46a36f..9ebec7dd8 100644 --- a/Tests/GRDBTests/IndexInfoTests.swift +++ b/Tests/GRDBTests/IndexInfoTests.swift @@ -71,9 +71,37 @@ class IndexInfoTests: GRDBTestCase { try XCTAssertFalse(db.table("citizenships", hasUniqueKey: ["year"])) try XCTAssertFalse(db.table("citizenships", hasUniqueKey: ["personId"])) try XCTAssertFalse(db.table("citizenships", hasUniqueKey: ["countryIsoCode"])) + + try db.execute(sql: "CREATE VIEW personView AS SELECT * FROM persons") + try XCTAssertFalse(db.table("personView", hasUniqueKey: ["rowid"])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: ["id"])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: ["email"])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: [])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: ["name"])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: ["id", "email"])) } } + func testColumnsThatUniquelyIdentityRows_with_view_and_schema_source() throws { + struct MySchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } + } + + dbConfiguration.schemaSource = MySchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") + try db.execute(sql: "CREATE VIEW personView AS SELECT * FROM persons") + + try XCTAssertTrue(db.table("personView", hasUniqueKey: ["id"])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: [])) + try XCTAssertFalse(db.table("personView", hasUniqueKey: ["name"])) + try XCTAssertTrue(db.table("personView", hasUniqueKey: ["id", "email"])) + } + } + // Regression test for https://github.com/groue/GRDB.swift/issues/840 func testIndexOnExpressionIsExcluded() throws { let dbQueue = try makeDatabaseQueue() From c7bbebc80f864252d1b5b32d19fc282a4f4177ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 13:08:53 +0200 Subject: [PATCH 25/45] Change the way we count changes in order to support INSTEAD OF triggers Database.changesCount calls sqlite3_changes(), whose documentation says: > https://sqlite.org/c3ref/changes.html > Changes to a view that are intercepted by INSTEAD OF triggers are not counted. Since we want to support INSTEAD OF triggers well, so that record types can be based on views, we switch to sqlite3_total_changes(). --- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 6 ++++-- GRDB/Record/MutablePersistableRecord+Delete.swift | 3 ++- GRDB/Record/MutablePersistableRecord+Update.swift | 4 +++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index c53cca1c0..95ad8aed4 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -635,8 +635,9 @@ extension QueryInterfaceRequest { @discardableResult public func deleteAll(_ db: Database) throws -> Int { let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db) + let prevCount = db.totalChangesCount try statement.execute() - return db.changesCount + return db.totalChangesCount - prevCount } } @@ -1135,8 +1136,9 @@ extension QueryInterfaceRequest { // database not hit return 0 } + let prevCount = db.totalChangesCount try updateStatement.execute() - return db.changesCount + return db.totalChangesCount - prevCount } /// Updates matching rows, and returns the number of updated rows. diff --git a/GRDB/Record/MutablePersistableRecord+Delete.swift b/GRDB/Record/MutablePersistableRecord+Delete.swift index f800ab244..f1b03f977 100644 --- a/GRDB/Record/MutablePersistableRecord+Delete.swift +++ b/GRDB/Record/MutablePersistableRecord+Delete.swift @@ -53,7 +53,8 @@ extension MutablePersistableRecord { // Nil primary key return false } + let prevCount = db.totalChangesCount try statement.execute() - return db.changesCount > 0 + return (db.totalChangesCount - prevCount) > 0 } } diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index 89d81d817..a248918b6 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -956,8 +956,10 @@ extension MutablePersistableRecord { // Nil primary key try dao.recordNotFound() } + let prevCount = db.totalChangesCount let returned = try fetch(statement) - if db.changesCount == 0 { + let changesCount = db.totalChangesCount - prevCount + if changesCount == 0 { // No row was updated try dao.recordNotFound() } From 9518d74fa6883f1839a7dbb2a62fbb68e8740e29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 13:09:16 +0200 Subject: [PATCH 26/45] Improve error message --- GRDB/Core/Database+Schema.swift | 33 ++++++++++++++++--- .../Request/RequestProtocols.swift | 25 +++++++++++--- Tests/GRDBTests/PrimaryKeyInfoTests.swift | 32 ++++++++++++++---- 3 files changed, 75 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 8febc3767..570fdde97 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -347,7 +347,22 @@ extension Database { return result } } - throw DatabaseError.noSuchTable(tableName) + + if (try? viewExists(tableName, in: schemaName)) == true { + if configuration.schemaSource == nil { + throw DatabaseError(message: """ + The database view '\(tableName)' has no primary key. \ + To support views, provide a custom schema source in Configuration.schemaSource. + """) + } else { + throw DatabaseError(message: """ + The database view '\(tableName)' has no primary key, \ + according to Configuration.schemaSource. + """) + } + } else { + throw DatabaseError.noSuchTable(tableName) + } } /// Returns the name of the single-column primary key. @@ -370,10 +385,18 @@ extension Database { if case .SQLITE_ERROR = error.resultCode, (try? viewExists(tableName)) == true { - fatalError(""" - Filtering by primary key is not available on the database view '\(tableName)'. \ - Use `filter(Column("...") == value)` instead. - """) + if configuration.schemaSource == nil { + fatalError(""" + Filtering by primary key is not available on the database view '\(tableName)'. \ + Instead, use `filter(Column("...") == value)`, or provide \ + a custom schema source in Configuration.schemaSource. + """) + } else { + fatalError(""" + Filtering by primary key requires a single-column primary key in the view '\(tableName)'. \ + No such primary key is configured by Configuration.schemaSource. + """) + } } else { throw error } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 9e13293f6..9b88e64dd 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -826,10 +826,27 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // ("foo", "bar") do not contain a unique key (primary key // or unique index). guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { - fatalError(""" - table \(databaseTableName) has no unique key on column(s) \ - \(key.keys.sorted().joined(separator: ", ")) - """) + if (try? db.viewExists(databaseTableName)) == true { + if db.configuration.schemaSource == nil { + fatalError(""" + view \(databaseTableName) has no unique key on column(s) \ + \(key.keys.sorted().joined(separator: ", ")). To support \ + keys in views, provide a custom schema source in \ + Configuration.schemaSource. + """) + } else { + fatalError(""" + view \(databaseTableName) has no unique key on column(s) \ + \(key.keys.sorted().joined(separator: ", ")), \ + according to Configuration.schemaSource. + """) + } + } else { + fatalError(""" + table \(databaseTableName) has no unique key on column(s) \ + \(key.keys.sorted().joined(separator: ", ")) + """) + } } let lowercaseColumns = columns.map { $0.lowercased() } diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index ba66b2b94..25c9485ce 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -26,8 +26,16 @@ class PrimaryKeyInfoTests: GRDBTestCase { XCTFail("Expected Error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) - XCTAssertEqual(error.message, "no such table: items") - XCTAssertEqual(error.description, "SQLite error 1: no such table: items") + XCTAssertEqual(error.message, """ + The database view 'items' has no primary key. \ + To support views, provide a custom schema source \ + in Configuration.schemaSource. + """) + XCTAssertEqual(error.description, """ + SQLite error 1: The database view 'items' has no primary key. \ + To support views, provide a custom schema source \ + in Configuration.schemaSource. + """) } } } @@ -273,8 +281,14 @@ class PrimaryKeyInfoTests: GRDBTestCase { XCTFail("Expected Error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) - XCTAssertEqual(error.message, "no such table: playerView") - XCTAssertEqual(error.description, "SQLite error 1: no such table: playerView") + XCTAssertEqual(error.message, """ + The database view 'playerView' has no primary key, \ + according to Configuration.schemaSource. + """) + XCTAssertEqual(error.description, """ + SQLite error 1: The database view 'playerView' has no primary key, \ + according to Configuration.schemaSource. + """) } } } @@ -307,8 +321,14 @@ class PrimaryKeyInfoTests: GRDBTestCase { XCTFail("Expected Error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) - XCTAssertEqual(error.message, "no such table: playerView") - XCTAssertEqual(error.description, "SQLite error 1: no such table: playerView") + XCTAssertEqual(error.message, """ + The database view 'playerView' has no primary key, \ + according to Configuration.schemaSource. + """) + XCTAssertEqual(error.description, """ + SQLite error 1: The database view 'playerView' has no primary key, \ + according to Configuration.schemaSource. + """) } } } From 2e433a3cb2475b8969cd5aea56d888c8f63b4510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 13:40:14 +0200 Subject: [PATCH 27/45] Update TableRecordDeleteTests with record types based on database views --- Tests/GRDBTests/GRDBTestCase.swift | 5 +- Tests/GRDBTests/TableRecordDeleteTests.swift | 412 ++++++++++++++++++- 2 files changed, 399 insertions(+), 18 deletions(-) diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index c93a23ad5..915702a98 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -70,7 +70,10 @@ class GRDBTestCase: XCTestCase { var sqlQueries: [String] { _sqlQueriesMutex.load() } // Automatically updated by default dbConfiguration - var lastSQLQuery: String? { sqlQueries.last } + var lastSQLQuery: String? { + // Skip comments that may be inserted by triggers and virtual tables. + sqlQueries.last { !$0.hasPrefix("--") } + } override func setUp() { super.setUp() diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index a2fe139fe..87575b267 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -1,6 +1,7 @@ import XCTest import GRDB +// Table records private struct Hacker : TableRecord { static let databaseTableName = "hackers" var id: Int64? // Optional @@ -26,6 +27,40 @@ private struct Citizenship : TableRecord { static let databaseTableName = "citizenships" } +// View records + +private struct PersonView : Codable, PersistableRecord, FetchableRecord, Hashable { + static let databaseTableName = "personsView" + var id: Int64 // Non-optional + var name: String + var email: String + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + } +} + +extension PersonView: Identifiable { } + +private struct CitizenshipView : TableRecord { + static let databaseTableName = "citizenshipsView" +} + +// Schema source + +private struct ViewSchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + switch view.name { + case "personsView": + return ["id"] + case "citizenshipsView": + return ["personId", "countryIsoCode"] + default: + return nil + } + } +} class TableRecordDeleteTests: GRDBTestCase { @@ -34,6 +69,40 @@ class TableRecordDeleteTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE hackers (name TEXT)") try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") try db.execute(sql: "CREATE TABLE citizenships (personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))") + + // mutable views + try db.execute(sql: """ + CREATE VIEW personsView AS SELECT * FROM persons; + -- Insert trigger + CREATE TRIGGER personsView_insert + INSTEAD OF INSERT ON personsView + BEGIN + INSERT INTO persons (id, name, email) + VALUES (NEW.id, NEW.name, NEW.email); + END; + -- Delete trigger + CREATE TRIGGER personsView_delete + INSTEAD OF DELETE ON personsView + BEGIN + DELETE FROM persons WHERE id = OLD.id; + END; + """) + try db.execute(sql: """ + CREATE VIEW citizenshipsView AS SELECT * FROM citizenships; + -- Insert trigger + CREATE TRIGGER citizenshipsView_insert + INSTEAD OF INSERT ON citizenshipsView + BEGIN + INSERT INTO citizenships (personId, countryIsoCode) + VALUES (NEW.personId, NEW.countryIsoCode); + END; + -- Delete trigger + CREATE TRIGGER citizenshipsView_delete + INSTEAD OF DELETE ON citizenshipsView + BEGIN + DELETE FROM citizenships WHERE personId = OLD.personId AND countryIsoCode = OLD.countryIsoCode; + END; + """) } } @@ -76,7 +145,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testSingleColumnPrimaryKey() throws { + func testSingleColumnPrimaryKey_table() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var deleted = try Person.deleteOne(db, key: 1) @@ -114,7 +183,48 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testMultipleColumnPrimaryKey() throws { + func testSingleColumnPrimaryKey_view() throws { + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var deleted = try PersonView.deleteOne(db, key: 1) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1") + XCTAssertFalse(deleted) + + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + deleted = try PersonView.deleteOne(db, key: 1) + XCTAssertTrue(deleted) + XCTAssertEqual(try PersonView.fetchCount(db), 0) + + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + deleted = try PersonView.deleteOne(db, id: 1) + XCTAssertTrue(deleted) + XCTAssertEqual(try PersonView.fetchCount(db), 0) + + do { + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) + let deletedCount = try PersonView.deleteAll(db, keys: [2, 3, 4]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (2, 3, 4)") + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(try PersonView.fetchCount(db), 1) + } + + do { + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) + let deletedCount = try PersonView.deleteAll(db, ids: [2, 3, 4]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (2, 3, 4)") + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(try PersonView.fetchCount(db), 1) + } + } + } + + func testMultipleColumnPrimaryKey_table() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) @@ -135,6 +245,30 @@ class TableRecordDeleteTests: GRDBTestCase { } } + func testMultipleColumnPrimaryKey_view() throws { + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var deleted = try CitizenshipView.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenshipsView\" WHERE (\"personId\" = 1) AND (\"countryIsoCode\" = 'FR')") + XCTAssertFalse(deleted) + + try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"]) + deleted = try CitizenshipView.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) + XCTAssertTrue(deleted) + XCTAssertEqual(try CitizenshipView.fetchCount(db), 0) + + try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"]) + try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "US"]) + try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [2, "US"]) + let deletedCount = try CitizenshipView.deleteAll(db, keys: [["personId": 1, "countryIsoCode": "FR"], ["personId": 1, "countryIsoCode": "US"], ["personId": 1, "countryIsoCode": "DE"]]) + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(try CitizenshipView.fetchCount(db), 1) + } + } + func testUniqueIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -156,7 +290,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testImplicitUniqueIndexOnSingleColumnPrimaryKey() throws { + func testImplicitUniqueIndexOnSingleColumnPrimaryKey_table() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var deleted = try Person.deleteOne(db, key: ["id": 1]) @@ -177,7 +311,31 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDeleteAll() throws { + func testImplicitUniqueIndexOnSingleColumnPrimaryKey_view() throws { + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var deleted = try PersonView.deleteOne(db, key: ["id": 1]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1") + XCTAssertFalse(deleted) + + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + deleted = try PersonView.deleteOne(db, key: ["id": 1]) + XCTAssertTrue(deleted) + XCTAssertEqual(try PersonView.fetchCount(db), 0) + + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) + try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) + let deletedCount = try PersonView.deleteAll(db, keys: [["id": 2], ["id": 3], ["id": 4]]) + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(try PersonView.fetchCount(db), 1) + } + } + + func testRequestDeleteAll_table() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -230,7 +388,63 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDeleteAndFetchStatement() throws { + func testRequestDeleteAll_view() throws { + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + + try dbQueue.inDatabase { db in + try PersonView.deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"") + + try PersonView.filter { $0.name == "Arthur" }.deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"name\" = 'Arthur'") + + try PersonView.filter(key: 1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1") + + try PersonView.filter(keys: [1, 2]).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2)") + + try PersonView.filter(id: 1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1") + + try PersonView.filter(ids: [1, 2]).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2)") + + try PersonView.filter(sql: "id = 1").deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE id = 1") + + try PersonView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE (id = 1) AND (\"name\" = 'Arthur')") + + try PersonView.select { $0.name }.deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"") + + try PersonView.order { $0.name }.deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"") + + if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { + try PersonView.limit(1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" LIMIT 1") + + try PersonView.order { $0.name }.deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"") + + try PersonView.order { $0.name }.limit(1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" ORDER BY \"name\" LIMIT 1") + + try PersonView.order { $0.name }.limit(1, offset: 2).reversed().deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" ORDER BY \"name\" DESC LIMIT 1 OFFSET 2") + + try PersonView.limit(1, offset: 2).reversed().deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" LIMIT 1 OFFSET 2") + } + } + } + + func testRequestDeleteAndFetchStatement_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -264,7 +478,41 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDeleteAndFetchCursor() throws { + func testRequestDeleteAndFetchStatement_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = PersonView.all() + let statement = try request.deleteAndFetchStatement(db, select: { [$0.name] }) + XCTAssertEqual(statement.sql, "DELETE FROM \"personsView\" RETURNING \"name\"") + XCTAssertEqual(statement.columnNames, ["name"]) + } + do { + let request = PersonView.all() + let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns]) + XCTAssertEqual(statement.sql, "DELETE FROM \"personsView\" RETURNING *") + XCTAssertEqual(statement.columnNames, ["id", "name", "email"]) + } + do { + let request = PersonView.all() + let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns(excluding: ["name"])]) + XCTAssertEqual(statement.sql, "DELETE FROM \"personsView\" RETURNING \"id\", \"email\"") + XCTAssertEqual(statement.columnNames, ["id", "email"]) + } + } + } + + func testRequestDeleteAndFetchCursor_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -293,19 +541,11 @@ class TableRecordDeleteTests: GRDBTestCase { _ = try Person.filter(keys: [1, 2]).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") -#if GRDBCUSTOMSQLITE || GRDBCIPHER _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") -#else - _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") - - _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") -#endif _ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *") @@ -323,7 +563,60 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDeleteAndFetchArray() throws { + func testRequestDeleteAndFetchCursor_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + + try dbQueue.inDatabase { db in + _ = try PersonView.all().deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *") + + _ = try PersonView.all().deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *") + + _ = try PersonView.filter { $0.name == "Arthur" }.deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"name\" = 'Arthur' RETURNING *") + + _ = try PersonView.filter(key: 1).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1 RETURNING *") + + _ = try PersonView.filter(keys: [1, 2]).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2) RETURNING *") + + _ = try PersonView.filter(id: 1).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1 RETURNING *") + + _ = try PersonView.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2) RETURNING *") + + _ = try PersonView.filter(sql: "id = 1").deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE id = 1 RETURNING *") + + _ = try PersonView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE (id = 1) AND (\"name\" = 'Arthur') RETURNING *") + + _ = try PersonView.select { $0.name }.deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *") + + _ = try PersonView.order { $0.name }.deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *") + + // No test for LIMIT ... RETURNING ... since this is not supported by SQLite + } + } + + func testRequestDeleteAndFetchArray_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -351,7 +644,37 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDeleteAndFetchSet() throws { + func testRequestDeleteAndFetchArray_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try PersonView(id: 1, name: "Arthur", email: "arthur@example.com").insert(db) + try PersonView(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) + try PersonView(id: 3, name: "Craig", email: "craig@example.com").insert(db) + + let request = PersonView.filter { $0.id != 2 } + let deletePersons = try request + .deleteAndFetchAll(db) + .sorted(by: { $0.id < $1.id }) + XCTAssertEqual(deletePersons, [ + PersonView(id: 1, name: "Arthur", email: "arthur@example.com"), + PersonView(id: 3, name: "Craig", email: "craig@example.com"), + ]) + } + } + + func testRequestDeleteAndFetchSet_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -377,7 +700,35 @@ class TableRecordDeleteTests: GRDBTestCase { } } - func testRequestDeleteAndFetchIds() throws { + func testRequestDeleteAndFetchSet_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try PersonView(id: 1, name: "Arthur", email: "arthur@example.com").insert(db) + try PersonView(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) + try PersonView(id: 3, name: "Craig", email: "craig@example.com").insert(db) + + let request = PersonView.filter { $0.id != 2 } + let deletePersons = try request.deleteAndFetchSet(db) + XCTAssertEqual(deletePersons, [ + PersonView(id: 1, name: "Arthur", email: "arthur@example.com"), + PersonView(id: 3, name: "Craig", email: "craig@example.com"), + ]) + } + } + + func testRequestDeleteAndFetchIds_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -400,6 +751,32 @@ class TableRecordDeleteTests: GRDBTestCase { } } + func testRequestDeleteAndFetchIds_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try PersonView(id: 1, name: "Arthur", email: "arthur@example.com").insert(db) + try PersonView(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) + try PersonView(id: 3, name: "Craig", email: "craig@example.com").insert(db) + + let request = PersonView.filter { $0.id != 2 } + let deletedIds = try request.deleteAndFetchIds(db) + XCTAssertEqual(deletedIds, [1, 3]) + } + } + + #warning("TODO: duplicate test with views") func testJoinedRequestDeleteAll() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -460,6 +837,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } + #warning("TODO: duplicate test with views") func testJoinedRequestDeleteAndFetch() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { From 75e99861af2070da3b7319e83f32d83455e1d50f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 14:18:36 +0200 Subject: [PATCH 28/45] Update TableRecordUpdateTests with record types based on database views --- Tests/GRDBTests/TableRecordUpdateTests.swift | 460 ++++++++++++++++++- 1 file changed, 450 insertions(+), 10 deletions(-) diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index b851b6538..410f10bf8 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable { +private struct Player: Codable, Identifiable, PersistableRecord, FetchableRecord, Hashable { var id: Int64 var name: String var score: Int @@ -24,7 +24,45 @@ private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable { } } -extension Player: Identifiable { } +private struct PlayerView: Codable, Identifiable, PersistableRecord, FetchableRecord, Hashable { + var id: Int64 + var name: String + var score: Int + var bonus: Int + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + static let bonus = Column(CodingKeys.bonus) + } + + static func createTable(_ db: Database) throws { + try db.execute(sql: """ + CREATE VIEW playerView AS SELECT * FROM player; + -- Insert trigger + CREATE TRIGGER playerView_insert + INSTEAD OF INSERT ON playerView + BEGIN + INSERT INTO player (id, name, score, bonus) + VALUES (NEW.id, NEW.name, NEW.score, NEW.bonus); + END; + -- Update trigger + CREATE TRIGGER playerView_update + INSTEAD OF UPDATE ON playerView + BEGIN + UPDATE player SET name = NEW.name, score = NEW.score, bonus = NEW.bonus + WHERE id = OLD.id; + END; + """) + } +} + +private struct ViewSchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } +} private typealias Columns = Player.Columns @@ -35,7 +73,7 @@ private extension QueryInterfaceRequest { } class TableRecordUpdateTests: GRDBTestCase { - func testRequestUpdateAll() throws { + func testRequestUpdateAll_table() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) let assignment = Columns.score.set(to: 0) @@ -119,7 +157,95 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAll_DatabaseComponents() throws { + func testRequestUpdateAll_view() throws { + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + let assignment = Columns.score.set(to: 0) + + try PlayerView.updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + try PlayerView.filter { $0.name == "Arthur" }.updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE \"name\" = 'Arthur' + """) + + try PlayerView.filter(key: 1).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" = 1 + """) + + try PlayerView.filter(keys: [1, 2]).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2) + """) + + try PlayerView.filter(id: 1).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" = 1 + """) + + try PlayerView.filter(ids: [1, 2]).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2) + """) + + try PlayerView.filter(sql: "id = 1").updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE id = 1 + """) + + try PlayerView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur') + """) + + try PlayerView.select { $0.name }.updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + try PlayerView.order { $0.name }.updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { + try PlayerView.limit(1).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 LIMIT 1 + """) + + try PlayerView.order { $0.name }.updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + try PlayerView.order { $0.name }.limit(1).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" LIMIT 1 + """) + + try PlayerView.order { $0.name }.limit(1, offset: 2).reversed().updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2 + """) + + try PlayerView.limit(1, offset: 2).reversed().updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 LIMIT 1 OFFSET 2 + """) + } + } + } + + func testRequestUpdateAll_DatabaseComponents_table() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -202,7 +328,94 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchStatement() throws { + func testRequestUpdateAll_DatabaseComponents_view() throws { + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + + try PlayerView.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + try PlayerView.filter { $0.name == "Arthur" }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE \"name\" = 'Arthur' + """) + + try PlayerView.filter(key: 1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" = 1 + """) + + try PlayerView.filter(keys: [1, 2]).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2) + """) + + try PlayerView.filter(id: 1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" = 1 + """) + + try PlayerView.filter(ids: [1, 2]).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2) + """) + + try PlayerView.filter(sql: "id = 1").updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE id = 1 + """) + + try PlayerView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur') + """) + + try PlayerView.select { $0.name }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + try PlayerView.order { $0.name }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { + try PlayerView.limit(1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 LIMIT 1 + """) + + try PlayerView.order { $0.name }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 + """) + + try PlayerView.order { $0.name }.limit(1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" LIMIT 1 + """) + + try PlayerView.order { $0.name }.limit(1, offset: 2).reversed().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2 + """) + + try PlayerView.limit(1, offset: 2).reversed().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "playerView" SET "score" = 0 LIMIT 1 OFFSET 2 + """) + } + } + } + + func testRequestUpdateAndFetchStatement_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -241,7 +454,46 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchStatement_DatabaseComponents() throws { + func testRequestUpdateAndFetchStatement_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + let assignment = Columns.score.set(to: 0) + + do { + let request = PlayerView.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [Column("score")]) + XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"score\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["score"]) + } + do { + let request = PlayerView.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns]) + XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING *") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"]) + } + do { + let request = PlayerView.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns(excluding: ["name"])]) + XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"]) + } + } + } + + func testRequestUpdateAndFetchStatement_DatabaseComponents_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -279,7 +531,46 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchCursor() throws { + func testRequestUpdateAndFetchStatement_DatabaseComponents_view() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard Database.sqliteLibVersionNumber >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + + do { + let request = PlayerView.all() + let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { [$0.score] } + XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"score\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["score"]) + } + do { + let request = PlayerView.all() + let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { _ in [.allColumns] } + XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING *") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"]) + } + do { + let request = PlayerView.all() + let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { _ in [.allColumns(excluding: ["name"])] } + XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"]) + } + } + } + + func testRequestUpdateAndFetchCursor_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -306,7 +597,47 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchCursor_DatabaseComponents() throws { + func testRequestUpdateAndFetchCursor_view() throws { + #warning("TODO: document this caveat") + // Mixing INSTEAD OF triggers and RETURNING used to trigger a bug + // that was fixed in SQLite 3.42. The SQLite test linked below + // landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16. + // (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2) + // + guard Database.sqliteLibVersionNumber >= 3042000 else { + throw XCTSkip("RETURNING and INSTEAD OF are buggy") + } + +#if !GRDBCUSTOMSQLITE && !GRDBCIPHER + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + // Fail in iOS 15.5 (SQLite 3.37) + // Fail in iOS 16.4 (SQLite 3.39) + // Fail in iOS 17.0 (SQLite 3.39) + // Passes in iOS 17.2 (SQLite 3.43) + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = PlayerView.filter { $0.id != 2 } + let cursor = try request.updateAndFetchCursor(db, [Columns.score += 100]) + let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0), + PlayerView(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + + func testRequestUpdateAndFetchCursor_DatabaseComponents_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -333,7 +664,42 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchAll() throws { + func testRequestUpdateAndFetchCursor_DatabaseComponents_view() throws { + // Mixing INSTEAD OF triggers and RETURNING used to trigger a bug + // that was fixed in SQLite 3.42. The SQLite test linked below + // landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16. + // (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2) + // + guard Database.sqliteLibVersionNumber >= 3042000 else { + throw XCTSkip("RETURNING and INSTEAD OF are buggy") + } + +#if !GRDBCUSTOMSQLITE && !GRDBCIPHER + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = PlayerView.filter { $0.id != 2 } + let cursor = try request.updateAndFetchCursor(db) { [$0.score += 100] } + let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0), + PlayerView(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + + func testRequestUpdateAndFetchAll_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -361,7 +727,43 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchAll_DatabaseComponents() throws { + func testRequestUpdateAndFetchAll_view() throws { + // Mixing INSTEAD OF triggers and RETURNING used to trigger a bug + // that was fixed in SQLite 3.42. The SQLite test linked below + // landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16. + // (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2) + // + guard Database.sqliteLibVersionNumber >= 3042000 else { + throw XCTSkip("RETURNING and INSTEAD OF are buggy") + } + +#if !GRDBCUSTOMSQLITE && !GRDBCIPHER + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = PlayerView.filter { $0.id != 2 } + let updatedPlayers = try request + .updateAndFetchAll(db, [Columns.score += 100]) + .sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0), + PlayerView(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + + func testRequestUpdateAndFetchAll_DatabaseComponents_table() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") @@ -389,6 +791,42 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testRequestUpdateAndFetchAll_DatabaseComponents_view() throws { + // Mixing INSTEAD OF triggers and RETURNING used to trigger a bug + // that was fixed in SQLite 3.42. The SQLite test linked below + // landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16. + // (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2) + // + guard Database.sqliteLibVersionNumber >= 3042000 else { + throw XCTSkip("RETURNING and INSTEAD OF are buggy") + } + +#if !GRDBCUSTOMSQLITE && !GRDBCIPHER + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + // Views need a schema source + dbConfiguration.schemaSource = ViewSchemaSource() + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try PlayerView.createTable(db) + try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = PlayerView.filter { $0.id != 2 } + let updatedPlayers = try request + .updateAndFetchAll(db) { [$0.score += 100] } + .sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0), + PlayerView(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + func testRequestUpdateAndFetchSet() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { @@ -1242,6 +1680,7 @@ class TableRecordUpdateTests: GRDBTestCase { } } + #warning("TODO: duplicate test with views") func testJoinedRequestUpdate() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -1314,6 +1753,7 @@ class TableRecordUpdateTests: GRDBTestCase { } } + #warning("TODO: duplicate test with views") func testJoinedRequestUpdate_DatabaseComponents() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { From 26ebd7e1476bd304c1a85daab40542d6001ed74d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 19:35:56 +0200 Subject: [PATCH 29/45] Update outdated comments --- GRDB/Core/Database+Schema.swift | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 570fdde97..1aba1c581 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -368,7 +368,8 @@ extension Database { /// Returns the name of the single-column primary key. /// /// A fatal error is raised if the primary key has several columns, or - /// if `tableName` is the name of a database view. + /// if `tableName` is the name of a database view that is not customized + /// with the schemaSource. func filteringPrimaryKeyColumn(_ tableName: String) throws -> String { do { let primaryKey = try primaryKey(tableName) @@ -561,6 +562,7 @@ extension Database { /// Returns whether the column identifies the rowid column func columnIsRowID(_ column: String, of tableName: String) throws -> Bool { + #warning("TODO: test with database views") let pk = try primaryKey(tableName) return pk.rowIDColumn == column || (pk.tableHasRowID && column.uppercased() == "ROWID") } @@ -1156,6 +1158,7 @@ extension Database { return primaryKey.columns } } else { + #warning("TODO: use the primary key if available") // View: check all columns for existence return try columns(in: tableName).map(\.name) } @@ -1703,13 +1706,15 @@ public struct PrimaryKeyInfo: Sendable { // try db.primaryKey("player").fastPrimaryKeyColumn // "rowid" return Column.rowID.name } else if columns.count == 1 { - // WITHOUT ROWID table: use primary key column + // WITHOUT ROWID table or view customized with the schemaSource: + // use primary key column // // // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID // try db.primaryKey("player").fastPrimaryKeyColumn // "uuid" return columns[0] } else { - // WITHOUT ROWID table with a multi-columns primary key + // WITHOUT ROWID table or view customized with the schemaSource + // with a multi-columns primary key return nil } } From 93d0baeade4365d0b23ed66d77626cb444ff0519 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Aug 2025 19:41:52 +0200 Subject: [PATCH 30/45] The stable order for views is provided by the schemaSource, if any --- GRDB/QueryInterface/SQL/SQLRelation.swift | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index fcbb7b884..764d236a0 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -285,12 +285,15 @@ extension SQLRelation: Refinable { func withStableOrder() -> Self { with { relation in relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in - if try db.tableExists(source.tableName) { + do { + #warning("TODO: test with views") // Order by primary key. Don't order by rowid because those are // not stable: rowids can change after a vacuum. return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering } - } else { - // Support for views: create a stable order from all columns: + } catch { + // Could not find the primary key. Assume we're ordering + // a view that is not customized with the schemaSource. + // Create a stable order from all columns: // ORDER BY 1, 2, 3, ... let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db) return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering } From e1abafaae3287b445bb0d1515bc682744e9875a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Sep 2025 08:52:35 +0200 Subject: [PATCH 31/45] Ignore schema source during migrations --- GRDB/Core/Configuration.swift | 4 +++ GRDB/Core/Database+Schema.swift | 24 +++++++++++-- GRDB/Core/Database.swift | 4 +++ GRDB/Migration/Migration.swift | 36 +++++++++++++------ .../Request/RequestProtocols.swift | 2 +- Tests/GRDBTests/DatabaseMigratorTests.swift | 34 ++++++++++++++++++ 6 files changed, 90 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 471177636..529f5bc6d 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -429,6 +429,10 @@ public struct Configuration: Sendable { /// would not work with the built-in schema introspection that is provided /// by SQLite. For example, a custom schema source can help record types /// that read or write in a database view. + /// + /// The schema source has not effect during database migrations + /// performed by ``DatabaseMigrator``. Those access the raw SQLite + /// schema, unaltered. public var schemaSource: (any DatabaseSchemaSource)? // MARK: - Factory Configuration diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 1aba1c581..bf02bbf1d 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -35,6 +35,24 @@ extension Database { // MARK: - Database Schema + /// Runs the provided closure with the provided schema source. + func withSchemaSource( + _ schemaSource: (any DatabaseSchemaSource)?, + execute block: () throws -> T + ) rethrows -> T { + SchedulingWatchdog.preconditionValidQueue(self) + + let previousSchemaSource = self.schemaSource + self.schemaSource = schemaSource + defer { + self.schemaSource = previousSchemaSource + clearSchemaCache() // Clear from cache the information loaded from the new schema source. + } + + clearSchemaCache() // Clear from cache the information loaded from the previous schema source. + return try block() + } + /// Returns the current schema version (`PRAGMA schema_version`). /// /// For example: @@ -349,7 +367,7 @@ extension Database { } if (try? viewExists(tableName, in: schemaName)) == true { - if configuration.schemaSource == nil { + if schemaSource == nil { throw DatabaseError(message: """ The database view '\(tableName)' has no primary key. \ To support views, provide a custom schema source in Configuration.schemaSource. @@ -386,7 +404,7 @@ extension Database { if case .SQLITE_ERROR = error.resultCode, (try? viewExists(tableName)) == true { - if configuration.schemaSource == nil { + if schemaSource == nil { fatalError(""" Filtering by primary key is not available on the database view '\(tableName)'. \ Instead, use `filter(Column("...") == value)`, or provide \ @@ -414,7 +432,7 @@ extension Database { var primaryKey: PrimaryKeyInfo? - if let schemaSource = configuration.schemaSource, + if let schemaSource, try viewExists(table.name, in: table.schemaID.name), let primaryKeyColumns = try schemaSource.columnsForPrimaryKey(self, inView: table) { diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index e1bc96ee1..0849f851a 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -276,6 +276,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The cache for the available database schemas (main, temp, attached databases). var schemaCache = SchemaCache() + /// To modify the schemaSource, use `withSchemaSource`. + var schemaSource: (any DatabaseSchemaSource)? + /// The cache for statements managed by GRDB. It is distinct from /// `publicStatementCache` so that we do not mess with statement arguments /// set by the user. @@ -442,6 +445,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.description = description self.configuration = configuration + self.schemaSource = configuration.schemaSource self.path = path // We do not report read-only transactions to transaction observers, so diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 5a100bdec..8df0f5ec5 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -8,20 +8,36 @@ struct Migration: Sendable { let identifier: String var foreignKeyChecks: ForeignKeyChecks - let migrate: @Sendable (Database) throws -> Void + // Private so that the guarantees of `run(_:)` are enforced. + private let migrate: @Sendable (Database) throws -> Void + + init( + identifier: String, + foreignKeyChecks: ForeignKeyChecks, + migrate: @escaping @Sendable (Database) throws -> Void + ) { + self.identifier = identifier + self.foreignKeyChecks = foreignKeyChecks + self.migrate = migrate + } func run(_ db: Database) throws { - if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { - switch foreignKeyChecks { - case .deferred: - try runWithDeferredForeignKeysChecks(db) - case .immediate: + // Migrations access the raw SQLite schema, without alteration due + // to the schemaSource. The goal is to ensure that migrations are + // immutable, immune from spooky actions at a distance. + try db.withSchemaSource(nil) { + if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { + switch foreignKeyChecks { + case .deferred: + try runWithDeferredForeignKeysChecks(db) + case .immediate: + try runWithImmediateForeignKeysChecks(db) + case .disabled: + try runWithDisabledForeignKeysChecks(db) + } + } else { try runWithImmediateForeignKeysChecks(db) - case .disabled: - try runWithDisabledForeignKeysChecks(db) } - } else { - try runWithImmediateForeignKeysChecks(db) } } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 9b88e64dd..924528135 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -827,7 +827,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // or unique index). guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { if (try? db.viewExists(databaseTableName)) == true { - if db.configuration.schemaSource == nil { + if db.schemaSource == nil { fatalError(""" view \(databaseTableName) has no unique key on column(s) \ \(key.keys.sorted().joined(separator: ", ")). To support \ diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index b82d221d0..b94d90ccb 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -1109,4 +1109,38 @@ class DatabaseMigratorTests : GRDBTestCase { XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } } + + func test_schemaSource_is_disabled_during_migrations() throws { + struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } + } + + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + var migrator = DatabaseMigrator() + + do { + migrator.registerMigration("A") { db in + try db.execute(sql: "CREATE VIEW myView as SELECT 1 AS id") + // Cache is empty, and schemaSource is disabled. + XCTAssertThrowsError(try db.primaryKey("myView")) + } + try migrator.migrate(dbQueue) + } + + try dbQueue.inDatabase { db in + // Cache was cleared, and schemaSource is active. + XCTAssertNoThrow(try db.primaryKey("myView")) + } + + do { + migrator.registerMigration("B") { db in + // Cache was cleared again, and schemaSource is disabled. + XCTAssertThrowsError(try db.primaryKey("myView")) + } + try migrator.migrate(dbQueue) + } + } } From 5786391dc9cab7a934d0a746216b7b94ee648336 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Sep 2025 20:03:03 +0200 Subject: [PATCH 32/45] RecordMappedOnMutableViewTests --- GRDB.xcodeproj/project.pbxproj | 4 + GRDBCustom.xcodeproj/project.pbxproj | 4 + .../GRDBTests.xcodeproj/project.pbxproj | 14 + .../GRDBTests.xcodeproj/project.pbxproj | 14 + .../RecordMappedOnMutableViewTests.swift | 327 ++++++++++++++++++ 5 files changed, 363 insertions(+) create mode 100644 Tests/GRDBTests/RecordMappedOnMutableViewTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1a3793b4c..913689475 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -224,6 +224,7 @@ 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; + 568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */; }; 5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; }; 56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; }; 56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; }; @@ -676,6 +677,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; + 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = ""; }; 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; @@ -999,6 +1001,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, + 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */, ); name = PersistableRecord; sourceTree = ""; @@ -2013,6 +2016,7 @@ 56677C15241D14450050755D /* FailureTestCase.swift in Sources */, 5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */, 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ada7796c8..1c9fecb11 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -220,6 +220,7 @@ 567E420A242AB3CB00CAAD2C /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */; }; 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; + 568515A62E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */; }; 5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */; }; 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; @@ -700,6 +701,7 @@ 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; + 568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = ""; }; 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; @@ -1013,6 +1015,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, + 568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */, ); name = PersistableRecord; sourceTree = ""; @@ -2257,6 +2260,7 @@ 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */, + 568515A62E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */, 56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */, 5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index a872849dd..7891f358f 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -491,6 +491,8 @@ 567B5C4C2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */; }; 567B5C4D2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; }; 567B5C4E2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; }; + 568515AB2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */; }; + 568515AC2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */; }; 568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; @@ -752,6 +754,7 @@ 567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = ""; }; 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; + 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = ""; }; 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; @@ -1019,6 +1022,7 @@ 56419C9F24A54054004967E1 /* Record+QueryInterfaceRequestTests.swift */, 56419D0C24A5405B004967E1 /* RecordEditedTests.swift */, 56419CAE24A54054004967E1 /* RecordInitializersTests.swift */, + 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */, 567B5C262AD32A2D00629622 /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, 56419D4224A5405F004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, 56419D0824A5405B004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */, @@ -1217,10 +1221,14 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); + inputPaths = ( + ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); + outputPaths = ( + ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks.sh\"\n"; @@ -1256,10 +1264,14 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); + inputPaths = ( + ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); + outputPaths = ( + ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks.sh\"\n"; @@ -1380,6 +1392,7 @@ 56419E4F24A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 567B5C412AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */, 56419E9F24A54063004967E1 /* FetchableRecordTests.swift in Sources */, + 568515AB2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */, 56419E3324A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 56419DFF24A54062004967E1 /* DatabaseCollationTests.swift in Sources */, 56419E9B24A54063004967E1 /* FTS3RecordTests.swift in Sources */, @@ -1630,6 +1643,7 @@ 56419E5024A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 567B5C422AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */, 56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */, + 568515AC2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */, 56419E3424A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 56419E0024A54062004967E1 /* DatabaseCollationTests.swift in Sources */, 56419E9C24A54063004967E1 /* FTS3RecordTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 64c03419a..19c1bb9ad 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -479,6 +479,8 @@ 567B5C462AD32F5900629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */; }; 567B5C472AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; }; 567B5C482AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; }; + 568515A82E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */; }; + 568515A92E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */; }; 568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; }; 568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; }; 568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; }; @@ -748,6 +750,7 @@ 567B5C0F2AD32A0000629622 /* TableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = ""; }; 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = ""; }; 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; + 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = ""; }; 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = ""; }; @@ -1023,6 +1026,7 @@ 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */, 56419F2124A54094004967E1 /* RecordEditedTests.swift */, 56419F4824A54097004967E1 /* RecordInitializersTests.swift */, + 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */, 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, 56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, 56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */, @@ -1223,10 +1227,14 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); + inputPaths = ( + ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); + outputPaths = ( + ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks.sh\"\n"; @@ -1262,10 +1270,14 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); + inputPaths = ( + ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); + outputPaths = ( + ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks.sh\"\n"; @@ -1386,6 +1398,7 @@ 5641A0C424A540A1004967E1 /* MapCursorTests.swift in Sources */, 5641A06E24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, 56419FE424A540A1004967E1 /* AssociationHasOneSQLTests.swift in Sources */, + 568515A92E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */, 56419FDE24A540A1004967E1 /* NumericOverflowTests.swift in Sources */, 5641A0E224A540A1004967E1 /* DatabaseAggregateTests.swift in Sources */, 5641A07E24A540A1004967E1 /* DatabaseErrorTests.swift in Sources */, @@ -1636,6 +1649,7 @@ 5641A0C524A540A1004967E1 /* MapCursorTests.swift in Sources */, 5641A06F24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, 56419FE524A540A1004967E1 /* AssociationHasOneSQLTests.swift in Sources */, + 568515A82E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */, 56419FDF24A540A1004967E1 /* NumericOverflowTests.swift in Sources */, 5641A0E324A540A1004967E1 /* DatabaseAggregateTests.swift in Sources */, 5641A07F24A540A1004967E1 /* DatabaseErrorTests.swift in Sources */, diff --git a/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift new file mode 100644 index 000000000..88d1027a6 --- /dev/null +++ b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift @@ -0,0 +1,327 @@ +import XCTest +import GRDB + +#warning("TODO: document the caveat that didInsert(with:) is unreliable due to last insert rowid not set by triggers: https://sqlite.org/c3ref/last_insert_rowid.html. See also https://sqlite.org/forum/forumpost/fb1c3b4a13") +private struct Player: Codable, + Equatable, + Identifiable, + FetchableRecord, + PersistableRecord +{ + var id: String + var name: String + var teamId: String? + var isCaptain: Bool +} + +private struct Team: Codable, + Equatable, + Identifiable, + FetchableRecord, + PersistableRecord +{ + var id: String + var name: String + + static let captain = hasOne(Captain.self, using: ForeignKey(["teamId"])) +} + +private struct Captain: Codable, + Equatable, + Identifiable, + FetchableRecord, + PersistableRecord +{ + var id: String + var name: String + var teamId: String + + static let team = belongsTo(Team.self, using: ForeignKey(["teamId"])) +} + +private struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + if view.name == "captain" { + return ["id"] + } else { + // Do not customize + return nil + } + } +} + +class RecordMappedOnMutableViewTests : GRDBTestCase { + static func setupDatabase(_ db: Database) throws { + try db.create(table: "team") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + } + + try db.create(table: "player") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.belongsTo("team", onDelete: .setNull) + t.column("isCaptain", .boolean).notNull() + } + + try db.create(indexOn: "player", columns: ["teamId"], options: .unique, condition: Column("isCaptain")) + + try db.execute(sql: """ + CREATE VIEW captain AS + SELECT player.id, player.name, player.teamId + FROM player + WHERE isCaptain; + + -- Insert trigger + CREATE TRIGGER captain_insert + INSTEAD OF INSERT ON captain + BEGIN + -- Remove previous captain + UPDATE player SET isCaptain = 0 + WHERE teamId = NEW.teamId AND isCaptain = 1; + + -- Insert new captain + INSERT INTO player(id, name, teamId, isCaptain) + VALUES (NEW.id, NEW.name, NEW.teamId, 1); + END; + + -- Update trigger + CREATE TRIGGER captain_update + INSTEAD OF UPDATE ON captain + BEGIN + -- Remove previous captain + UPDATE player SET isCaptain = 0 + WHERE teamId = NEW.teamId AND isCaptain = 1 AND id <> OLD.id; + + -- Update captain + UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1 + WHERE id = OLD.id; + END; + + -- Delete trigger + CREATE TRIGGER captain_delete + INSTEAD OF DELETE ON captain + BEGIN + DELETE FROM player WHERE id = OLD.id; + END; + """) + } + + func test_CRUD() throws { + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try Self.setupDatabase(db) + + let red = Team(id: "red", name: "Red") + try red.insert(db) + + let blue = Team(id: "blue", name: "Blue") + try blue.insert(db) + + // Insert in view + let alice = Captain(id: "alice", name: "Alice", teamId: red.id) + try alice.insert(db) + + var bob = Captain(id: "bob", name: "Bob", teamId: blue.id) + try bob.insert(db) + do { + try XCTAssertEqual( + Player.find(db, id: "bob"), + Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true)) + } + + // Update in view + let modified = try bob.updateChanges(db) { + $0.name = "Bobby" + $0.teamId = red.id + } + XCTAssertTrue(modified) + do { + // Bob is captain of reds. + try XCTAssertEqual( + Player.find(db, id: "bob"), + Player(id: "bob", name: "Bobby", teamId: "red", isCaptain: true)) + + // Alice is no longer captain. + try XCTAssertEqual( + Player.find(db, id: "alice"), + Player(id: "alice", name: "Alice", teamId: "red", isCaptain: false)) + } + + // Insert in view and replace caption + let craig = Captain(id: "craig", name: "Craig", teamId: "red") + try craig.insert(db) + do { + // Craig is captain of reds. + try XCTAssertEqual( + Player.find(db, id: "craig"), + Player(id: "craig", name: "Craig", teamId: "red", isCaptain: true)) + + // Bob is no longer captain. + try XCTAssertEqual( + Player.find(db, id: "bob"), + Player(id: "bob", name: "Bobby", teamId: "red", isCaptain: false)) + } + + // Delete in view + let deleted = try craig.delete(db) + XCTAssertTrue(deleted) + do { + try XCTAssertNil(Player.fetchOne(db, id: "craig")) + } + } + } + + func test_fetch_by_primary_key() throws { + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try Self.setupDatabase(db) + + try Team(id: "red", name: "Red").insert(db) + try Captain(id: "alice", name: "Alice", teamId: "red").insert(db) + + try XCTAssertEqual( + Captain.fetchOne(db, key: "alice"), + Captain(id: "alice", name: "Alice", teamId: "red")) + + try XCTAssertEqual( + Captain.fetchOne(db, key: ["id": "alice"]), + Captain(id: "alice", name: "Alice", teamId: "red")) + + try XCTAssertEqual( + Captain.fetchOne(db, id: "alice"), + Captain(id: "alice", name: "Alice", teamId: "red")) + + try XCTAssertEqual( + Captain.find(db, id: "alice"), + Captain(id: "alice", name: "Alice", teamId: "red")) + } + } + + func test_stable_order() throws { + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try Self.setupDatabase(db) + let request = Captain.all().withStableOrder() + try assertEqualSQL(db, request, "SELECT * FROM \"captain\" ORDER BY \"id\"") + } + } + + func test_team_has_one_captain_request() throws { + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try Self.setupDatabase(db) + + let red = Team(id: "red", name: "Red") + try red.insert(db) + + let blue = Team(id: "blue", name: "Blue") + try blue.insert(db) + + try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db) + + do { + let captain = try red.request(for: Team.captain).fetchOne(db) + // This LIMIT 1 can't be removed until we know that teamId + // is a unique key on the captain view. + // + // We considered using the teamId as the primary key for + // captains, but when a captain does not know its player id: + // + // - Conversion between Player and Captain is uneasy + // - We can't insert a captain because the player id is not + // auto-incremented (no sqlite3_last_insert_rowid + // from triggers) + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "captain" WHERE "teamId" = 'red' LIMIT 1 + """) + XCTAssertEqual(captain, Captain(id: "alice", name: "Alice", teamId: "red")) + } + + do { + struct TeamWithCaptain: Decodable, Equatable, FetchableRecord { + var team: Team + var captain: Captain? + } + + let teamsWithCaptain = try Team + .including(optional: Team.captain) + .asRequest(of: TeamWithCaptain.self) + .orderByPrimaryKey() + .fetchAll(db) + + XCTAssertEqual(lastSQLQuery, """ + SELECT "team".*, "captain".* \ + FROM "team" \ + LEFT JOIN "captain" ON "captain"."teamId" = "team"."id" \ + ORDER BY "team"."id" + """) + + XCTAssertEqual(teamsWithCaptain, [ + TeamWithCaptain( + team: Team(id: "blue", name: "Blue"), + captain: nil), + TeamWithCaptain( + team: Team(id: "red", name: "Red"), + captain: Captain(id: "alice", name: "Alice", teamId: "red")), + ]) + } + } + } + + func test_captain_belongs_to_team_request() throws { + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try Self.setupDatabase(db) + + try Team(id: "red", name: "Red").insert(db) + try Team(id: "blue", name: "Blue").insert(db) + + let alice = Captain(id: "alice", name: "Alice", teamId: "red") + try alice.insert(db) + try Captain(id: "bob", name: "Bob", teamId: "blue").insert(db) + + do { + let team = try alice.request(for: Captain.team).fetchOne(db) + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "team" WHERE "id" = 'red' + """) + XCTAssertEqual(team, Team(id: "red", name: "Red")) + } + + do { + struct CaptainWithTeam: Decodable, Equatable, FetchableRecord { + var captain: Captain + var team: Team + } + + let captainsWithTeam = try Captain + .including(required: Captain.team) + .asRequest(of: CaptainWithTeam.self) + .orderByPrimaryKey() + .fetchAll(db) + + XCTAssertEqual(lastSQLQuery, """ + SELECT "captain".*, "team".* \ + FROM "captain" \ + JOIN "team" ON "team"."id" = "captain"."teamId" \ + ORDER BY "captain"."id" + """) + + XCTAssertEqual(captainsWithTeam, [ + CaptainWithTeam( + captain: Captain(id: "alice", name: "Alice", teamId: "red"), + team: Team(id: "red", name: "Red")), + CaptainWithTeam( + captain: Captain(id: "bob", name: "Bob", teamId: "blue"), + team: Team(id: "blue", name: "Blue")), + ]) + } + } + } +} From 37dde3955797f5f1499a68c4a03d26168abc8fe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Sep 2025 07:17:21 +0200 Subject: [PATCH 33/45] Public Database.schemaSource and withSchemaSource(_:execute:) --- GRDB/Core/Configuration.swift | 8 ++++--- GRDB/Core/Database+Schema.swift | 4 ++-- GRDB/Core/Database.swift | 21 ++++++++++++++++--- Tests/GRDBTests/DatabaseMigratorTests.swift | 23 +++++++++++++++++++++ 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 529f5bc6d..1de641b15 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -430,9 +430,11 @@ public struct Configuration: Sendable { /// by SQLite. For example, a custom schema source can help record types /// that read or write in a database view. /// - /// The schema source has not effect during database migrations - /// performed by ``DatabaseMigrator``. Those access the raw SQLite - /// schema, unaltered. + /// The schema source is automatically disabled during database + /// migrations performed by ``DatabaseMigrator``: those access the raw + /// SQLite schema, unaltered. If a migration needs a schema source, + /// you may call ``Database/withSchemaSource(_:execute:)`` from within + /// the body of a migration. public var schemaSource: (any DatabaseSchemaSource)? // MARK: - Factory Configuration diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index bf02bbf1d..3309bf656 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -35,8 +35,8 @@ extension Database { // MARK: - Database Schema - /// Runs the provided closure with the provided schema source. - func withSchemaSource( + /// Executes the wrapped statements with the provided schema source. + public func withSchemaSource( _ schemaSource: (any DatabaseSchemaSource)?, execute block: () throws -> T ) rethrows -> T { diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 0849f851a..0a4f0e4f9 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -113,6 +113,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``resumeNotification`` /// - ``suspendNotification`` /// +/// ### The Schema Source +/// +/// - ``schemaSource`` +/// - ``withSchemaSource(_:execute:)`` +/// /// ### Other Database Operations /// /// - ``add(tokenizer:)`` @@ -187,6 +192,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The database configuration. public let configuration: Configuration + /// The current schema source. + /// + /// By default, it is the ``Configuration/schemaSource`` + /// of ``configuration``. To modify the schema source, + /// use ``withSchemaSource(_:execute:)``. + /// + /// The schema source is automatically disabled (nil) during database + /// migrations performed by ``DatabaseMigrator``: those access the raw + /// SQLite schema, unaltered. If a migration needs a schema source, + /// you may call ``Database/withSchemaSource(_:execute:)`` from within + /// the body of a migration. + public internal(set) var schemaSource: (any DatabaseSchemaSource)? + /// A description of this database connection. /// /// The returned string is based on the ``Configuration/label`` @@ -276,9 +294,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The cache for the available database schemas (main, temp, attached databases). var schemaCache = SchemaCache() - /// To modify the schemaSource, use `withSchemaSource`. - var schemaSource: (any DatabaseSchemaSource)? - /// The cache for statements managed by GRDB. It is distinct from /// `publicStatementCache` so that we do not mess with statement arguments /// set by the user. diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index b94d90ccb..f17401eb2 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -1125,6 +1125,7 @@ class DatabaseMigratorTests : GRDBTestCase { migrator.registerMigration("A") { db in try db.execute(sql: "CREATE VIEW myView as SELECT 1 AS id") // Cache is empty, and schemaSource is disabled. + XCTAssertNil(db.schemaSource) XCTAssertThrowsError(try db.primaryKey("myView")) } try migrator.migrate(dbQueue) @@ -1132,15 +1133,37 @@ class DatabaseMigratorTests : GRDBTestCase { try dbQueue.inDatabase { db in // Cache was cleared, and schemaSource is active. + XCTAssertNotNil(db.schemaSource) XCTAssertNoThrow(try db.primaryKey("myView")) } do { migrator.registerMigration("B") { db in // Cache was cleared again, and schemaSource is disabled. + XCTAssertNil(db.schemaSource) XCTAssertThrowsError(try db.primaryKey("myView")) } try migrator.migrate(dbQueue) } } + + func test_schemaSource_can_be_restored_during_migrations() throws { + struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } + } + + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + var migrator = DatabaseMigrator() + + migrator.registerMigration("A") { db in + try db.execute(sql: "CREATE VIEW myView as SELECT 1 AS id") + try db.withSchemaSource(SchemaSource()) { + XCTAssertNoThrow(try db.primaryKey("myView")) + } + } + try migrator.migrate(dbQueue) + } } From eb2378a741eb7030d38e4b647127ba20dd2d2869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Sep 2025 07:17:53 +0200 Subject: [PATCH 34/45] DatabaseSchemaSource documentation --- GRDB/Core/DatabaseSchemaSource.swift | 89 +++++++++++++++++++++++----- 1 file changed, 73 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index 7a6d44938..163e83f4f 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -6,13 +6,42 @@ /// /// The use case for a custom schema source is enabling GRDB features that /// would not work with the built-in schema introspection that is provided -/// by SQLite. For example, a custom schema source can help record types -/// that read or write in a database view. +/// by SQLite. /// -/// You do not interact directly with values of such a type. Instead, you -/// configure a database connection with ``Configuration/schemaSource``, and -/// you call methods on a -/// ``Database`` connection. +/// For example, if your database schema contains a view and you wish to use +/// GRDB features that need a primary key, such as the +/// ``FetchableRecord/find(_:id:)`` record method, or the persistence +/// methods of the ``PersistableRecord`` protocol, then use a schema source +/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. +/// +/// ## Enabling a Schema Source +/// +/// To enable a schema source in a database connection, configure its +/// ``Configuration/schemaSource``: +/// +/// ```swift +/// struct MySchemaSource: DatabaseSchemaSource { ... } +/// +/// var config = Configuration() +/// config.schemaSource = MySchemaSource() +/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config) +/// ``` +/// +/// For temporary use, call ``Database/withSchemaSource(_:execute:)``: +/// +/// ```swift +/// try dbQueue.read { db in +/// try db.withSchemaSource(MySchemaSource()) { +/// ... +/// } +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Customizing the Database Schema +/// +/// - ``columnsForPrimaryKey(_:inView:)`` public protocol DatabaseSchemaSource: Sendable { /// Returns the names of the columns for the primary key in the /// provided database view. @@ -30,18 +59,46 @@ public protocol DatabaseSchemaSource: Sendable { /// For example: /// /// ```swift + /// // A schema source that specifies that views have an "id" primary key. /// struct MySchemaSource: DatabaseSchemaSource { - /// func columnsForPrimaryKey( - /// _ db: Database, - /// inView view: DatabaseObjectID - /// ) throws -> [String]? { - /// switch table.name { - /// case "player": - /// // Use the email column as the primary key of this view. - /// return ["email"] + /// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { + /// ["id"] + /// } + /// } /// - /// default: - /// // Do not customize. + /// // A database connection configured with the schema source. + /// var config = Configuration() + /// config.schemaSource = MySchemaSource() + /// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config) + /// + /// // A record type that feeds from a view. + /// struct Player: Decodable, Identifiable, FetchableRecord { + /// static let databaseTableName = "playerView" + /// var id: String + /// var name: String + /// } + /// + /// // Thanks to the schema source, we can fetch players by id: + /// let player = try dbQueue.read { db in + /// try Player.find(db, id: "alice") + /// } + /// ``` + /// + /// When you are developing a library that accesses database files owned + /// by the users of your library, then you you should allow the host + /// application to deal with their own views. To do so, return nil for + /// views that your library does not manage. When necessary, use the + /// `db` argument in order to query the database schema. + /// + /// ```swift + /// struct MyLbrarySchemaSource: DatabaseSchemaSource { + /// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { + /// if view.name == "playerView" { + /// // This is a view managed by my library: + /// return ["id"] + /// } else { + /// // Not a view managed by my library: + /// // don't mess with user's schema /// return nil /// } /// } From 1095d21abde154ea6793a148cec19b78854f018d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Sep 2025 07:58:27 +0200 Subject: [PATCH 35/45] Default implementation for schema source chaining. When GRDB eventually adds methods to the DatabaseSchemaSource protocol, our chained schema source will implement chaining on those new methods. When users write their own custom chaining schema source, the compiler will not tell them that they have to chain the new methods when they upgrade GRDB. The built-in (and correct) implementation of chaining helps avoiding this scenario. --- GRDB/Core/DatabaseSchemaSource.swift | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index 163e83f4f..828de1b05 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -42,6 +42,10 @@ /// ### Customizing the Database Schema /// /// - ``columnsForPrimaryKey(_:inView:)`` +/// +/// ### Chaining Schema Sources +/// +/// - ``then(_:)`` public protocol DatabaseSchemaSource: Sendable { /// Returns the names of the columns for the primary key in the /// provided database view. @@ -118,3 +122,33 @@ extension DatabaseSchemaSource { nil } } + +// MARK: - Combined2SchemaSource + +extension DatabaseSchemaSource { + /// Returns a schema source that queries `other` when this source does + /// not perform customization. + public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource { + Chained2SchemaSource(first: self, second: other) + } +} + +// TODO: move to parameter packs eventually. Parameter packs in generic types +// are only available in macOS 14.0.0 or newer. +// This schema source is designed to tame bad citizens that customize tables +// and views they do not own (such as insufficienly robust schema sources +// exposed by external libraries). We should NEVER MERGE the results of the +// schema sources. +struct Chained2SchemaSource: DatabaseSchemaSource +where Source1: DatabaseSchemaSource, + Source2: DatabaseSchemaSource +{ + var first: Source1 + var second: Source2 + + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + if let result = try first.columnsForPrimaryKey(db, inView: view) { return result } + if let result = try second.columnsForPrimaryKey(db, inView: view) { return result } + return nil + } +} From 1b98a964d70c900434e7b2c9dfc663db8c644a7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Sep 2025 10:31:10 +0200 Subject: [PATCH 36/45] Documentation --- GRDB/Core/DatabaseSchemaSource.swift | 93 +++++++++++++++++++++++----- 1 file changed, 78 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index 828de1b05..14083b779 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -27,16 +27,25 @@ /// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config) /// ``` /// -/// For temporary use, call ``Database/withSchemaSource(_:execute:)``: +/// ## Schema Sources and Migrations +/// +/// By default, schema sources are disabled during . In +/// migrations that need a schema source, you can use +/// ``Database/withSchemaSource(_:execute:)``: /// /// ```swift -/// try dbQueue.read { db in +/// migrator.registerMigration("My migration") { db in +/// // No schema source is enabled at this point. /// try db.withSchemaSource(MySchemaSource()) { -/// ... +/// // Here the provided schema source is in effect. /// } /// } /// ``` /// +/// Take care that **a good migration is a migration that is never +/// modified once it has shipped**: check +/// . +/// /// ## Topics /// /// ### Customizing the Database Schema @@ -54,16 +63,22 @@ public protocol DatabaseSchemaSource: Sendable { /// to specify that the view has no primary key. The default /// implementation returns nil. /// - /// In your implementation, make sure that: + /// In your implementation, make sure that the returned columns define + /// a genuine **primary key**: /// - /// - The returned columns exist in the database schema. - /// - The returned columns identify unique rows. - /// - The returned columns do not contain NULL values. + /// - All columns exist in the provided view. + /// - The set of columns reliably identifies and distinguishes between + /// each individual row in the view. + /// - No column contains NULL values. + /// + /// It is a programmer error with undefined consequences to miss + /// those requirements. /// /// For example: /// /// ```swift - /// // A schema source that specifies that views have an "id" primary key. + /// // A schema source that specifies that all views are identified by + /// // their "id" column: /// struct MySchemaSource: DatabaseSchemaSource { /// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { /// ["id"] @@ -88,18 +103,32 @@ public protocol DatabaseSchemaSource: Sendable { /// } /// ``` /// - /// When you are developing a library that accesses database files owned - /// by the users of your library, then you you should allow the host - /// application to deal with their own views. To do so, return nil for - /// views that your library does not manage. When necessary, use the - /// `db` argument in order to query the database schema. + /// ### Schema Sources in Libraries + /// + /// When you are developing a schema source for a library, some extra + /// care is necessary whenever the database file is owned by the users + /// of your library. Your users may define views for their own purposes, + /// and your library knows nothing about the eventual primary key of + /// those views. + /// + /// In this case, make your schema source `public`, and have this method + /// return `nil` for those unknow views. If needed, use the `db` + /// argument and query the database schema with + /// methods. + /// + /// For example: /// /// ```swift - /// struct MyLbrarySchemaSource: DatabaseSchemaSource { - /// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { + /// // A well-behaved schema source defined by a library is public + /// // and returns nil for unknown views. + /// public struct MyLibrarySchemaSource: DatabaseSchemaSource { + /// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { /// if view.name == "playerView" { /// // This is a view managed by my library: /// return ["id"] + /// } else if try db.tableExists(view.name + "MyLibrary") { + /// // This is a view managed by my library: + /// return ["uuid"] /// } else { /// // Not a view managed by my library: /// // don't mess with user's schema @@ -108,6 +137,28 @@ public protocol DatabaseSchemaSource: Sendable { /// } /// } /// ``` + /// + /// With such a setup, your user will be able to deal with their + /// own views, by chaining your schema source with other ones + /// (see ``DatabaseSchemaSource/then(_:)``): + /// + /// ```swift + /// // Application code + /// import MyLibrary + /// import GRDB + /// + /// let myLibrarySchemaSource = MyLibrarySchemaSource() + /// let customSchemaSource = TheirCustomSchemaSource() + /// let schemaSource = myLibrarySchemaSource.then(customSchemaSource) + /// + /// var config = Configuration() + /// config.schemaSource = schemaSource + /// let dbQueue = try DatabaseQueue(path: "...", configuration: config) + /// ``` + /// + /// - Parameters: + /// - db: A database connection. + /// - view: The identifier of a database view. func columnsForPrimaryKey( _ db: Database, inView view: DatabaseObjectID @@ -128,6 +179,18 @@ extension DatabaseSchemaSource { extension DatabaseSchemaSource { /// Returns a schema source that queries `other` when this source does /// not perform customization. + /// + /// For example: + /// + /// ```swift + /// let schemaSource1 = SomeSchemaSource() + /// let schemaSource2 = AnotherSchemaSource() + /// let schemaSource = schemaSource1.then(schemaSource2) + /// + /// var config = Configuration() + /// config.schemaSource = schemaSource + /// let dbQueue = try DatabaseQueue(path: "...", configuration: config) + /// ``` public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource { Chained2SchemaSource(first: self, second: other) } From f4991273c2b8a307c221a5d0b17462d558f38260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Sep 2025 10:52:57 +0200 Subject: [PATCH 37/45] DatabaseSchemaSource tests --- GRDB.xcodeproj/project.pbxproj | 4 + GRDBCustom.xcodeproj/project.pbxproj | 4 + .../GRDBTests.xcodeproj/project.pbxproj | 18 ++-- .../GRDBTests.xcodeproj/project.pbxproj | 18 ++-- .../GRDBTests/DatabaseSchemaSourceTests.swift | 100 ++++++++++++++++++ 5 files changed, 124 insertions(+), 20 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseSchemaSourceTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 913689475..c0d3f02a7 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -290,6 +290,7 @@ 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; }; 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; }; + 56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; }; 56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; }; 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; }; 56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; }; @@ -796,6 +797,7 @@ 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = ""; }; 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = ""; }; + 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = ""; }; 56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.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 = ""; }; @@ -1491,6 +1493,7 @@ 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, + 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */, 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */, 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */, @@ -2121,6 +2124,7 @@ D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, + 56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 1c9fecb11..5ae342ef8 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -281,6 +281,7 @@ 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */; }; 56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; }; 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; }; + 56BCA2642E6C291200E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */; }; 56BF22882417821F003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF22862417821F003D86EB /* UtilsTests.swift */; }; 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538A22ACEECD0029D27D /* Fetch.swift */; }; 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; }; @@ -805,6 +806,7 @@ 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = ""; }; 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = ""; }; + 56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = ""; }; 56BF22862417821F003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = ""; }; 56C0538A22ACEECD0029D27D /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = ""; }; 56C0538C22ACEECD0029D27D /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; @@ -1496,6 +1498,7 @@ 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, + 56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */, 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */, 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */, @@ -2377,6 +2380,7 @@ 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 56BCA2642E6C291200E4F08D /* DatabaseSchemaSourceTests.swift in Sources */, 56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */, 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 7891f358f..013984344 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -497,11 +497,13 @@ 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; + 56BCA2662E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */; }; + 56BCA2672E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */; }; 56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; }; 56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; }; 56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; 56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; - 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; + 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; }; 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; /* End PBXBuildFile section */ @@ -757,6 +759,7 @@ 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = ""; }; 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; + 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = ""; }; 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; @@ -772,7 +775,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, + 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -938,6 +941,7 @@ 56419CF724A5405A004967E1 /* DatabaseRegionObservationTests.swift */, 56419D2624A5405D004967E1 /* DatabaseRegionTests.swift */, 56419CB324A54055004967E1 /* DatabaseSavepointTests.swift */, + 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */, 567B5C222AD32A2D00629622 /* DatabaseSnapshotPoolTests.swift */, 56419CE624A54058004967E1 /* DatabaseSnapshotTests.swift */, 56419CD624A54057004967E1 /* DatabaseSuspensionTests.swift */, @@ -1221,14 +1225,10 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); - inputPaths = ( - ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); - outputPaths = ( - ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks.sh\"\n"; @@ -1264,14 +1264,10 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); - inputPaths = ( - ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); - outputPaths = ( - ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks.sh\"\n"; @@ -1497,6 +1493,7 @@ 56419DD124A54062004967E1 /* ValueObservationRecordTests.swift in Sources */, 56419E1124A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */, 56419DC724A54062004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, + 56BCA2672E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */, 56419EF524A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56419D6F24A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */, 56419E7324A54062004967E1 /* TruncateOptimizationTests.swift in Sources */, @@ -1748,6 +1745,7 @@ 56419DD224A54062004967E1 /* ValueObservationRecordTests.swift in Sources */, 56419E1224A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */, 56419DC824A54062004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, + 56BCA2662E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */, 56419EF624A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56419D7024A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */, 56419E7424A54062004967E1 /* TruncateOptimizationTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 19c1bb9ad..370f75c10 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -499,11 +499,13 @@ 568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; + 56BCA2692E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */; }; + 56BCA26A2E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */; }; 56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; }; 56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; }; 56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; 56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; - 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; + 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; }; E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; /* End PBXBuildFile section */ @@ -760,6 +762,7 @@ 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; + 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = ""; }; 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; @@ -775,7 +778,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, + 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -942,6 +945,7 @@ 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */, 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */, 56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */, + 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */, 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */, 56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */, 56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */, @@ -1227,14 +1231,10 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); - inputPaths = ( - ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); - outputPaths = ( - ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTests/Pods-GRDBTests-frameworks.sh\"\n"; @@ -1270,14 +1270,10 @@ inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); - inputPaths = ( - ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); - outputPaths = ( - ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted-frameworks.sh\"\n"; @@ -1503,6 +1499,7 @@ 5641A00024A540A1004967E1 /* StatementArguments+FoundationTests.swift in Sources */, 5641A0BE24A540A1004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */, 5641A07224A540A1004967E1 /* FoundationNSNullTests.swift in Sources */, + 56BCA26A2E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */, 5641A14E24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */, 5641A0C024A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */, 5641A08024A540A1004967E1 /* ResultCodeTests.swift in Sources */, @@ -1754,6 +1751,7 @@ 5641A00124A540A1004967E1 /* StatementArguments+FoundationTests.swift in Sources */, 5641A0BF24A540A1004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */, 5641A07324A540A1004967E1 /* FoundationNSNullTests.swift in Sources */, + 56BCA2692E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */, 5641A14F24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */, 5641A0C124A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */, 5641A08124A540A1004967E1 /* ResultCodeTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseSchemaSourceTests.swift b/Tests/GRDBTests/DatabaseSchemaSourceTests.swift new file mode 100644 index 000000000..16dd0d781 --- /dev/null +++ b/Tests/GRDBTests/DatabaseSchemaSourceTests.swift @@ -0,0 +1,100 @@ +import XCTest +import GRDB + +class DatabaseSchemaSourceTests: GRDBTestCase { + func test_schemaSource_can_query_schema() throws { + struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + let tableName = view.name + "_table" + if try db.tableExists(view.name + "_table"), + try db.primaryKey(tableName).columns == ["id"], + try db.columns(in: view.name, in: view.schemaID.name).contains(where: { $0.name == "name" }) + { + return ["id"] + } else { + return nil + } + } + } + + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + -- Matches SchemaSource + CREATE TABLE view1_table(id INTEGER PRIMARY KEY, name TEXT); + CREATE VIEW view1 AS SELECT * FROM view1_table; + + -- Does not match SchemaSource + CREATE VIEW view2 AS SELECT 1; + + -- Does not match SchemaSource + CREATE TABLE view3_table(uuid TEXT PRIMARY KEY); + CREATE VIEW view3 AS SELECT * FROM view3_table; + + -- Does not match SchemaSource + CREATE TABLE view4_table(id INTEGER PRIMARY KEY, name TEXT); + CREATE VIEW view4 AS SELECT id FROM view4_table; + """) + + try XCTAssertEqual(db.primaryKey("view1").columns, ["id"]) + XCTAssertThrowsError(try db.primaryKey("view2")) + XCTAssertThrowsError(try db.primaryKey("view3")) + XCTAssertThrowsError(try db.primaryKey("view4")) + } + } + + func test_then_with_columnsForPrimaryKey_inView() throws { + struct SchemaSource1: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + switch view.name { + case "view1": ["code"] + case "view2": ["id"] + default: nil + } + } + } + + struct SchemaSource2: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + switch view.name { + case "view1": ["identifier"] + case "view3": ["uuid"] + default: nil + } + } + } + + func setupSchema(_ db: Database) throws { + try db.execute(sql: """ + CREATE VIEW view1 AS SELECT 'foo' AS code, 'whatever' AS identifier; + CREATE VIEW view2 AS SELECT 1 AS id; + CREATE VIEW view3 AS SELECT 'foo' AS uuid; + """) + } + + do { + let schemaSource = SchemaSource1().then(SchemaSource2()) + dbConfiguration.schemaSource = schemaSource + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try setupSchema(db) + try XCTAssertEqual(db.primaryKey("view1").columns, ["code"]) + try XCTAssertEqual(db.primaryKey("view2").columns, ["id"]) + try XCTAssertEqual(db.primaryKey("view3").columns, ["uuid"]) + } + } + + do { + let schemaSource = SchemaSource2().then(SchemaSource1()) + dbConfiguration.schemaSource = schemaSource + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try setupSchema(db) + try XCTAssertEqual(db.primaryKey("view1").columns, ["identifier"]) + try XCTAssertEqual(db.primaryKey("view2").columns, ["id"]) + try XCTAssertEqual(db.primaryKey("view3").columns, ["uuid"]) + } + } + } +} From 99ecf76a77aa91e28719ccfa3a23dfeb1fd4b18e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Sep 2025 11:16:05 +0200 Subject: [PATCH 38/45] Support primary key when testing the existence of an association to a view --- GRDB/Core/Database+Schema.swift | 18 ++++++---- .../AssociationBelongsToSQLTests.swift | 36 +++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3309bf656..2fcce080c 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -580,7 +580,6 @@ extension Database { /// Returns whether the column identifies the rowid column func columnIsRowID(_ column: String, of tableName: String) throws -> Bool { - #warning("TODO: test with database views") let pk = try primaryKey(tableName) return pk.rowIDColumn == column || (pk.tableHasRowID && column.uppercased() == "ROWID") } @@ -1153,8 +1152,8 @@ extension Database { /// /// The returned array is never empty. func existenceCheckColumns(in tableName: String) throws -> [String] { - if try tableExists(tableName) { - // Table: only check the primary key columns for existence + do { + // Check the primary key columns for existence let primaryKey = try self.primaryKey(tableName) if let rowIDColumn = primaryKey.rowIDColumn { // Prefer the user-provided name of the rowid @@ -1175,10 +1174,15 @@ extension Database { // try db.existenceCheckColumns(in: "player") // ["uuid"] return primaryKey.columns } - } else { - #warning("TODO: use the primary key if available") - // View: check all columns for existence - return try columns(in: tableName).map(\.name) + } catch let error as DatabaseError { + if case .SQLITE_ERROR = error.resultCode, + (try? viewExists(tableName)) == true + { + // View without primary key: check all columns for existence + return try columns(in: tableName).map(\.name) + } else { + throw error + } } } } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 3e4c2fd43..b7d737d18 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -2359,5 +2359,41 @@ class AssociationBelongsToSQLTests: GRDBTestCase { """) } } + + do { + // View with custom primary key. + // Existence check is performed on the primary key. + struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } + } + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorID", .integer) + } + try db.execute(sql: """ + CREATE VIEW authorView AS SELECT * FROM author + """) + + let association = Book.belongsTo(Table("authorView"), using: ForeignKey(["authorId"], to: ["id"])) + let authorAlias = TableAlias() + let request = Book + .joining(optional: association.aliased(authorAlias)) + .filter(!authorAlias.exists) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + LEFT JOIN "authorView" ON "authorView"."id" = "book"."authorId" \ + WHERE "authorView"."id" IS NULL + """) + } + } } } From ca27f75760f3ac66e99d9081df2b0b93e06cb3bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Sep 2025 11:31:43 +0200 Subject: [PATCH 39/45] Test the stable order of views with a primary key --- GRDB/QueryInterface/SQL/SQLRelation.swift | 1 - Tests/GRDBTests/DatabaseDumpTests.swift | 69 +++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 764d236a0..6fdf125db 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -286,7 +286,6 @@ extension SQLRelation: Refinable { with { relation in relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in do { - #warning("TODO: test with views") // Order by primary key. Don't order by rowid because those are // not stable: rowids can change after a vacuum. return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering } diff --git a/Tests/GRDBTests/DatabaseDumpTests.swift b/Tests/GRDBTests/DatabaseDumpTests.swift index 1013d713c..8a654f85a 100644 --- a/Tests/GRDBTests/DatabaseDumpTests.swift +++ b/Tests/GRDBTests/DatabaseDumpTests.swift @@ -22,6 +22,11 @@ private struct Player: Codable, MutablePersistableRecord { mutating func didInsert(_ inserted: InsertionSuccess) { id = inserted.rowID } + + enum Columns { + static let name = Column(CodingKeys.name) + static let teamId = Column(CodingKeys.teamId) + } } private struct Team: Codable, PersistableRecord { @@ -1141,6 +1146,70 @@ final class DatabaseDumpTests: GRDBTestCase { } } + func test_dumpTables_single_view_with_schema_source() throws { + struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["teamId", "name"] + } + } + dbConfiguration.schemaSource = SchemaSource() + + try makeRugbyDatabase().write { db in + try db.create(view: "playerName", as: Player + .orderByPrimaryKey() + .filter { $0.teamId != nil } + .select { [$0.teamId, $0.name] }) + + do { + // Default order: use the view ordering + do { + // Default format + let stream = TestStream() + try db.dumpTables(["playerName"], to: stream) + XCTAssertEqual(stream.output, """ + FRA|Antoine Dupond + ENG|Owen Farrell + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpTables(["playerName"], format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"teamId":"FRA","name":"Antoine Dupond"}, + {"teamId":"ENG","name":"Owen Farrell"}] + + """) + } + } + + do { + // Stable order (primary key) + do { + // Default format + let stream = TestStream() + try db.dumpTables(["playerName"], stableOrder: true, to: stream) + XCTAssertEqual(stream.output, """ + ENG|Owen Farrell + FRA|Antoine Dupond + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpTables(["playerName"], format: .json(), stableOrder: true, to: stream) + XCTAssertEqual(stream.output, """ + [{"teamId":"ENG","name":"Owen Farrell"}, + {"teamId":"FRA","name":"Antoine Dupond"}] + + """) + } + } + } + } + func test_dumpTables_multiple() throws { try makeRugbyDatabase().read { db in do { From a7e3acf4094016e428542464891a8896d885491a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Sep 2025 11:42:25 +0200 Subject: [PATCH 40/45] Remove TODO warnings --- Tests/GRDBTests/TableRecordDeleteTests.swift | 4 ++-- Tests/GRDBTests/TableRecordUpdateTests.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 87575b267..386cc3cdf 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -776,7 +776,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } - #warning("TODO: duplicate test with views") + // TODO: duplicate test with views? func testJoinedRequestDeleteAll() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -837,7 +837,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } - #warning("TODO: duplicate test with views") + // TODO: duplicate test with views? func testJoinedRequestDeleteAndFetch() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER guard Database.sqliteLibVersionNumber >= 3035000 else { diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index 410f10bf8..3ee015537 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -1680,7 +1680,7 @@ class TableRecordUpdateTests: GRDBTestCase { } } - #warning("TODO: duplicate test with views") + // TODO: duplicate test with views? func testJoinedRequestUpdate() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -1753,7 +1753,7 @@ class TableRecordUpdateTests: GRDBTestCase { } } - #warning("TODO: duplicate test with views") + // TODO: duplicate test with views? func testJoinedRequestUpdate_DatabaseComponents() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { From b210ec742864213d960d063526aed89d802e3674 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Sep 2025 14:09:12 +0200 Subject: [PATCH 41/45] View Records guide --- GRDB/Core/DatabaseSchemaSource.swift | 3 +- GRDB/Documentation.docc/GRDB.md | 1 + GRDB/Documentation.docc/ViewRecords.md | 383 ++++++++++++++++++ GRDB/Record/MutablePersistableRecord.swift | 5 + GRDB/Record/PersistableRecord.swift | 5 + GRDB/Record/TableRecord.swift | 4 + .../RecordMappedOnMutableViewTests.swift | 177 +++++--- 7 files changed, 518 insertions(+), 60 deletions(-) create mode 100644 GRDB/Documentation.docc/ViewRecords.md diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index 14083b779..9b25006e5 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -12,7 +12,8 @@ /// GRDB features that need a primary key, such as the /// ``FetchableRecord/find(_:id:)`` record method, or the persistence /// methods of the ``PersistableRecord`` protocol, then use a schema source -/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. +/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See +/// for a detailed guide about such views. /// /// ## Enabling a Schema Source /// diff --git a/GRDB/Documentation.docc/GRDB.md b/GRDB/Documentation.docc/GRDB.md index d824121e9..e76f56dc1 100644 --- a/GRDB/Documentation.docc/GRDB.md +++ b/GRDB/Documentation.docc/GRDB.md @@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in - - - +- ### Application Tools diff --git a/GRDB/Documentation.docc/ViewRecords.md b/GRDB/Documentation.docc/ViewRecords.md new file mode 100644 index 000000000..80cc0400f --- /dev/null +++ b/GRDB/Documentation.docc/ViewRecords.md @@ -0,0 +1,383 @@ +# View Records + +Define record types that target database views. + +## Overview + +A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view. + +With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration: + +```swift +// OK: Works out of the box +let captains = try Captain.fetchAll(db) +let captainCount = try Captain.fetchCount(db) + +// KO: Requires extra configuration +// SQLite error 1: The database view 'captain' has no primary key. +var bob = try Captain.find(db, id: "bob") +bob.name = "Bobby" +// SQLite error 1: cannot modify captain because it is a view +try bob.update(db) +``` + +This article explains how to solve those errors: + +- How to provide a primary key to a view. +- How to define INSTEAD OF triggers that insert, update, and delete through a database view. + +> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers: +> +> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932). +> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems. + +## Preliminary Setup + +To support this documentation, we need a database that contains a view. The sample code below uses and methods. + +The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains: + +```swift +var migrator = DatabaseMigrator() +migrator.registerMigration("Teams and players") { db in + try db.create(table: "team") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + } + + try db.create(table: "player") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.belongsTo("team", onDelete: .setNull) + t.column("isCaptain", .boolean).notNull() + } + + // One unique captain per team + try db.create( + indexOn: "player", columns: ["teamId"], + options: .unique, + condition: Column("isCaptain")) +} +``` + +We define record types for the `team` and `player` tables, as described in : + +```swift +struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord { + var id: String + var name: String +} + +struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord { + var id: String + var name: String + var teamId: String? + var isCaptain: Bool +} +``` + +Let's define a view and a record type for captains. At this point, both the view and the record are read-only: + +```swift +migrator.registerMigration("Read-only captains") { db in + try db.execute(sql: """ + CREATE VIEW captain AS + SELECT id, name, teamId + FROM player + WHERE isCaptain AND teamId IS NOT NULL; + """) +} + +struct Captain: Decodable, Identifiable, FetchableRecord { + var id: String + var name: String + var teamId: String +} +``` + +✅ From now on, we can use the `Captain` record: + +```swift +let dbQueue = try DatabaseQueue() +try migrator.migrate(dbQueue) +try dbQueue.write { db in + try Team(id: "red", name: "Red").insert(db) + try Team(id: "blue", name: "Blue").insert(db) + try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db) + try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db) + try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db) + + let captains = try Captain.fetchAll(db) + // Prints: + // Captain(id: "alice", name: "Alice", teamId: "red") + // Captain(id: "bob", name: "Bob", teamId: "blue") + print(captains) +} +``` + +## Specifying the primary key of a view + +SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key. + +To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions: + +```swift +struct GameSchemaSource: DatabaseSchemaSource { + /// Returns the names of the columns for the primary key in the + /// provided database view. + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } +} +``` + +We configure the database connection with this schema source: + +```swift +var config = Configuration() +config.schemaSource = GameSchemaSource() +let dbQueue = try DatabaseQueue(configuration: config) +try migrator.migrate(dbQueue) +``` + +✅ We can now use the primary key of captains: + +```swift +try dbQueue.read { db in + // [Insert some teams and players...] + let captains = try Captain.orderByPrimaryKey().fetchAll(db) + let alice = try Captain.find(db, id: "alice") +} +``` + +## Associations between views + +To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in : + +```swift +extension Captain { + // Time to define some columns + enum Columns { + static let teamId = Column(CodingKeys.teamId) + } + + // The captain view has a foreign key to teams, + // from the teamId column to the team primary key. + // SQLite does not know about it, so we declare it explicitly: + static let teamForeignKey = ForeignKey([Columns.teamId]) + + // A captain belongs to a team. + static let team = belongsTo(Team.self, using: teamForeignKey) +} + +extension Team { + // A team has a captain. + static let captain = hasOne(Captain.self, using: Captain.teamForeignKey) +} +``` + +✅ We can now use those associations: + +```swift +try dbQueue.read { db in + // All teams with a captain + let teamsWithCaptain: [Team] = try Team + .joining(required: Team.captain) + .fetchAll(db) + + // All (captain, team) pairs + struct CaptainWithTeam: Decodable, FetchableRecord { + var captain: Captain + var team: Team + } + let captainsWithTeam: [CaptainWithTeam] = try Captain + .including(required: Captain.team) + .asRequest(of: CaptainWithTeam.self) + .fetchAll(db) +} +``` + +## Inserting rows into a view + +SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view. + +INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any: + +```swift +migrator.registerMigration("Captain insert") { db in + try db.execute(sql: """ + -- Insert trigger + CREATE TRIGGER captain_insert + INSTEAD OF INSERT ON captain + BEGIN + -- Remove previous captain + UPDATE player SET isCaptain = 0 + WHERE teamId = NEW.teamId AND isCaptain; + + -- Insert new captain + INSERT INTO player(id, name, teamId, isCaptain) + VALUES (NEW.id, NEW.name, NEW.teamId, 1); + END; + """) +} + +// Apply the new migration +try migrator.migrate(dbQueue) +``` + +Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol: + +```swift +extension Captain: Encodable, PersistableRecord { } +``` + +- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine. + +✅ We can directly insert captains: + +```swift +try dbQueue.write { + try Team(id: "green", name: "Green").insert(db) + // Diane is the captain + try Captain(id: "diane", name: "Diane", teamId: "green").insert(db) + // Well, no: Eugene is the captain + try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db) + + // Prints: + // team player captain + // green|Green diane|Diane|green|0 eugene|Eugene|green + // eugene|Eugene|green|1 + try db.dumpTables(["team", "player", "captain"]) +} +``` + +## Updating rows in a view + +Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view. + +In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any: + +```swift +migrator.registerMigration("Captain update") { db in + try db.execute(sql: """ + -- Update trigger + CREATE TRIGGER captain_update + INSTEAD OF UPDATE ON captain + BEGIN + -- Remove previous captain + UPDATE player SET isCaptain = 0 + WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id; + + -- Update captain + UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1 + WHERE id = NEW.id; + END; + """) +} + +// Apply the new migration +try migrator.migrate(dbQueue) +``` + +✅ Let's update captains: + +```swift +try dbQueue.write { + try Team(id: "red", name: "Red").insert(db) + try Team(id: "blue", name: "Blue").insert(db) + try Captain(id: "alice", name: "Alice", teamId: "red").insert(db) + + // Bob is the Blue captain. + var bob = Captain(id: "bob", name: "Bob", teamId: "blue") + try bob.insert(db) + + // Bob is now Bobby, the Red captain. + // Alice is no longer the Red captain. + try bob.updateChanges(db) { + $0.name = "Bobby" + $0.teamId = "red" + } + + // Prints: + // team player captain + // blue|Blue alice|Alice|red|0 bob|Bobby|red + // red|Red bob|Bobby|red|1 + try db.dumpTables(["team", "player", "captain"]) +} +``` + +## Deleting rows from a view + +The last missing INSTEAD OF trigger deals with deletes: + +```swift +migrator.registerMigration("Captain delete") { db in + try db.execute(sql: """ + -- Delete trigger + CREATE TRIGGER captain_delete + INSTEAD OF DELETE ON captain + BEGIN + DELETE FROM player WHERE id = OLD.id; + END; + """) +} + +// Apply the new migration +try migrator.migrate(dbQueue) +``` + +✅ Let's delete some captains: + +```swift +try dbQueue.write { + // Delete Alice + try Captain.deleteOne(db, id: "alice") + + // Delete Bob + let bob = try Captain.find(db, id: "bob") + try bob.delete(db) + + // Delete all captains + try Captain.deleteAll() +} +``` + +## Going further + +To exercise the techniques described here, try to define record types for these other views: + +- The `enrolledPlayer` view that only contains players that belong to a team: + + ```swift + try db.execute(sql: """ + CREATE VIEW enrolledPlayer AS + SELECT id, name, teamId, isCaptain + FROM player + WHERE teamId IS NOT NULL; + """) + ``` + +- The `teamWithCaptainId` view that contains a `captainId` column: + + ```swift + try db.execute(sql: """ + CREATE VIEW teamWithCaptainId AS + SELECT team.id, team.name, player.id AS captainId + FROM team + JOIN player ON player.teamId = team.id AND player.isCaptain; + """) + ``` + +- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team: + + ```swift + try db.execute(sql: """ + CREATE VIEW captain AS + SELECT teamId, name + FROM player + WHERE isCaptain AND teamId IS NOT NULL; + """) + ``` + +[database view]: https://www.sqlite.org/lang_createview.html +[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift index 2b7db54d1..d8e5b7811 100644 --- a/GRDB/Record/MutablePersistableRecord.swift +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -184,6 +184,11 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// } /// ``` /// + /// - important: Due to an SQLite limitation, this callback is + /// unreliable when the record type writes into a database view + /// through an INSTEAD OF trigger. The `inserted.rowID` value is + /// not the rowid of the inserted row. + /// /// - parameter inserted: Information about the inserted row. mutating func didInsert(_ inserted: InsertionSuccess) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index e769284ed..05e283ba3 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -73,6 +73,11 @@ public protocol PersistableRecord: MutablePersistableRecord { /// - note: If you need a mutating variant of this method, adopt the /// ``MutablePersistableRecord`` protocol instead. /// + /// - important: Due to an SQLite limitation, this callback is + /// unreliable when the record type writes into a database view + /// through an INSTEAD OF trigger. The `inserted.rowID` value is + /// not the rowid of the inserted row. + /// /// - parameter inserted: Information about the inserted row. func didInsert(_ inserted: InsertionSuccess) } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 716b4fc0b..019b9e6fb 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -209,6 +209,10 @@ public protocol TableRecord: GRDBSendableMetatype { /// // SELECT * FROM player /// try Player.fetchAll(db) /// ``` + /// + /// You can specify the name of a database table, or the name of a + /// database view. When you target a database view, some extra + /// configuration might be needed. Please check . static var databaseTableName: String { get } /// The columns selected by the record. diff --git a/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift index 88d1027a6..429f8f1d9 100644 --- a/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift +++ b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift @@ -23,7 +23,7 @@ private struct Team: Codable, var id: String var name: String - static let captain = hasOne(Captain.self, using: ForeignKey(["teamId"])) + static let captain = hasOne(Captain.self, using: Captain.teamForeignKey) } private struct Captain: Codable, @@ -36,7 +36,12 @@ private struct Captain: Codable, var name: String var teamId: String - static let team = belongsTo(Team.self, using: ForeignKey(["teamId"])) + enum Columns { + static let teamId = Column(CodingKeys.teamId) + } + + static let teamForeignKey = ForeignKey([Columns.teamId]) + static let team = belongsTo(Team.self, using: teamForeignKey) } private struct SchemaSource: DatabaseSchemaSource { @@ -51,68 +56,125 @@ private struct SchemaSource: DatabaseSchemaSource { } class RecordMappedOnMutableViewTests : GRDBTestCase { - static func setupDatabase(_ db: Database) throws { - try db.create(table: "team") { t in - t.primaryKey("id", .text) - t.column("name", .text).notNull() + private lazy var migrator: DatabaseMigrator = { + var migrator = DatabaseMigrator() + migrator.registerMigration("Teams and players") { db in + try db.create(table: "team") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + } + + try db.create(table: "player") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.belongsTo("team", onDelete: .setNull) + t.column("isCaptain", .boolean).notNull() + } + + // One unique captain per team + try db.create( + indexOn: "player", columns: ["teamId"], + options: .unique, + condition: Column("isCaptain")) } - try db.create(table: "player") { t in - t.primaryKey("id", .text) - t.column("name", .text).notNull() - t.belongsTo("team", onDelete: .setNull) - t.column("isCaptain", .boolean).notNull() - } - - try db.create(indexOn: "player", columns: ["teamId"], options: .unique, condition: Column("isCaptain")) - - try db.execute(sql: """ - CREATE VIEW captain AS - SELECT player.id, player.name, player.teamId + migrator.registerMigration("Read-only captains") { db in + try db.execute(sql: """ + CREATE VIEW captain AS + SELECT id, name, teamId FROM player - WHERE isCaptain; - - -- Insert trigger - CREATE TRIGGER captain_insert - INSTEAD OF INSERT ON captain - BEGIN - -- Remove previous captain - UPDATE player SET isCaptain = 0 - WHERE teamId = NEW.teamId AND isCaptain = 1; + WHERE isCaptain AND teamId IS NOT NULL; + """) + } + + migrator.registerMigration("Captain CRUD") { db in + try db.execute(sql: """ + -- Insert trigger + CREATE TRIGGER captain_insert + INSTEAD OF INSERT ON captain + BEGIN + -- Remove previous captain + UPDATE player SET isCaptain = 0 + WHERE teamId = NEW.teamId AND isCaptain; + + -- Insert new captain + INSERT INTO player(id, name, teamId, isCaptain) + VALUES (NEW.id, NEW.name, NEW.teamId, 1); + END; - -- Insert new captain - INSERT INTO player(id, name, teamId, isCaptain) - VALUES (NEW.id, NEW.name, NEW.teamId, 1); - END; - - -- Update trigger - CREATE TRIGGER captain_update - INSTEAD OF UPDATE ON captain - BEGIN - -- Remove previous captain - UPDATE player SET isCaptain = 0 - WHERE teamId = NEW.teamId AND isCaptain = 1 AND id <> OLD.id; + -- Update trigger + CREATE TRIGGER captain_update + INSTEAD OF UPDATE ON captain + BEGIN + -- Remove previous captain + UPDATE player SET isCaptain = 0 + WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id; + + -- Update captain + UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1 + WHERE id = NEW.id; + END; - -- Update captain - UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1 - WHERE id = OLD.id; - END; + -- Delete trigger + CREATE TRIGGER captain_delete + INSTEAD OF DELETE ON captain + BEGIN + DELETE FROM player WHERE id = OLD.id; + END; + """) + } + + return migrator + }() + + func test_read_only() throws { + // No schema source, no CRUD + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue, upTo: "Read-only captains") + try dbQueue.write { db in + try Team(id: "red", name: "Red").insert(db) + try Team(id: "blue", name: "Blue").insert(db) + try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db) + try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db) + try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db) + + let captains = try Captain.fetchAll(db) + XCTAssertEqual(captains.count, 2) + XCTAssert(captains.contains(Captain(id: "alice", name: "Alice", teamId: "red"))) + XCTAssert(captains.contains(Captain(id: "bob", name: "Bob", teamId: "blue"))) + } + } + + func test_read_only_primary_key() throws { + // No CRUD + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue, upTo: "Read-only captains") + try dbQueue.write { db in + try Team(id: "red", name: "Red").insert(db) + try Team(id: "blue", name: "Blue").insert(db) + try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db) + try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db) + try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db) - -- Delete trigger - CREATE TRIGGER captain_delete - INSTEAD OF DELETE ON captain - BEGIN - DELETE FROM player WHERE id = OLD.id; - END; - """) + let captains = try Captain.orderByPrimaryKey().fetchAll(db) + XCTAssertEqual(captains, [ + Captain(id: "alice", name: "Alice", teamId: "red"), + Captain(id: "bob", name: "Bob", teamId: "blue"), + ]) + + let alice = try Captain.find(db, id: "alice") + XCTAssertEqual(alice, Captain(id: "alice", name: "Alice", teamId: "red")) + + try db.dumpTables(["team", "player", "captain"]) + } } func test_CRUD() throws { dbConfiguration.schemaSource = SchemaSource() let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) try dbQueue.write { db in - try Self.setupDatabase(db) - let red = Team(id: "red", name: "Red") try red.insert(db) @@ -176,9 +238,8 @@ class RecordMappedOnMutableViewTests : GRDBTestCase { func test_fetch_by_primary_key() throws { dbConfiguration.schemaSource = SchemaSource() let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) try dbQueue.write { db in - try Self.setupDatabase(db) - try Team(id: "red", name: "Red").insert(db) try Captain(id: "alice", name: "Alice", teamId: "red").insert(db) @@ -203,8 +264,8 @@ class RecordMappedOnMutableViewTests : GRDBTestCase { func test_stable_order() throws { dbConfiguration.schemaSource = SchemaSource() let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) try dbQueue.write { db in - try Self.setupDatabase(db) let request = Captain.all().withStableOrder() try assertEqualSQL(db, request, "SELECT * FROM \"captain\" ORDER BY \"id\"") } @@ -213,9 +274,8 @@ class RecordMappedOnMutableViewTests : GRDBTestCase { func test_team_has_one_captain_request() throws { dbConfiguration.schemaSource = SchemaSource() let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) try dbQueue.write { db in - try Self.setupDatabase(db) - let red = Team(id: "red", name: "Red") try red.insert(db) @@ -276,9 +336,8 @@ class RecordMappedOnMutableViewTests : GRDBTestCase { func test_captain_belongs_to_team_request() throws { dbConfiguration.schemaSource = SchemaSource() let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) try dbQueue.write { db in - try Self.setupDatabase(db) - try Team(id: "red", name: "Red").insert(db) try Team(id: "blue", name: "Blue").insert(db) From f5dc68fc6f0803469d12c0b613fc06a344270876 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Sep 2025 10:45:06 +0200 Subject: [PATCH 42/45] Fix typos --- GRDB/Core/DatabaseSchemaSource.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index 9b25006e5..fa1e6b105 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -4,8 +4,8 @@ /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// -/// The use case for a custom schema source is enabling GRDB features that -/// would not work with the built-in schema introspection that is provided +/// The use case for a custom schema source is to enable GRDB features that +/// would not work with the built-in schema introspection provided /// by SQLite. /// /// For example, if your database schema contains a view and you wish to use @@ -60,9 +60,9 @@ public protocol DatabaseSchemaSource: Sendable { /// Returns the names of the columns for the primary key in the /// provided database view. /// - /// Return nil if no customization should happen. Return an empty array - /// to specify that the view has no primary key. The default - /// implementation returns nil. + /// Return `nil` if no customization should happen. Return an empty + /// array to specify that the view has no primary key. The default + /// implementation returns `nil`. /// /// In your implementation, make sure that the returned columns define /// a genuine **primary key**: @@ -113,7 +113,7 @@ public protocol DatabaseSchemaSource: Sendable { /// those views. /// /// In this case, make your schema source `public`, and have this method - /// return `nil` for those unknow views. If needed, use the `db` + /// return `nil` for those unknown views. If needed, use the `db` /// argument and query the database schema with /// methods. /// @@ -179,7 +179,7 @@ extension DatabaseSchemaSource { extension DatabaseSchemaSource { /// Returns a schema source that queries `other` when this source does - /// not perform customization. + /// not perform a customization. /// /// For example: /// From 9ef5e2c8eb4e52b9e33430db34af80f5688c959d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Sep 2025 08:25:52 +0200 Subject: [PATCH 43/45] Simplify error messages --- GRDB/Core/Database+Schema.swift | 29 ++++--------------- GRDB/Documentation.docc/ViewRecords.md | 2 +- .../Request/RequestProtocols.swift | 18 +++--------- Tests/GRDBTests/PrimaryKeyInfoTests.swift | 20 ++++--------- 4 files changed, 17 insertions(+), 52 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 2fcce080c..eb409a6b5 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -367,17 +367,9 @@ extension Database { } if (try? viewExists(tableName, in: schemaName)) == true { - if schemaSource == nil { - throw DatabaseError(message: """ - The database view '\(tableName)' has no primary key. \ - To support views, provide a custom schema source in Configuration.schemaSource. - """) - } else { - throw DatabaseError(message: """ - The database view '\(tableName)' has no primary key, \ - according to Configuration.schemaSource. - """) - } + throw DatabaseError(message: """ + database view \(tableName) has no primary key + """) } else { throw DatabaseError.noSuchTable(tableName) } @@ -404,18 +396,9 @@ extension Database { if case .SQLITE_ERROR = error.resultCode, (try? viewExists(tableName)) == true { - if schemaSource == nil { - fatalError(""" - Filtering by primary key is not available on the database view '\(tableName)'. \ - Instead, use `filter(Column("...") == value)`, or provide \ - a custom schema source in Configuration.schemaSource. - """) - } else { - fatalError(""" - Filtering by primary key requires a single-column primary key in the view '\(tableName)'. \ - No such primary key is configured by Configuration.schemaSource. - """) - } + throw DatabaseError(message: """ + database view \(tableName) has no primary key + """) } else { throw error } diff --git a/GRDB/Documentation.docc/ViewRecords.md b/GRDB/Documentation.docc/ViewRecords.md index 80cc0400f..5b256e264 100644 --- a/GRDB/Documentation.docc/ViewRecords.md +++ b/GRDB/Documentation.docc/ViewRecords.md @@ -14,7 +14,7 @@ let captains = try Captain.fetchAll(db) let captainCount = try Captain.fetchCount(db) // KO: Requires extra configuration -// SQLite error 1: The database view 'captain' has no primary key. +// SQLite error 1: database view captain has no primary key var bob = try Captain.find(db, id: "bob") bob.name = "Bobby" // SQLite error 1: cannot modify captain because it is a view diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 924528135..e2b366d57 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -827,20 +827,10 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // or unique index). guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { if (try? db.viewExists(databaseTableName)) == true { - if db.schemaSource == nil { - fatalError(""" - view \(databaseTableName) has no unique key on column(s) \ - \(key.keys.sorted().joined(separator: ", ")). To support \ - keys in views, provide a custom schema source in \ - Configuration.schemaSource. - """) - } else { - fatalError(""" - view \(databaseTableName) has no unique key on column(s) \ - \(key.keys.sorted().joined(separator: ", ")), \ - according to Configuration.schemaSource. - """) - } + fatalError(""" + database view \(databaseTableName) has no unique key on column(s) \ + \(key.keys.sorted().joined(separator: ", ")) + """) } else { fatalError(""" table \(databaseTableName) has no unique key on column(s) \ diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index 25c9485ce..7cae11b84 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -27,14 +27,10 @@ class PrimaryKeyInfoTests: GRDBTestCase { } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, """ - The database view 'items' has no primary key. \ - To support views, provide a custom schema source \ - in Configuration.schemaSource. + database view items has no primary key """) XCTAssertEqual(error.description, """ - SQLite error 1: The database view 'items' has no primary key. \ - To support views, provide a custom schema source \ - in Configuration.schemaSource. + SQLite error 1: database view items has no primary key """) } } @@ -282,12 +278,10 @@ class PrimaryKeyInfoTests: GRDBTestCase { } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, """ - The database view 'playerView' has no primary key, \ - according to Configuration.schemaSource. + database view playerView has no primary key """) XCTAssertEqual(error.description, """ - SQLite error 1: The database view 'playerView' has no primary key, \ - according to Configuration.schemaSource. + SQLite error 1: database view playerView has no primary key """) } } @@ -322,12 +316,10 @@ class PrimaryKeyInfoTests: GRDBTestCase { } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, """ - The database view 'playerView' has no primary key, \ - according to Configuration.schemaSource. + database view playerView has no primary key """) XCTAssertEqual(error.description, """ - SQLite error 1: The database view 'playerView' has no primary key, \ - according to Configuration.schemaSource. + SQLite error 1: database view playerView has no primary key """) } } From edd292bcbd0845eda3d361a0af77fa163aa8c3a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Tue, 23 Sep 2025 17:44:05 +0200 Subject: [PATCH 44/45] CHANGELOG --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2d264d45..31070d05a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -138,6 +138,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807) +- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810) +- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813) +- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797) + ## 7.6.1 Released July 23, 2025 From d1bfce829b0fcc2cd9024fbeaa3c27b0dcb3d92e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 23 Sep 2025 19:30:13 +0200 Subject: [PATCH 45/45] v7.7.0 --- CHANGELOG.md | 5 ++++- GRDB.swift.podspec | 2 +- README.md | 2 +- Support/Info.plist | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31070d05a..cc9a7b9ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 7.x Releases +- `7.7.x` Releases - [7.7.0](#770) - `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761) - `7.5.x` Releases - [7.5.0](#750) - `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741) @@ -138,7 +139,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 7.7.0 + +Released September 23, 2025 - **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807) - **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 16bf3ccbb..97d5f0932 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '7.6.1' + s.version = '7.7.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/README.md b/README.md index b0428333a..58d89ce87 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ --- -**Latest release**: July 23, 2025 • [version 7.6.1](https://github.com/groue/GRDB.swift/tree/v7.6.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) +**Latest release**: September 23, 2025 • [version 7.7.0](https://github.com/groue/GRDB.swift/tree/v7.7.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) **Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+ diff --git a/Support/Info.plist b/Support/Info.plist index 23ae401c0..5a7f03b51 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 7.6.1 + 7.7.0 CFBundleSignature ???? CFBundleVersion