diff --git a/CHANGELOG.md b/CHANGELOG.md index e2d264d45..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,6 +139,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 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) +- **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 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 @@ 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b8eed9860..c0d3f02a7 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 */; }; @@ -223,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 */; }; @@ -288,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 */; }; @@ -503,6 +506,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 = ""; }; @@ -674,6 +678,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 = ""; }; @@ -792,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 = ""; }; @@ -997,6 +1003,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, + 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */, ); name = PersistableRecord; sourceTree = ""; @@ -1486,6 +1493,7 @@ 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, + 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */, 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */, 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */, @@ -1592,6 +1600,7 @@ 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */, 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, + 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -1842,8 +1851,9 @@ DC3773EA19C8CBB3004FCF85 /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1400; + LastUpgradeCheck = 2600; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 56E5D7F81B4D422D00430942 = { @@ -2009,6 +2019,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 */, @@ -2113,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 */, @@ -2207,6 +2219,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 */, @@ -2539,6 +2552,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( @@ -2546,6 +2560,7 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11"; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos"; SUPPORTS_MACCATALYST = YES; @@ -2570,6 +2585,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( @@ -2577,6 +2593,7 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11"; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos"; SUPPORTS_MACCATALYST = YES; diff --git a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDB.xcscheme b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDB.xcscheme index 22f2e8b49..29751fc70 100644 --- a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDB.xcscheme +++ b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDB.xcscheme @@ -1,6 +1,6 @@ DatabaseSchemaCache { // internal so that it can be tested + subscript(schemaID: DatabaseSchemaID) -> DatabaseSchemaCache { // internal so that it can be tested get { schemas[schemaID] ?? DatabaseSchemaCache() } @@ -28,74 +28,31 @@ 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 + /// Executes the wrapped statements with the provided schema source. + public 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: @@ -145,40 +102,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 +141,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 +150,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 +159,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 +169,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 +183,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 +217,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 +240,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 +272,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 +301,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 +316,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 +345,12 @@ 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 . + /// + /// 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 @@ -401,18 +360,26 @@ 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 } } - throw DatabaseError.noSuchTable(tableName) + + if (try? viewExists(tableName, in: schemaName)) == true { + throw DatabaseError(message: """ + database view \(tableName) has no primary key + """) + } else { + throw DatabaseError.noSuchTable(tableName) + } } /// 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) @@ -429,9 +396,8 @@ 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. + throw DatabaseError(message: """ + database view \(tableName) has no primary key """) } else { throw error @@ -440,18 +406,47 @@ 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) { return primaryKey.value } - if try !tableExists(table) { - // Views, CTEs, etc. + var primaryKey: PrimaryKeyInfo? + + if let 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 { 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 // @@ -476,22 +471,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] @@ -517,17 +510,55 @@ 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: fetchTableHasRowID(table)) } + default: // Multi-columns primary key - primaryKey = 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 } - schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name) - return primaryKey + 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 @@ -539,19 +570,16 @@ extension Database { /// Returns whether the table has a rowid column. /// /// - precondition: table exists. - private func tableHasRowID(_ table: TableIdentifier) 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 @@ -571,7 +599,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 @@ -601,8 +629,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 +642,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 +651,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 +667,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 +731,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 +755,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 +764,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 } @@ -743,9 +773,9 @@ 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)) + 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 +850,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 +914,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 +967,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,20 +991,44 @@ 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 } + 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); @@ -1013,30 +1071,20 @@ 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) - .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 } @@ -1044,6 +1092,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 @@ -1054,23 +1105,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 @@ -1081,8 +1135,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 @@ -1103,13 +1157,133 @@ extension Database { // try db.existenceCheckColumns(in: "player") // ["uuid"] return primaryKey.columns } - } else { - // 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 + } } } } +/// 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" + } + } + + 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.) +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:)`` @@ -1183,7 +1357,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"] @@ -1480,7 +1654,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? { @@ -1537,13 +1711,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 } } @@ -1587,27 +1763,20 @@ 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 - var hasRowID: Bool + /// False for tables with a rowid, and for views. + var isWithoutRowIDTable: Bool 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] - hasRowID = !row[4] + isWithoutRowIDTable = row[4] strict = row[5] } } @@ -1667,10 +1836,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/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..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:)`` @@ -169,7 +174,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 @@ -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`` @@ -442,6 +460,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 @@ -459,7 +478,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 @@ -806,7 +825,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. @@ -1286,7 +1305,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 +1502,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 +1645,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() @@ -1744,7 +1763,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/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/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 11387222c..f6e6a84de 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) } @@ -464,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. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 4c791a1d9..21b5db750 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -361,8 +361,13 @@ extension DatabasePool: DatabaseReader { return try await readerPool.get { reader in try await reader.execute { 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) } // The block isolation comes from the DEFERRED transaction. @@ -387,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) } @@ -551,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/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/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/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift new file mode 100644 index 000000000..fa1e6b105 --- /dev/null +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -0,0 +1,218 @@ +/// 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 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 +/// 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. See +/// for a detailed guide about such views. +/// +/// ## 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) +/// ``` +/// +/// ## 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 +/// 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 +/// +/// - ``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. + /// + /// 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**: + /// + /// - 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 all views are identified by + /// // their "id" column: + /// struct MySchemaSource: DatabaseSchemaSource { + /// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { + /// ["id"] + /// } + /// } + /// + /// // 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") + /// } + /// ``` + /// + /// ### 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 unknown views. If needed, use the `db` + /// argument and query the database schema with + /// methods. + /// + /// For example: + /// + /// ```swift + /// // 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 + /// return nil + /// } + /// } + /// } + /// ``` + /// + /// 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 + ) throws -> [String]? +} + +extension DatabaseSchemaSource { + public func columnsForPrimaryKey( + _ db: Database, + inView view: DatabaseObjectID + ) throws -> [String]? { + nil + } +} + +// MARK: - Combined2SchemaSource + +extension DatabaseSchemaSource { + /// Returns a schema source that queries `other` when this source does + /// not perform a 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) + } +} + +// 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 + } +} 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/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 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/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) 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/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/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/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/Documentation.docc/ViewRecords.md b/GRDB/Documentation.docc/ViewRecords.md new file mode 100644 index 000000000..5b256e264 --- /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: 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/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/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/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/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 66816236b..95ad8aed4 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) } @@ -633,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 } } @@ -1133,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/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 9e13293f6..e2b366d57 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -826,10 +826,17 @@ 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 { + 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) \ + \(key.keys.sorted().joined(separator: ", ")) + """) + } } let lowercaseColumns = columns.map { $0.lowercased() } 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/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) } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index fcbb7b884..6fdf125db 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -285,12 +285,14 @@ 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 { // 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 } 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 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() } 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 c3a98756b..019b9e6fb 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: @@ -209,6 +209,10 @@ public protocol TableRecord { /// // 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/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/Utils/Utils.swift b/GRDB/Utils/Utils.swift index d690b9eec..47bb3a16c 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -23,6 +23,16 @@ public func databaseQuestionMarks(count: Int) -> String { repeatElement("?", count: count).joined(separator: ",") } +#if compiler(>=6.2) +/// 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 the standard `SendableMetatype` protocol in Swift 6.2, +/// and `Any` in previous compiler versions. +public typealias GRDBSendableMetatype = Any +#endif + // MARK: - Internal /// Reserved for GRDB: do not use. 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 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 diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 24d55315b..5ae342ef8 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 */; }; @@ -219,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 */; }; @@ -279,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 */; }; @@ -516,6 +519,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 = ""; }; @@ -698,6 +702,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 = ""; }; @@ -801,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 = ""; }; @@ -1011,6 +1017,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, + 568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */, ); name = PersistableRecord; sourceTree = ""; @@ -1491,6 +1498,7 @@ 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, + 56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */, 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */, 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */, @@ -1597,6 +1605,7 @@ 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */, 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, + 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -1880,8 +1889,9 @@ DC3773EA19C8CBB3004FCF85 /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1400; + LastUpgradeCheck = 2600; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { F3BA80591CFB2BB2003DC1BA = { @@ -2028,6 +2038,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 */, @@ -2252,6 +2263,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 */, @@ -2368,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 */, @@ -2555,6 +2568,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( @@ -2562,6 +2576,7 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11"; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "appletvos appletvsimulator driverkit iphoneos iphonesimulator macosx watchos watchsimulator"; SUPPORTS_MACCATALYST = YES; @@ -2588,6 +2603,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = ( @@ -2595,6 +2611,7 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11"; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "appletvos appletvsimulator driverkit iphoneos iphonesimulator macosx watchos watchsimulator"; SUPPORTS_MACCATALYST = YES; diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustom.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustom.xcscheme index e755da341..f4810616a 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustom.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustom.xcscheme @@ -1,6 +1,6 @@ **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 > } 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/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 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 - 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 diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index a872849dd..013984344 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -491,15 +491,19 @@ 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 */; }; 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 */ @@ -752,8 +756,10 @@ 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 = ""; }; + 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 = ""; }; @@ -769,7 +775,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, + 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -935,6 +941,7 @@ 56419CF724A5405A004967E1 /* DatabaseRegionObservationTests.swift */, 56419D2624A5405D004967E1 /* DatabaseRegionTests.swift */, 56419CB324A54055004967E1 /* DatabaseSavepointTests.swift */, + 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */, 567B5C222AD32A2D00629622 /* DatabaseSnapshotPoolTests.swift */, 56419CE624A54058004967E1 /* DatabaseSnapshotTests.swift */, 56419CD624A54057004967E1 /* DatabaseSuspensionTests.swift */, @@ -1019,6 +1026,7 @@ 56419C9F24A54054004967E1 /* Record+QueryInterfaceRequestTests.swift */, 56419D0C24A5405B004967E1 /* RecordEditedTests.swift */, 56419CAE24A54054004967E1 /* RecordInitializersTests.swift */, + 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */, 567B5C262AD32A2D00629622 /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, 56419D4224A5405F004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, 56419D0824A5405B004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */, @@ -1380,6 +1388,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 */, @@ -1484,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 */, @@ -1630,6 +1640,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 */, @@ -1734,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 64c03419a..370f75c10 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 */; }; @@ -497,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 */ @@ -748,6 +752,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 = ""; }; @@ -757,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 = ""; }; @@ -772,7 +778,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, + 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -939,6 +945,7 @@ 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */, 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */, 56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */, + 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */, 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */, 56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */, 56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */, @@ -1023,6 +1030,7 @@ 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */, 56419F2124A54094004967E1 /* RecordEditedTests.swift */, 56419F4824A54097004967E1 /* RecordInitializersTests.swift */, + 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */, 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, 56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, 56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */, @@ -1386,6 +1394,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 */, @@ -1490,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 */, @@ -1636,6 +1646,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 */, @@ -1740,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/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 + """) + } + } } } 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]) } } 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 { diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index b82d221d0..f17401eb2 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -1109,4 +1109,61 @@ 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. + XCTAssertNil(db.schemaSource) + XCTAssertThrowsError(try db.primaryKey("myView")) + } + try migrator.migrate(dbQueue) + } + + 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) + } } 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.. [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"]) + } + } + } +} 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/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() diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index efe2ac8da..7cae11b84 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -26,8 +26,12 @@ 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, """ + database view items has no primary key + """) + XCTAssertEqual(error.description, """ + SQLite error 1: database view items has no primary key + """) } } } @@ -242,4 +246,117 @@ 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, """ + database view playerView has no primary key + """) + XCTAssertEqual(error.description, """ + SQLite error 1: database view playerView has no primary key + """) + } + } + } + + 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, """ + database view playerView has no primary key + """) + XCTAssertEqual(error.description, """ + SQLite error 1: database view playerView has no primary key + """) + } + } + } + + 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) + } + } + } } diff --git a/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift new file mode 100644 index 000000000..429f8f1d9 --- /dev/null +++ b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift @@ -0,0 +1,386 @@ +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: Captain.teamForeignKey) +} + +private struct Captain: Codable, + Equatable, + Identifiable, + FetchableRecord, + PersistableRecord +{ + var id: String + var name: String + var teamId: String + + 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 { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + if view.name == "captain" { + return ["id"] + } else { + // Do not customize + return nil + } + } +} + +class RecordMappedOnMutableViewTests : GRDBTestCase { + 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")) + } + + 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; + """) + } + + 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; + + -- 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; + + -- 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) + + 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 + 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 migrator.migrate(dbQueue) + try dbQueue.write { db in + 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 migrator.migrate(dbQueue) + try dbQueue.write { db in + 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 migrator.migrate(dbQueue) + try dbQueue.write { db in + 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 migrator.migrate(dbQueue) + try dbQueue.write { db in + 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")), + ]) + } + } + } +} diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index a2fe139fe..386cc3cdf 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]) + } + } + + // TODO: duplicate test with views? func testJoinedRequestDeleteAll() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -460,6 +837,7 @@ class TableRecordDeleteTests: GRDBTestCase { } } + // 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 b851b6538..3ee015537 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 { } } + // TODO: duplicate test with views? func testJoinedRequestUpdate() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -1314,6 +1753,7 @@ class TableRecordUpdateTests: GRDBTestCase { } } + // TODO: duplicate test with views? func testJoinedRequestUpdate_DatabaseComponents() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme index 143cc0289..c8bc2d0a8 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme @@ -1,6 +1,6 @@