diff --git a/.gitignore b/.gitignore index cd1383aee..7c7e11035 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -## https://github.com/github/gitignore/blob/master/Global/OSX.gitignore +## https://github.com/github/gitignore/blob/master/Global/macOS.gitignore .DS_Store .AppleDouble diff --git a/BRAG.md b/BRAG.md index e56e8f4d6..284b8b083 100644 --- a/BRAG.md +++ b/BRAG.md @@ -4,6 +4,46 @@ Here is a list of people who were happy to meet GRDB :-) --- +https://twitter.com/DamienPetrilli/status/1623922310976786433 + +> I can't overstate how much more productive I am since I ditched the obsolete Core Data framework and started to use GRDB instead. +> +> The hard stuff is doable, and the simple stuff is even simpler, as it should be. + +--- + +https://twitter.com/fullqueuedev/status/1603350969357684736 + +> Yes, I much prefer GRDB. I’ve tested many SQLite wrappers over the years πŸ’œ + +--- + +https://twitter.com/cassiuspacheco/status/1574948903857770497 + +> SQLite using @groue’s GRDB, no brainer! Awesome documentation, support and beautifully designed. + +--- + +https://twitter.com/simrandotdev/status/1552004471122587649 + +> We get Core Data from Apple which is the worst library to deal with. +> Then there is Realm which is nice but again you do not get the RAW SQL power as it is its own type of Db. +> Then comes the most beautiful library every written which is very close to Room called GRDB. + +--- + +https://twitter.com/bellebcooper/status/1534070340850094080 + +> When I first started using GRDB I didn't know SQL or much at all about databases 😬 So I've always really liked the query API. But these days I really appreciate that you support raw SQL too, because it gives me more control and freedom when I need it. πŸ‘πŸ‘πŸ‘ + +--- + +https://twitter.com/mikeash/status/1504810545429499909 + +> Another cool library using SQL interpolation! + +--- + https://twitter.com/swiftkarim/status/1354753451377483781 > I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful! diff --git a/CHANGELOG.md b/CHANGELOG.md index c487c37ad..bcba96b78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.7.x` Releases - [6.7.0](#670) - `6.6.x` Releases - [6.6.0](#660) - [6.6.1](#661) - `6.5.x` Releases - [6.5.0](#650) - `6.4.x` Releases - [6.4.0](#640) @@ -104,6 +105,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.7.0 + +Released February 19, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.6.1...v6.7.0) + +- **Fixed**: [#1316](https://github.com/groue/GRDB.swift/pull/1316) and [#1320](https://github.com/groue/GRDB.swift/pull/1320) by [@baekteun](https://github.com/baekteun): Replace "OSX" with "macOS". +- **Fixed**: [#1328](https://github.com/groue/GRDB.swift/pull/1328) by [@ytti](https://github.com/ytti): Fix documentation about Data passphrases. +- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version. +- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date +- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default +- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records. +- Added support for `Table` in SQL interpolation. + ## 6.6.1 Released January 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.6.0...v6.6.1) @@ -3660,7 +3673,7 @@ It comes with breaking changes, but the good news is that they are the last (unt As a matter of fact, GRDB 1.0 still supports Xcode 8.1 and Swift 3.0. But future versions are free to use Swift 3.1 features, and will require Xcode 8.3+. - The targetted operating systems are unchanged: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ + The targetted operating systems are unchanged: iOS 8.0+ / macOS 10.9+ / watchOS 2.0+ - **[Record types](https://github.com/groue/GRDB.swift#records) have their `persistentDictionary` property replaced with the `encode(to:)` method:** @@ -5468,11 +5481,11 @@ Released May 17, 2016 **Fixed** -- Restored support for iOS before 8.2 and OS X before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51). +- Restored support for iOS before 8.2 and macOS before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51). **Breaking Changes** -- Support for advanced migrations is not available until iOS 8.2 and OS X 10.10: +- Support for advanced migrations is not available until iOS 8.2 and macOS 10.10: ```diff struct DatabaseMigrator { @@ -5528,7 +5541,7 @@ Released May 10, 2016 **New** -- `FetchedRecordsController` is now exposed in OSX CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller)) +- `FetchedRecordsController` is now exposed in macOS CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller)) **Fixed** @@ -5661,7 +5674,7 @@ Released April 5, 2016 **Fixed** -- Restored CocoaPods support for iOS 8+ and OS X 10.9+ +- Restored CocoaPods support for iOS 8+ and macOS 10.9+ ## 0.56.0 @@ -5704,7 +5717,7 @@ Released March 31, 2016 Released March 29, 2016 -This release restores CocoaPods support for iOS 9.0+ and OSX 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or OSX 10.9+ in a further release. +This release restores CocoaPods support for iOS 9.0+ and macOS 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or macOS 10.9+ in a further release. ## 0.54.0 @@ -6603,7 +6616,7 @@ Released August 25, 2015 **Fixed** -- Reduced iOS Deployment Target to 8.0, and OSX Deployment Target to 10.9. +- Reduced iOS Deployment Target to 8.0, and macOS Deployment Target to 10.9. - `DatabaseQueue.inTransaction()` is now declared as `rethrows`. **Breaking changes** diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 77396313e..0aa7b8379 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -40,6 +40,20 @@ remoteGlobalIDString = 56B036021E8D9EBE003B6DA4; remoteInfo = GRDBDemoiOS; }; + 5642252F29A2390800D714BF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = DC3773F219C8CBB3004FCF85; + remoteInfo = GRDB; + }; + 5642253329A2391900D714BF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = DC3773F219C8CBB3004FCF85; + remoteInfo = GRDB; + }; 56606D092355931F00185962 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; @@ -328,6 +342,7 @@ buildRules = ( ); dependencies = ( + 5642253429A2391900D714BF /* PBXTargetDependency */, ); name = "GRDBDemoWatchOS Extension"; productName = "GRDBDemoWatchOS Extension"; @@ -347,6 +362,7 @@ buildRules = ( ); dependencies = ( + 5642253029A2390800D714BF /* PBXTargetDependency */, 568E5FD81E926430002582E0 /* PBXTargetDependency */, ); name = GRDBDemoiOS; @@ -511,6 +527,16 @@ target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */; targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */; }; + 5642253029A2390800D714BF /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GRDB; + targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */; + }; + 5642253429A2391900D714BF /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GRDB; + targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */; + }; 568E5FCE1E926430002582E0 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */; diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 8ff58693f..eca1c7ca7 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -197,7 +197,7 @@ The changes can quite impact your application. We'll describe them below, as wel scheduling: .immediate, onError: { error in ... }, onChange: { [weak self] (players: [Player]) in - guard let self = self else { return } + guard let self else { return } self.updateView(players) }) // <- Here the view has already been updated. diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index be4015f98..1fd67547b 100644 --- a/Documentation/Playgrounds/Associations.playground/Contents.swift +++ b/Documentation/Playgrounds/Associations.playground/Contents.swift @@ -103,7 +103,7 @@ let authorInfo: AuthorInfo? = try dbQueue.read { db in let books = try author.books.fetchAll(db) return AuthorInfo(author: author, books: books) } -if let authorInfo = authorInfo { +if let authorInfo { print("\(authorInfo.author.name) has written:") for book in authorInfo.books { print("- \(book.title)") @@ -126,7 +126,7 @@ let bookInfo: BookInfo? = try dbQueue.read { db in .including(required: Book.author) return try BookInfo.fetchOne(db, request) } -if let bookInfo = bookInfo { +if let bookInfo { print("\(bookInfo.book.title) was written by \(bookInfo.author.name)") } diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 884c19788..3a00cce83 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -363,7 +363,7 @@ Let's extend Player with database methods. This chapter lists all kinds of supported interpolations. -- Types adopting the [TableRecord] protocol: +- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table) instances: ```swift struct Player: TableRecord { ... } @@ -371,9 +371,13 @@ This chapter lists all kinds of supported interpolations. // SELECT * FROM player "SELECT * FROM \(Player.self)" - // INSERT INTO player ... + // SELECT * FROM player let player: Player = ... - "INSERT INTO \(tableOf: player) ..." + "SELECT * FROM \(tableOf: player) ..." + + // SELECT * FROM player + let playerTable = Table("player") + "SELECT * FROM \(playerTable)" ``` - Columns selected by [TableRecord]: diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 6115f9f49..ec0e657ef 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.6.1' + s.version = '6.7.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' @@ -20,6 +20,9 @@ Pod::Spec.new do |s| ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h' ss.framework = 'Foundation' ss.library = 'sqlite3' + ss.xcconfig = { + 'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5', + } end s.subspec 'SQLCipher' do |ss| diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 089a9fd2a..1d711ca40 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -250,6 +250,8 @@ 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; }; 56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; }; 56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; }; + 56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; }; + 56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; }; 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; }; @@ -711,6 +713,8 @@ 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = ""; }; 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; + 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = ""; }; + 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = ""; }; 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; @@ -1368,6 +1372,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, + 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, ); name = Core; @@ -1467,6 +1472,7 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, + 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, 5605F1471C672E4000235C62 /* Support */, @@ -1950,6 +1956,7 @@ 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, + 56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, @@ -2098,6 +2105,7 @@ 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, + 56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, 56959629222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */, diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index 1fec2cce9..3258ed7a7 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -17,6 +17,9 @@ location = "group:MyPlayground.playground"> + + diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 2316c2cb1..0dae035df 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -169,6 +169,21 @@ public struct Configuration { /// ``` public var publicStatementArguments = false + /// The clock that feeds ``Database/transactionDate``. + /// + /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The default clock is ``DefaultTransactionClock`` (which returns the + /// current date with `Date()`). + /// + /// For example: + /// + /// ```swift + /// var config = Configuration() + /// config.transactionClock = .custom { db in /* return some Date */ } + /// ``` + public var transactionClock: TransactionClock = .default + // MARK: - Managing SQLite Connections private var setups: [(Database) throws -> Void] = [] @@ -406,7 +421,7 @@ public struct Configuration { /// Creates a DispatchQueue which has the quality of service and target /// queue of read accesses. func makeReaderDispatchQueue(label: String) -> DispatchQueue { - if let targetQueue = targetQueue { + if let targetQueue { return DispatchQueue(label: label, target: targetQueue) } else { return DispatchQueue(label: label, qos: qos) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index a4350e39f..1e7338e02 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -387,7 +387,7 @@ extension Database { return try self.table(for: table)!.hasRowID } #else - if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { + if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+ return try self.table(for: table)!.hasRowID } #endif @@ -912,7 +912,7 @@ public struct ColumnInfo: FetchableRecord { /// Information about an index. /// -/// You get `ForeignKeyInfo` instances with the ``Database/indexes(on:)`` +/// You get `IndexInfo` instances with the ``Database/indexes(on:)`` /// `Database` method. /// /// Related SQLite documentation: @@ -1032,7 +1032,7 @@ public struct ForeignKeyViolation { }) var description: String - if let foreignKey = foreignKey { + if let foreignKey { description = """ FOREIGN KEY constraint violation - \ from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \ @@ -1042,9 +1042,9 @@ public struct ForeignKeyViolation { description = "FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)" } - if let originRow = originRow { + if let originRow { description += ", in \(String(describing: originRow))" - } else if let originRowID = originRowID { + } else if let originRowID { description += ", in rowid \(originRowID)" } @@ -1084,7 +1084,7 @@ extension ForeignKeyViolation: CustomStringConvertible { /// /// See also ``failureDescription(_:)``. public var description: String { - if let originRowID = originRowID { + if let originRowID { return """ FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable), \ in rowid \(originRowID) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 6a8d52f01..c3fabdeaf 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -406,8 +406,8 @@ extension SQLStatementCursor: Cursor { /// Check that all arguments were consumed: it is a programmer error to /// provide arguments that do not match the statements. private func checkArgumentsAreEmpty() throws { - if let arguments = arguments, - let initialArgumentCount = initialArgumentCount, + if let arguments, + let initialArgumentCount, arguments.values.isEmpty == false { throw DatabaseError( @@ -445,6 +445,8 @@ extension Database { clearSchemaCache() } + checkForAutocommitTransition() + // Database observation: cleanup try observationBroker?.statementDidExecute(statement) } @@ -460,6 +462,8 @@ extension Database { internalStatementCache.remove(statement) publicStatementCache.remove(statement) + checkForAutocommitTransition() + // Extract values that may be modified by the user in their // `TransactionObserver.databaseDidRollback(_:)` implementation // (see below). @@ -481,6 +485,25 @@ extension Database { arguments: arguments, publicStatementArguments: configuration.publicStatementArguments) } + + private func checkForAutocommitTransition() { + if sqlite3_get_autocommit(sqliteConnection) == 0 { + if autocommitState == .on { + // Record transaction date as soon as the connection leaves + // auto-commit mode. + // We grab a result, so that this failure is later reported + // whenever the user calls `Database.transactionDate`. + transactionDateResult = Result { try configuration.transactionClock.now(self) } + } + autocommitState = .off + } else { + if autocommitState == .off { + // Reset transaction date + transactionDateResult = nil + } + autocommitState = .on + } + } } /// A thread-unsafe statement cache @@ -510,7 +533,7 @@ struct StatementCache { let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) #else let statement: Statement - if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { + if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+ statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) } else { statement = try db.makeStatement(sql: sql) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index fb0e129c2..c007c812d 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -61,6 +61,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``inTransaction(_:_:)`` /// - ``isInsideTransaction`` /// - ``rollback()`` +/// - ``transactionDate`` /// - ``TransactionCompletion`` /// - ``TransactionKind`` /// @@ -276,6 +277,60 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? + // MARK: - Transaction Date + + enum AutocommitState { + case off + case on + } + + /// The state of the auto-commit mode, as left by the last + /// executed statement. + /// + /// The goal of this property is to detect changes in the auto-commit mode. + /// When you need to know if the database is currently in the auto-commit + /// mode, always prefer ``isInsideTransaction``. + var autocommitState = AutocommitState.on + + /// The date of the current transaction, wrapped in a result that is an + /// error if there was an error grabbing this date when the transaction has + /// started. + /// + /// Invariant: `transactionDateResult` is nil iff connection is not + /// inside a transaction. + var transactionDateResult: Result? + + /// The date of the current transaction. + /// + /// The returned date is constant at any point during a transaction. It is + /// set when the database leaves the + /// [autocommit mode](https://www.sqlite.org/c3ref/get_autocommit.html) with + /// a `BEGIN` statement. + /// + /// When the database is not currently in a transaction, a new date is + /// returned on each call. + /// + /// See for an example of usage. + /// + /// Transaction dates, by default, are built from a new `Date()` instance. + /// You can override this default behavior by configuring + /// ``Configuration/transactionClock``. + public var transactionDate: Date { + get throws { + SchedulingWatchdog.preconditionValidQueue(self) + + // Check invariant: `transactionDateResult` is nil iff connection + // is not inside a transaction. + assert(isInsideTransaction || transactionDateResult == nil) + + if let transactionDateResult { + return try transactionDateResult.get() + } else { + return try configuration.transactionClock.now(self) + } + } + } + // MARK: - Private properties /// Support for ``Configuration/busyMode``. @@ -335,10 +390,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib _ = sqlite3_close(sqliteConnection) // ignore result code throw DatabaseError(resultCode: code) } - if let sqliteConnection = sqliteConnection { - return sqliteConnection + guard let sqliteConnection else { + throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? } - throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? + return sqliteConnection } // MARK: - Database Setup @@ -1163,7 +1218,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - if let firstError = firstError { + if let firstError { throw firstError } } @@ -1312,7 +1367,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - if let firstError = firstError { + if let firstError { throw firstError } } @@ -1861,10 +1916,10 @@ extension Database { enum Impl { case trace_v1(String) case trace_v2( - sqliteStatement: SQLiteStatement, - unexpandedSQL: UnsafePointer?, - sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?, - publicStatementArguments: Bool) // See Configuration.publicStatementArguments + sqliteStatement: SQLiteStatement, + unexpandedSQL: UnsafePointer?, + sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?, + publicStatementArguments: Bool) // See Configuration.publicStatementArguments } var impl: Impl @@ -1886,7 +1941,7 @@ extension Database { fatalError("Unavailable statement SQL") case let .trace_v2(sqliteStatement, unexpandedSQL, _, _): - if let unexpandedSQL = unexpandedSQL { + if let unexpandedSQL { return String(cString: unexpandedSQL).trimmedSQLStatement } else { return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 7fdc9d1ab..a703f9c2a 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -198,7 +198,7 @@ extension ResultCode: CustomStringConvertible { } public var description: String { - if let errorString = errorString { + if let errorString { return "\(rawValue) (\(errorString))" } else { return "\(rawValue)" @@ -543,13 +543,13 @@ extension DatabaseError: CustomStringConvertible { /// without notice: don't have your application rely on any specific format. public var description: String { var description = "SQLite error \(resultCode.rawValue)" - if let message = message { + if let message { description += ": \(message)" } - if let sql = sql { + if let sql { description += " - while executing `\(sql)`" } - if publicStatementArguments, let arguments = arguments, !arguments.isEmpty { + if publicStatementArguments, let arguments, !arguments.isEmpty { description += " with arguments \(arguments)" } return description @@ -571,13 +571,13 @@ extension DatabaseError: CustomStringConvertible { /// property with care. public var expandedDescription: String { var description = "SQLite error \(resultCode.rawValue)" - if let message = message { + if let message { description += ": \(message)" } - if let sql = sql { + if let sql { description += " - while executing `\(sql)`" } - if let arguments = arguments, !arguments.isEmpty { + if let arguments, !arguments.isEmpty { description += " with arguments \(arguments)" } return description @@ -598,7 +598,7 @@ extension DatabaseError: CustomNSError { /// Part of the `CustomNSError` conformance. public var errorUserInfo: [String: Any] { var userInfo = [NSLocalizedDescriptionKey: description] - if let message = message { + if let message { userInfo[NSLocalizedFailureReasonErrorKey] = message } return userInfo diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 3f146ceb3..4abc2e085 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -116,7 +116,7 @@ public final class DatabasePool { // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error - // Explicit unregistration is required before OS X 10.11. + // Explicit unregistration is required before macOS 10.11. NotificationCenter.default.removeObserver(self) // Close reader connections before the writer connection. diff --git a/GRDB/Core/DatabasePublishers.swift b/GRDB/Core/DatabasePublishers.swift index 3aa69d9d9..8f8054953 100644 --- a/GRDB/Core/DatabasePublishers.swift +++ b/GRDB/Core/DatabasePublishers.swift @@ -1,5 +1,5 @@ #if canImport(Combine) /// A namespace for database Combine publishers. -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public enum DatabasePublishers { } #endif diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ddb3bf494..ed5d1bcce 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -103,7 +103,7 @@ public final class DatabaseQueue { // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error - // Explicit unregistration is required before OS X 10.11. + // Explicit unregistration is required before macOS 10.11. NotificationCenter.default.removeObserver(self) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 6bea5c1bb..2ac917d1f 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -441,7 +441,7 @@ extension DatabaseReader { /// - parameter value: A closure which accesses the database. /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func read(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncRead { result in @@ -487,7 +487,7 @@ extension DatabaseReader { /// - parameter value: A closure which accesses the database. /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func unsafeRead(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncUnsafeRead { result in @@ -532,7 +532,7 @@ extension DatabaseReader { /// /// - parameter scheduler: A Combine Scheduler. /// - parameter value: A closure which accesses the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, value: @escaping (Database) throws -> Output) @@ -550,7 +550,7 @@ extension DatabaseReader { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that reads from the database. /// @@ -569,7 +569,7 @@ extension DatabasePublishers { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher where Failure == Error { fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read { .init(upstream: eraseToAnyPublisher()) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 384a9e414..232cd472d 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -287,8 +287,8 @@ private struct TableRegion: Equatable { var rowIds: Set? // nil means "all rowids" var isEmpty: Bool { - if let columns = columns, columns.isEmpty { return true } - if let rowIds = rowIds, rowIds.isEmpty { return true } + if let columns, columns.isEmpty { return true } + if let rowIds, rowIds.isEmpty { return true } return false } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index eb95739af..0e69ea865 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -231,7 +231,7 @@ extension DatabaseRegionObservation { } #if canImport(Combine) -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabaseRegionObservation { // MARK: - Publishing Impactful Transactions @@ -243,7 +243,7 @@ extension DatabaseRegionObservation { /// /// Do not reschedule the publisher with `receive(on:options:)` or any /// `Publisher` method that schedules publisher elements. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion { DatabasePublishers.DatabaseRegion(self, in: writer) } @@ -284,7 +284,7 @@ private class DatabaseRegionObserver: TransactionObserver { } #if canImport(Combine) -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that tracks transactions that modify a database region. /// diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index dcfbd4cb8..33cee1292 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -322,7 +322,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { return result } } else { - /// There is no unsafe access to a snapshot. + // There is no unsafe access to a snapshot. return try read(value) } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 44afac439..ce5017a42 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -159,7 +159,7 @@ public final class DatabaseValueCursor: Databas init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self._statement = statement - if let adapter = adapter { + if let adapter { // adapter may redefine the index of the leftmost column columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index a1ada352c..1861d1505 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -516,7 +516,7 @@ extension DatabaseWriter { /// /// - Parameter filePath: file path for new database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) public func vacuum(into filePath: String) throws { try writeWithoutTransaction { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) @@ -582,7 +582,7 @@ extension DatabaseWriter { /// - throws: The error thrown by `updates`, or any ``DatabaseError`` that /// would happen while establishing the database access or committing /// the transaction. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func write(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncWrite(updates, completion: { _, result in @@ -620,7 +620,7 @@ extension DatabaseWriter { /// /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func writeWithoutTransaction(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in asyncWriteWithoutTransaction { db in @@ -672,7 +672,7 @@ extension DatabaseWriter { /// /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func barrierWriteWithoutTransaction( _ updates: @Sendable @escaping (Database) throws -> T) async throws -> T @@ -687,7 +687,7 @@ extension DatabaseWriter { /// Erases the content of the database. /// /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func erase() async throws { try await writeWithoutTransaction { try $0.erase() } } @@ -698,7 +698,7 @@ extension DatabaseWriter { /// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// /// Related SQLite documentation: - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func vacuum() async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") } } @@ -715,7 +715,7 @@ extension DatabaseWriter { /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func vacuum(into filePath: String) async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) @@ -730,7 +730,7 @@ extension DatabaseWriter { /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func vacuum(into filePath: String) async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) @@ -775,7 +775,7 @@ extension DatabaseWriter { /// /// - parameter scheduler: A Combine Scheduler. /// - parameter updates: A closure which accesses the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, updates: @escaping (Database) throws -> Output) @@ -840,7 +840,7 @@ extension DatabaseWriter { /// - parameter scheduler: A Combine Scheduler. /// - parameter updates: A closure which writes in the database. /// - parameter value: A closure which reads from the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func writePublisher( receiveOn scheduler: S = DispatchQueue.main, updates: @escaping (Database) throws -> T, @@ -872,7 +872,7 @@ extension DatabaseWriter { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that writes into the database. /// @@ -891,7 +891,7 @@ extension DatabasePublishers { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher where Failure == Error { fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write { .init(upstream: self.eraseToAnyPublisher()) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index b37822c02..9e4c64a84 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -682,7 +682,7 @@ extension Row { /// ``JoinableRequest/including(optional:)`` request methods define scopes /// named after the key of included associations between record types. /// - /// A depth-first search is performed in all available scopes in the row, + /// A breadth-first search is performed in all available scopes in the row, /// recursively. /// /// A fatal error is raised if the scope is not available, or contains only @@ -726,7 +726,7 @@ extension Row { /// ``JoinableRequest/including(optional:)`` request methods define scopes /// named after the key of included associations between record types. /// - /// A depth-first search is performed in all available scopes in the row, + /// A breadth-first search is performed in all available scopes in the row, /// recursively. /// /// The result is nil if the scope is not available, or contains only @@ -879,7 +879,7 @@ extension Row { /// A view on the scopes tree defined by row adapters. /// /// The returned object provides an access to all available scopes in - /// the row, recursively. For any given scope identifier, a depth-first + /// the row, recursively. For any given scope identifier, a breadth-first /// search is performed. /// /// Row scopes can be defined manually, with ``ScopeAdapter``. diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 644251c81..4246cf202 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -121,8 +121,8 @@ public struct SQL { fileprivate func qualified(with alias: TableAlias) -> Element { switch self { case .sql: - /// A raw SQL string can't be qualified with a table alias, - /// because we can't parse it. + // A raw SQL string can't be qualified with a table alias, + // because we can't parse it. return self case .subquery: // Subqueries don't need table alias diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 8a0bd2043..6ec272c57 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -206,9 +206,9 @@ extension SQLRequest: FetchRequest { switch cache { case .none: statement = try db.makeStatement(sql: sql) - case .public?: + case .public: statement = try db.cachedStatement(sql: sql) - case .internal?: + case .internal: statement = try db.internalCachedStatement(sql: sql) } try statement.setArguments(context.arguments) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 39e98827f..5f2334bb2 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -175,7 +175,7 @@ public final class Statement { database.sqliteConnection, statementStart, -1, prepFlags, &sqliteStatement, statementEnd) #else - if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) { + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+ code = sqlite3_prepare_v3( database.sqliteConnection, statementStart, -1, prepFlags, &sqliteStatement, statementEnd) @@ -294,7 +294,7 @@ public final class Statement { var valuesIterator = arguments.values.makeIterator() for (index, argumentName) in zip(CInt(1)..., sqliteArgumentNames) { - if let argumentName = argumentName, let value = arguments.namedValues[argumentName] { + if let argumentName, let value = arguments.namedValues[argumentName] { bind(value, at: index) } else if let value = valuesIterator.next() { bind(value, at: index) @@ -372,7 +372,7 @@ public final class Statement { func reset(withArguments arguments: StatementArguments?) throws { // Force arguments validity: it is a programmer error to provide // arguments that do not match the statement. - if let arguments = arguments { + if let arguments { try setArguments(arguments) } else if argumentsNeedValidation { try reset() @@ -1122,7 +1122,7 @@ public struct StatementArguments: Hashable { { let initialValuesCount = values.count let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in - if let argumentName = argumentName { + if let argumentName { if let dbValue = namedValues[argumentName] { return dbValue } else if values.isEmpty { diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index e77d823eb..5fe6f9dbe 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -107,7 +107,7 @@ final class StatementAuthorizer { case SQLITE_DELETE: if isDropStatement { return SQLITE_OK } - guard let cString1 = cString1 else { return SQLITE_OK } + guard let cString1 else { return SQLITE_OK } // Deletions from sqlite_master and sqlite_temp_master are not like // other deletions: `sqlite3_update_hook` does not notify them, and @@ -137,7 +137,7 @@ final class StatementAuthorizer { return SQLITE_OK case SQLITE_TRANSACTION: - guard let cString1 = cString1 else { return SQLITE_OK } + guard let cString1 else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginTransaction } else if strcmp(cString1, "COMMIT") == 0 { @@ -148,7 +148,7 @@ final class StatementAuthorizer { return SQLITE_OK case SQLITE_SAVEPOINT: - guard let cString1 = cString1 else { return SQLITE_OK } + guard let cString1 else { return SQLITE_OK } guard let name = cString2.map(String.init) else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginSavepoint(name) diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 27995317e..87efd16f1 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -215,7 +215,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self._statement = statement - if let adapter = adapter { + if let adapter { // adapter may redefine the index of the leftmost column columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement)) } else { diff --git a/GRDB/Core/TransactionClock.swift b/GRDB/Core/TransactionClock.swift new file mode 100644 index 000000000..0e033d5d6 --- /dev/null +++ b/GRDB/Core/TransactionClock.swift @@ -0,0 +1,64 @@ +import Foundation + +/// A type that provides the moment of a transaction. +/// +/// - note: [**πŸ”₯ EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// ## Topics +/// +/// ### Built-in Clocks +/// +/// - ``DefaultTransactionClock`` +/// - ``CustomTransactionClock`` +public protocol TransactionClock { + /// Returns the date of the current transaction. + /// + /// This function is called whenever a transaction starts - precisely + /// speaking, whenever the database connection leaves the auto-commit mode. + /// + /// It is also called when the ``Database/transactionDate`` property is + /// called, and the database connection is not in a transaction. + /// + /// Related SQLite documentation: + func now(_ db: Database) throws -> Date +} + +extension TransactionClock where Self == DefaultTransactionClock { + /// Returns the default clock. + public static var `default`: Self { DefaultTransactionClock() } +} + +extension TransactionClock where Self == CustomTransactionClock { + /// Returns a custom clock. + /// + /// The provided closure is called whenever a transaction starts - precisely + /// speaking, whenever the database connection leaves the auto-commit mode. + /// + /// It is also called when the ``Database/transactionDate`` property is + /// called, and the database connection is not in a transaction. + public static func custom(_ now: @escaping (Database) throws -> Date) -> Self { + CustomTransactionClock(now) + } +} + +/// The default clock. +public struct DefaultTransactionClock: TransactionClock { + public func now(_ db: Database) throws -> Date { + // An opportunity to fetch transaction time from the database when + // SQLite supports the feature. + Date() + } +} + +/// A custom transaction clock. +public struct CustomTransactionClock: TransactionClock { + let _now: (Database) throws -> Date + + public init(_ now: @escaping (Database) throws -> Date) { + self._now = now + } + + public func now(_ db: Database) throws -> Date { + try _now(db) + } +} diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index e16a0f12d..28e902426 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1125,7 +1125,7 @@ public protocol TransactionObserver: AnyObject { /// /// Requires SQLite compiled with option SQLITE_ENABLE_PREUPDATE_HOOK. /// - /// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library + /// As of macOS 10.11.5, and iOS 9.3.2, the built-in SQLite library /// does not have this enabled, so you'll need to compile your own /// version of SQLite: /// See @@ -1482,7 +1482,7 @@ public struct DatabasePreUpdateEvent { /// The triggering depth of the row update /// Returns: /// 0 if the preupdate callback was invoked as a result of a direct insert, - // update, or delete operation; + /// update, or delete operation; /// 1 for inserts, updates, or deletes invoked by top-level triggers; /// 2 for changes resulting from triggers called by top-level triggers; /// ... and so forth @@ -1699,7 +1699,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { { var value: SQLiteValue? = nil guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } - if let value = value { + if let value { return DatabaseValue(sqliteValue: value) } return nil diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 7ce291061..36f21eb69 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -65,7 +65,7 @@ final class WALSnapshot: Sendable { /// /// See . func compare(_ other: WALSnapshot) -> CInt { - return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot) + sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot) } #else static let available = false diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index eead88397..5fa411950 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -32,6 +32,7 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD ### Records and the Query Interface - +- ### Responding to Database Changes diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index 3954ae64a..87464a9e7 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -94,6 +94,8 @@ do { - ``observesSuspensionNotifications`` - ``prepareDatabase(_:)`` - ``publicStatementArguments`` +- ``transactionClock`` +- ``TransactionClock`` ### Configuring the Quality of Service diff --git a/GRDB/Documentation.docc/FullTextSearch.md b/GRDB/Documentation.docc/FullTextSearch.md index 6fcd4bc52..f7ad9f123 100644 --- a/GRDB/Documentation.docc/FullTextSearch.md +++ b/GRDB/Documentation.docc/FullTextSearch.md @@ -12,3 +12,4 @@ Please refer to the [Full-Text Search](https://github.com/groue/GRDB.swift/blob/ - ``FTS3`` - ``FTS4`` +- ``FTS5`` diff --git a/GRDB/Documentation.docc/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md new file mode 100644 index 000000000..8b3427dcd --- /dev/null +++ b/GRDB/Documentation.docc/RecordTimestamps.md @@ -0,0 +1,187 @@ +# Record Timestamps and Transaction Date + +Learn how applications can save creation and modification dates of records. + +## Overview + +Record timestamps are the responsibility of your application. This article provides some sample code that you can adapt for your specific needs. + +> Note: Creation and modification timestamps can be automatically handled by [SQLite triggers](https://www.sqlite.org/lang_createtrigger.html). We'll explore a different technique. +> +> This is not an advice against triggers, and you won't feel hindered in any way if you prefer to use triggers. Still, consider: +> +> - A trigger does not suffer any exception, when some applications eventually want to fine-tune timestamps, or to perform migrations without touching timestamps. +> - The "current time" according to SQLite can't be controlled in tests and previews. +> - The "current time" according to SQLite is not guaranteed to be constant in a given transaction, and this may create undesired timestamp variations. + +We'll start from this table and record type: + +```swift +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("creationDate", .datetime).notNull() + t.column("modificationDate", .datetime).notNull() + t.column("name", .text).notNull() + t.column("score", .integer).notNull() +} + +struct Player: Identifiable { + var id: Int64? + var creationDate: Date? + var modificationDate: Date? + var name: String + var score: Int +} +``` + +Note that the table has non-null dates, while the record has optional dates. + +This is because we intend, in this article, to timestamp actual database operations. The `creationDate` property is the date of database insertion, and `modificationDate` is the date of last modification in the database. A new `Player` instance has no meaningful timestamp until it is saved, and this absence of information is represented with `nil`: + +```swift +// A new player has no timestamps. +var player = Player(id: nil, name: "Arthur", score: 1000) +player.id // nil, because never saved +player.creationDate // nil, because never saved +player.modificationDate // nil, because never saved + +// After insertion, the player has timestamps. +try dbQueue.write { db in + try player.insert(db) +} +player.id // not nil +player.creationDate // not nil +player.modificationDate // not nil +``` + +In the rest of the article, we'll address insertion first, then updates, and finally we'll see a way to avoid those optional timestamps. + +## Insertion Timestamp + +On insertion, the record should get fresh `creationDate` and `modificationDate`. The ``MutablePersistableRecord`` protocol provides the necessary tooling: + +```swift +extension Player: Encodable, MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } + + // Update timestamps before insertion + mutating func willInsert(_ db: Database) throws { + creationDate = try db.transactionDate + modificationDate = try db.transactionDate + } +} +``` + +Note that we are using the ``Database/transactionDate`` instead of `Date()`. This has two advantages: + +- Within a write transaction, all inserted players get the same timestamp: + + ```swift + // All players have the same timestamp. + try dbQueue.write { db in + for var player in players { + try player.insert(db) + } + } + ``` + +- The transaction date can be configured with ``Configuration/transactionClock``, so that your tests and previews can control the date. + +## Modification Timestamp + +Let's now deal with updates. The `update` persistence method won't automatically bump the timestamp as the `insert` method does. We have to explicitly deal with the modification date: + +```swift +// Increment the player score. +try dbQueue.write { db in + var player: Player + try player.updateChanges(db) { + $0.score += 1 + $0.modificationDate = try db.transactionDate + } +} +``` + +Again, we use ``Database/transactionDate``, so that all modified players get the same timestamp within a given write transaction. + +## Dealing with Optional Timestamps + +When you fetch timestamped records from the database, it may be inconvenient to deal with optional dates, even though the database columns are guaranteed to be not null: + +```swift +let player = try dbQueue.read { db + try Player.find(db, id: 1) +} +player.creationDate // optional πŸ˜• +player.modificationDate // optional πŸ˜• +``` + +A possible technique is to define two record types. + +One record can deal with unsaved players: + +```swift +struct Player: Identifiable { + var id: Int64? + var creationDate: Date? + var modificationDate: Date? + var name: String + var score: Int +} + +extension Player: Encodable, MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } + + // Update timestamps before insertion + mutating func willInsert(_ db: Database) throws { + creationDate = try db.transactionDate + modificationDate = try db.transactionDate + } +} +``` + +The other record only deals with saved players: + +```swift +struct TimestampedPlayer: Identifiable { + let id: Int64 + let creationDate: Date + var modificationDate: Date + var name: String + var score: Int +} + +extension TimestampedPlayer: Codable, FetchableRecord, PersistableRecord { + static var databaseTableName: String { Player.databaseTableName } +} +``` + +Usage: + +```swift +// Fetch +let timestampedPlayer = try dbQueue.read { db + try TimestampedPlayer.find(db, id: 1) +} +timestampedPlayer.creationDate // not optional +timestampedPlayer.modificationDate // not optional + +// Insert +try dbQueue.write { db in + var player = Player(id: nil, name: "Arthur", score: 1000) + + let timestampedPlayer = try player.insertAndFetch(db, as: TimestampedPlayer.self) + + timestampedPlayer.id // not optional + timestampedPlayer.creationDate // not optional + timestampedPlayer.modificationDate // not optional +} +``` + +See ``MutablePersistableRecord/insertAndFetch(_:onConflict:as:)`` and related methods for more information. diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index d93549816..cb308cd06 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -1,7 +1,14 @@ /// The virtual table module for the FTS3 full-text engine. /// /// To create FTS3 tables, use the ``Database`` method -/// ``Database/create(virtualTable:ifNotExists:using:_:)``. +/// ``Database/create(virtualTable:ifNotExists:using:_:)``: +/// +/// ```swift +/// // CREATE VIRTUAL TABLE document USING fts3(content) +/// try db.create(virtualTable: "document", using: FTS3()) { t in +/// t.column("content") +/// } +/// ``` /// /// Related SQLite documentation: /// @@ -23,26 +30,24 @@ public struct FTS3 { /// Options for Latin script characters. public enum Diacritics { - /// Do not remove diacritics from Latin script characters. + /// Do not remove diacritics from Latin script characters. This option + /// matches the `remove_diacritics=0` tokenizer argument. /// - /// This option matches the `remove_diacritics=0` tokenizer argument. + /// Related SQLite documentation: case keep - /// Remove diacritics from Latin script characters. - /// - /// This option matches the `remove_diacritics=1` tokenizer argument. + /// Remove diacritics from Latin script characters. This option matches + /// the `remove_diacritics=1` tokenizer argument. case removeLegacy #if GRDBCUSTOMSQLITE - /// Remove diacritics from Latin script characters. - /// - /// This option matches the `remove_diacritics=2` tokenizer argument. + /// Remove diacritics from Latin script characters. This option matches + /// the `remove_diacritics=2` tokenizer argument. case remove #elseif !GRDBCIPHER - /// Remove diacritics from Latin script characters. - /// - /// This option matches the `remove_diacritics=2` tokenizer argument. - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) // SQLite 3.27+ + /// Remove diacritics from Latin script characters. This option matches + /// the `remove_diacritics=2` tokenizer argument. + @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+ case remove #endif } diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 375ec7f53..378af557c 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -1,11 +1,11 @@ -/// An ``FTS3`` tokenizer. +/// The descriptor for an ``FTS3`` tokenizer. /// /// `FTS3TokenizerDescriptor` can be used in both ``FTS3`` and ``FTS4`` tables. /// /// For example: /// /// ```swift -/// db.create(virtualTable: "book", using: FTS4()) { t in +/// try db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .simple // FTS3TokenizerDescriptor /// } /// ``` @@ -14,7 +14,7 @@ /// /// ## Topics /// -/// ### Creating Tokenizers +/// ### Creating Tokenizer Descriptors /// /// - ``porter`` /// - ``simple`` @@ -34,7 +34,7 @@ public struct FTS3TokenizerDescriptor { /// For example: /// /// ```swift - /// db.create(virtualTable: "book", using: FTS4()) { t in + /// try db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .simple /// } /// ``` @@ -47,7 +47,7 @@ public struct FTS3TokenizerDescriptor { /// For example: /// /// ```swift - /// db.create(virtualTable: "book", using: FTS4()) { t in + /// try db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .porter /// } /// ``` @@ -60,7 +60,7 @@ public struct FTS3TokenizerDescriptor { /// For example: /// /// ```swift - /// db.create(virtualTable: "book", using: FTS4()) { t in + /// try db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .unicode61() /// } /// ``` diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index ab5cbefef..36e5e7c74 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -1,7 +1,14 @@ /// The virtual table module for the FTS4 full-text engine. /// /// To create FTS4 tables, use the ``Database`` method -/// ``Database/create(virtualTable:ifNotExists:using:_:)``. +/// ``Database/create(virtualTable:ifNotExists:using:_:)``: +/// +/// ```swift +/// // CREATE VIRTUAL TABLE document USING fts4(content) +/// try db.create(virtualTable: "document", using: FTS4()) { t in +/// t.column("content") +/// } +/// ``` /// /// Related SQLite documentation: /// @@ -62,7 +69,7 @@ extension FTS4: VirtualTableModule { switch definition.contentMode { case .raw(let content): - if let content = content { + if let content { arguments.append("content=\"\(content)\"") } case .synchronized(let contentTable): @@ -234,7 +241,7 @@ public final class FTS4TableDefinition { /// The FTS4 `prefix` option. /// /// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4'); - /// db.create(virtualTable: "document", using:FTS4()) { t in + /// try db.create(virtualTable: "document", using:FTS4()) { t in /// t.prefixes = [2, 4] /// t.column("content") /// } @@ -300,7 +307,7 @@ public final class FTS4TableDefinition { /// try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") /// ``` /// - /// Related SQLite documentation: + /// Related SQLite documentation: public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 5c1c7fb36..1d1c67a7b 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,19 +1,45 @@ #if SQLITE_ENABLE_FTS5 import Foundation -/// FTS5 lets you define "fts5" virtual tables. +/// The virtual table module for the FTS5 full-text engine. /// -/// // CREATE VIRTUAL TABLE document USING fts5(content) -/// try db.create(virtualTable: "document", using: FTS5()) { t in -/// t.column("content") -/// } +/// To create FTS5 tables, use the ``Database`` method +/// ``Database/create(virtualTable:ifNotExists:using:_:)``: /// -/// See -public struct FTS5: VirtualTableModule { +/// ```swift +/// // CREATE VIRTUAL TABLE document USING fts5(content) +/// try db.create(virtualTable: "document", using: FTS5()) { t in +/// t.column("content") +/// } +/// ``` +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### The FTS5 Module +/// +/// - ``init()`` +/// - ``FTS5TableDefinition`` +/// - ``FTS5ColumnDefinition`` +/// - ``FTS5TokenizerDescriptor`` +/// +/// ### Full-Text Search Pattern +/// +/// - ``FTS5Pattern`` +/// +/// ### FTS5 Tokenizers +/// +/// - ``FTS5Tokenizer`` +/// - ``FTS5CustomTokenizer`` +/// - ``FTS5WrapperTokenizer`` +/// - ``FTS5TokenFlags`` +/// - ``FTS5Tokenization`` +public struct FTS5 { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// - /// See + /// Related SQLite documentation: public enum Diacritics { /// Do not remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=0" tokenizer argument. @@ -30,20 +56,23 @@ public struct FTS5: VirtualTableModule { /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=2" tokenizer argument, /// available from SQLite 3.27.0 - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+ case remove #endif } - /// Creates a FTS5 module suitable for the Database - /// `create(virtualTable:using:)` method. + /// Creates an FTS5 module. /// - /// // CREATE VIRTUAL TABLE document USING fts5(content) - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("content") - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE VIRTUAL TABLE document USING fts5(content) + /// try db.create(virtualTable: "document", using: FTS5()) { t in + /// t.column("content") + /// } + /// ``` + /// + /// See ``Database/create(virtualTable:ifNotExists:using:_:)`` public init() { } // Support for FTS5Pattern initializers. Don't make public. Users tokenize @@ -71,10 +100,70 @@ public struct FTS5: VirtualTableModule { } } - // MARK: - VirtualTableModule Adoption + static func api(_ db: Database) -> UnsafePointer { + // Access to FTS5 is one of the rare SQLite api which was broken in + // SQLite 3.20.0+, for security reasons: + // + // Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api. + // The previous way to access FTS5 does not work any longer. + // + // So let's see which SQLite version we are linked against: + + #if GRDBCUSTOMSQLITE || GRDBCIPHER + // GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more. + return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) + #else + // GRDB is linked against the system SQLite. + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+ + return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) + } else { + return api_v1(db) + } + #endif + } + private static func api_v1(_ db: Database) -> UnsafePointer { + guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { + fatalError("FTS5 is not available") + } + return data.withUnsafeBytes { + $0.bindMemory(to: UnsafePointer.self).first! + } + } + + // Technique given by Jordan Rose: + // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 + private static func api_v2( + _ db: Database, + // swiftlint:disable:next line_length + _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, CInt, CUnsignedInt, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> CInt, + // swiftlint:disable:next line_length + _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) + -> UnsafePointer + { + var statement: SQLiteStatement? = nil + var api: UnsafePointer? = nil + let type: StaticString = "fts5_api_ptr" + + let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil) + guard code == SQLITE_OK else { + fatalError("FTS5 is not available") + } + defer { sqlite3_finalize(statement) } + type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in + _ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil) + } + sqlite3_step(statement) + guard let api else { + fatalError("FTS5 is not available") + } + return api + } +} + +extension FTS5: VirtualTableModule { /// The virtual table module name - public let moduleName = "fts5" + public var moduleName: String { "fts5" } /// Reserved; part of the VirtualTableModule protocol. /// @@ -114,11 +203,11 @@ public struct FTS5: VirtualTableModule { switch definition.contentMode { case let .raw(content, contentRowID): - if let content = content { + if let content { let quotedContent = try content.sqlExpression.quotedSQL(db) arguments.append("content=\(quotedContent)") } - if let contentRowID = contentRowID { + if let contentRowID { let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db) arguments.append("content_rowid=\(quotedContentRowID)") } @@ -203,82 +292,38 @@ public struct FTS5: VirtualTableModule { try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')") } } - - static func api(_ db: Database) -> UnsafePointer { - // Access to FTS5 is one of the rare SQLite api which was broken in - // SQLite 3.20.0+, for security reasons: - // - // Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api. - // The previous way to access FTS5 does not work any longer. - // - // So let's see which SQLite version we are linked against: - - #if GRDBCUSTOMSQLITE || GRDBCIPHER - // GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more. - return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) - #else - // GRDB is linked against the system SQLite. - // - // Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)? - if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) { - // SQLite 3.24.0 or more - return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) - } else { - // SQLite 3.19.3 or less - return api_v1(db) - } - #endif - } - - private static func api_v1(_ db: Database) -> UnsafePointer { - guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { - fatalError("FTS5 is not available") - } - return data.withUnsafeBytes { - $0.bindMemory(to: UnsafePointer.self).first! - } - } - - // Technique given by Jordan Rose: - // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 - private static func api_v2( - _ db: Database, - // swiftlint:disable:next line_length - _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, CInt, CUnsignedInt, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> CInt, - // swiftlint:disable:next line_length - _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) - -> UnsafePointer - { - var statement: SQLiteStatement? = nil - var api: UnsafePointer? = nil - let type: StaticString = "fts5_api_ptr" - - let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil) - guard code == SQLITE_OK else { - fatalError("FTS5 is not available") - } - defer { sqlite3_finalize(statement) } - type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in - _ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil) - } - sqlite3_step(statement) - guard let api else { - fatalError("FTS5 is not available") - } - return api - } } -/// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table. +/// A `FTS5TableDefinition` lets you define the components of an FTS5 +/// virtual table. /// -/// You don't create instances of this class. Instead, you use the Database -/// `create(virtualTable:using:)` method: +/// You don't create instances of this class. Instead, you use the `Database` +/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method: /// -/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition -/// t.column("content") -/// } +/// ```swift +/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition +/// t.column("content") +/// } +/// ``` /// -/// See +/// ## Topics +/// +/// ### Define Columns +/// +/// - ``column(_:)`` +/// +/// ### External Content Tables +/// +/// - ``synchronize(withTable:)`` +/// +/// ### FTS5 Options +/// +/// - ``columnSize`` +/// - ``content`` +/// - ``contentRowID`` +/// - ``detail`` +/// - ``prefixes`` +/// - ``tokenizer`` public final class FTS5TableDefinition { enum ContentMode { case raw(content: String?, contentRowID: String?) @@ -289,25 +334,30 @@ public final class FTS5TableDefinition { fileprivate var columns: [FTS5ColumnDefinition] = [] fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil) - /// The virtual table tokenizer + /// The virtual table tokenizer. /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.tokenizer = .porter() - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE VIRTUAL TABLE "documents" USING fts5(tokenize=porter) + /// try db.create(virtualTable: "document", using: FTS5()) { t in + /// t.tokenizer = .porter() + /// } + /// ``` + /// + /// Related SQLite documentation: public var tokenizer: FTS5TokenizerDescriptor? - /// The FTS5 `content` option + /// The FTS5 `content` option. /// /// When you want the full-text table to be synchronized with the - /// content of an external table, prefer the `synchronize(withTable:)` - /// method. + /// content of an external table, prefer the + /// ``synchronize(withTable:)`` method. /// /// Setting this property invalidates any synchronization previously - /// established with the `synchronize(withTable:)` method. + /// established with the ``synchronize(withTable:)`` method. /// - /// See + /// Related SQLite documentation: public var content: String? { get { switch contentMode { @@ -330,13 +380,13 @@ public final class FTS5TableDefinition { /// The FTS5 `content_rowid` option /// /// When you want the full-text table to be synchronized with the - /// content of an external table, prefer the `synchronize(withTable:)` - /// method. + /// content of an external table, prefer the + /// ``synchronize(withTable:)`` method. /// /// Setting this property invalidates any synchronization previously - /// established with the `synchronize(withTable:)` method. + /// established with the ``synchronize(withTable:)`` method. /// - /// See + /// Related SQLite documentation: public var contentRowID: String? { get { switch contentMode { @@ -356,19 +406,19 @@ public final class FTS5TableDefinition { } } - /// Support for the FTS5 `prefix` option + /// The FTS5 `prefix` option. /// - /// See + /// Related SQLite documentation: public var prefixes: Set? - /// Support for the FTS5 `columnsize` option + /// The FTS5 `columnsize` option. /// - /// + /// Related SQLite documentation: public var columnSize: Int? - /// Support for the FTS5 `detail` option + /// The FTS5 `detail` option. /// - /// + /// Related SQLite documentation: public var detail: String? init(configuration: VirtualTableConfiguration) { @@ -377,11 +427,18 @@ public final class FTS5TableDefinition { /// Appends a table column. /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("content") - /// } + /// For example: + /// + /// ```swift + /// // CREATE VIRTUAL TABLE document USING fts5(content) + /// try db.create(virtualTable: "document", using: FTS5()) { t in + /// t.column("content") + /// } + /// ``` /// /// - parameter name: the column name. + /// - returns: A ``FTS5ColumnDefinition`` that allows you to refine the + /// column definition. @discardableResult public func column(_ name: String) -> FTS5ColumnDefinition { let column = FTS5ColumnDefinition(name: name) @@ -396,22 +453,50 @@ public final class FTS5TableDefinition { /// content in the external table. SQL triggers make sure that the /// full-text table is kept up to date with the external table. /// - /// See + /// SQLite automatically deletes those triggers when the content + /// (not full-text) table is dropped. + /// + /// However, those triggers remain after the full-text table has been + /// dropped. Unless they are dropped too, they will prevent future + /// insertion, updates, and deletions in the content table, and the creation + /// of a new full-text table. + /// + /// To drop those triggers, call the `Database` + /// ``Database/dropFTS5SynchronizationTriggers(forTable:)`` method: + /// + /// ```swift + /// // Create tables + /// try db.create(table: "book") { t in + /// ... + /// } + /// try db.create(virtualTable: "book_ft", using: FTS5()) { t in + /// t.synchronize(withTable: "book") + /// ... + /// } + /// + /// // Drop full-text table + /// try db.drop(table: "book_ft") + /// try db.dropFTS5SynchronizationTriggers(forTable: "book_ft") + /// ``` + /// + /// Related SQLite documentation: public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } } -/// The FTS5ColumnDefinition class lets you refine a column of an FTS5 -/// virtual table. +/// Describes a column in an ``FTS5`` virtual table. /// -/// You get instances of this class when you create an FTS5 table: +/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5`` +/// virtual table. For example: /// -/// try db.create(virtualTable: "document", using: FTS5()) { t in -/// t.column("content") // FTS5ColumnDefinition -/// } +/// ```swift +/// try db.create(virtualTable: "document", using: FTS5()) { t in +/// t.column("content") // FTS5ColumnDefinition +/// } +/// ``` /// -/// See +/// Related SQLite documentation: public final class FTS5ColumnDefinition { fileprivate let name: String fileprivate var isIndexed: Bool @@ -423,14 +508,18 @@ public final class FTS5ColumnDefinition { /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("a") - /// t.column("b").notIndexed() - /// } + /// For example: /// - /// See + /// ```swift + /// try db.create(virtualTable: "document", using: FTS5()) { t in + /// t.column("a") + /// t.column("b").notIndexed() + /// } + /// ``` /// - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func notIndexed() -> Self { self.isIndexed = false @@ -439,7 +528,7 @@ public final class FTS5ColumnDefinition { } extension Column { - /// The FTS5 rank column + /// The ``FTS5`` rank column. public static let rank = Column("rank") } diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 313d2e850..b6cf2fbd3 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,9 +1,13 @@ #if SQLITE_ENABLE_FTS5 - -/// The protocol for custom FTS5 tokenizers. +/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine. +/// +/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md) +/// for more information. public protocol FTS5CustomTokenizer: FTS5Tokenizer { - /// The name of the tokenizer; should uniquely identify your custom - /// tokenizer. + /// The name of the tokenizer. + /// + /// The name should uniquely identify the tokenizer: don't use a built-in + /// name such as `ascii`, `porter` or `unicode61`. static var name: String { get } /// Creates a custom tokenizer. @@ -27,7 +31,7 @@ extension FTS5CustomTokenizer { /// /// class MyTokenizer : FTS5CustomTokenizer { ... } /// - /// db.create(virtualTable: "book", using: FTS5()) { t in + /// try db.create(virtualTable: "book", using: FTS5()) { t in /// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"]) /// t.tokenizer = tokenizer /// } @@ -108,7 +112,7 @@ extension Database { } let constructor = Unmanaged.fromOpaque(constructorPointer).takeUnretainedValue() var arguments: [String] = [] - if let azArg = azArg { + if let azArg { for i in 0.. +/// +/// ## Topics +/// +/// ### Creating Raw FTS5 Patterns +/// +/// - ``Database/makeFTS5Pattern(rawPattern:forTable:)`` +/// +/// ### Creating FTS5 Patterns from User Input +/// +/// - ``init(matchingAllPrefixesIn:)`` +/// - ``init(matchingAllTokensIn:)`` +/// - ``init(matchingAnyTokenIn:)`` +/// - ``init(matchingPhrase:)`` +/// - ``init(matchingPrefixPhrase:)`` public struct FTS5Pattern { - /// The raw pattern string. Guaranteed to be a valid FTS5 pattern. + /// The raw pattern string. + /// + /// It is guaranteed to be a valid FTS5 pattern. public let rawPattern: String - /// Creates a pattern that matches any token found in the input string; - /// returns nil if no pattern could be built. + /// Creates a pattern that matches any token found in the input string. /// - /// FTS5Pattern(matchingAnyTokenIn: "") // nil - /// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS5 pattern + /// For example: + /// + /// ```swift + /// FTS5Pattern(matchingAnyTokenIn: "") // nil + /// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar + /// ``` + /// + /// - parameter string: The string to turn into an FTS5 pattern. public init?(matchingAnyTokenIn string: String) { guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else { return nil @@ -19,13 +42,18 @@ public struct FTS5Pattern { try? self.init(rawPattern: tokens.joined(separator: " OR ")) } - /// Creates a pattern that matches all tokens found in the input string; - /// returns nil if no pattern could be built. + /// Creates a pattern that matches all tokens found in the input string. /// - /// FTS5Pattern(matchingAllTokensIn: "") // nil - /// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS5 pattern + /// For example: + /// + /// ```swift + /// FTS5Pattern(matchingAllTokensIn: "") // nil + /// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar + /// ``` + /// + /// - parameter string: The string to turn into an FTS5 pattern. public init?(matchingAllTokensIn string: String) { guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else { return nil @@ -34,12 +62,18 @@ public struct FTS5Pattern { } /// Creates a pattern that matches all token prefixes found in the input - /// string; returns nil if no pattern could be built. + /// string. /// - /// FTS3Pattern(matchingAllTokensIn: "") // nil - /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo* bar* + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS3 pattern + /// For example: + /// + /// ```swift + /// FTS5Pattern(matchingAllTokensIn: "") // nil + /// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo* bar* + /// ``` + /// + /// - parameter string: The string to turn into an FTS5 pattern. public init?(matchingAllPrefixesIn string: String) { guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else { return nil @@ -47,13 +81,18 @@ public struct FTS5Pattern { try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " ")) } - /// Creates a pattern that matches a contiguous string; returns nil if no - /// pattern could be built. + /// Creates a pattern that matches a contiguous string. /// - /// FTS5Pattern(matchingPhrase: "") // nil - /// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar" + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS5 pattern + /// For example: + /// + /// ```swift + /// FTS5Pattern(matchingPhrase: "") // nil + /// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar" + /// ``` + /// + /// - parameter string: The string to turn into an FTS5 pattern. public init?(matchingPhrase string: String) { guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else { return nil @@ -61,14 +100,20 @@ public struct FTS5Pattern { try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } - /// Creates a pattern that matches the prefix of an indexed document; - /// returns nil if no pattern could be built. + /// Creates a pattern that matches the prefix of an indexed document. /// - /// FTS5Pattern(matchingPrefixPhrase: "") // nil - /// FTS5Pattern(matchingPrefixPhrase: "the word") // ^"the word" + /// The result is nil if no pattern could be built. /// - /// This pattern matches a prefix made of full tokens: "the bat" matches - /// "the bat is happy", but not "mind the bat", or "the batcave is dark". + /// The returned pattern matches a prefix made of full tokens: "the bat" + /// matches "the bat is happy", but not "mind the bat", or "the batcave + /// is dark". + /// + /// For example: + /// + /// ```swift + /// FTS5Pattern(matchingPrefixPhrase: "") // nil + /// FTS5Pattern(matchingPrefixPhrase: "the word") // ^"the word" + /// ``` /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPrefixPhrase string: String) { @@ -113,13 +158,26 @@ extension Database { // MARK: - FTS5 - /// Creates a pattern from a raw pattern string; throws DatabaseError on - /// invalid syntax. + /// Creates an FTS5 pattern from a raw pattern string. /// - /// The pattern syntax is documented at + /// For example: /// - /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK - /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] + /// ```swift + /// try dbQueue.read { db in + /// // OK + /// let pattern = try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") + /// + /// // Throws error: malformed MATCH expression: [AND] + /// let pattern = try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") + /// } + /// ``` + /// + /// - parameter rawPattern: A pattern that follows the + /// [Full-text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax). + /// - parameter table: The full-text table that the pattern is intended to + /// match against. + /// - returns: A valid FTS5 pattern. + /// - throws: A ``DatabaseError`` if the raw pattern is invalid. public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern { try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map(\.name)) } diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 74d34b6c9..be19d6f59 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -3,7 +3,7 @@ import Foundation /// A low-level SQLite function that lets FTS5Tokenizer notify tokens. /// -/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) +/// See ``FTS5Tokenizer/tokenize(context:tokenization:pText:nText:tokenCallback:)``. public typealias FTS5TokenCallback = @convention(c) ( _ context: UnsafeMutableRawPointer?, _ flags: CInt, @@ -15,7 +15,7 @@ public typealias FTS5TokenCallback = @convention(c) ( /// The reason why FTS5 is requesting tokenization. /// -/// See +/// See the `FTS5_TOKENIZE_*` constants in . public struct FTS5Tokenization: OptionSet { public let rawValue: CInt @@ -23,20 +23,42 @@ public struct FTS5Tokenization: OptionSet { self.rawValue = rawValue } - /// FTS5_TOKENIZE_QUERY + /// `FTS5_TOKENIZE_QUERY` public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY) - /// FTS5_TOKENIZE_PREFIX + /// `FTS5_TOKENIZE_PREFIX` public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX) - /// FTS5_TOKENIZE_DOCUMENT + /// `FTS5_TOKENIZE_DOCUMENT` public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT) - /// FTS5_TOKENIZE_AUX + /// `FTS5_TOKENIZE_AUX` public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX) } -/// The protocol for FTS5 tokenizers +/// A type that implements a tokenizer for the ``FTS5`` full-text engine. +/// +/// You can instantiate tokenizers, including +/// [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers), +/// with the ``Database/makeTokenizer(_:)`` method: +/// +/// ```swift +/// try dbQueue.read { db in +/// let unicode61 = try db.makeTokenizer(.unicode61()) // FTS5Tokenizer +/// } +/// ``` +/// +/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md) +/// for more information. +/// +/// ## Topics +/// +/// ### Tokenizing Text +/// +/// - ``tokenize(document:)`` +/// - ``tokenize(query:)`` +/// - ``tokenize(context:tokenization:pText:nText:tokenCallback:)`` +/// - ``FTS5TokenCallback`` public protocol FTS5Tokenizer: AnyObject { /// Tokenizes the text described by `pText` and `nText`, and /// notifies found tokens to the `tokenCallback` function. @@ -72,8 +94,10 @@ extension FTS5Tokenizer { /// /// For example: /// - /// let tokenizer = try db.makeTokenizer(.ascii()) - /// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)] + /// ```swift + /// let tokenizer = try db.makeTokenizer(.ascii()) + /// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)] + /// ``` /// /// See also `tokenize(query:)`. /// @@ -88,8 +112,10 @@ extension FTS5Tokenizer { /// /// For example: /// - /// let tokenizer = try db.makeTokenizer(.ascii()) - /// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)] + /// ```swift + /// let tokenizer = try db.makeTokenizer(.ascii()) + /// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)] + /// ``` /// /// See also `tokenize(document:)`. /// @@ -210,7 +236,7 @@ extension Database { throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate") } - if let tokenizerPointer = tokenizerPointer { + if let tokenizerPointer { self.tokenizerPointer = tokenizerPointer } else { throw DatabaseError(resultCode: code, message: "nil tokenizer") @@ -240,20 +266,27 @@ extension Database { /// Creates an FTS5 tokenizer, given its descriptor. /// - /// let unicode61 = try db.makeTokenizer(.unicode61()) + /// For example: + /// + /// ```swift + /// let unicode61 = try db.makeTokenizer(.unicode61()) + /// ``` + /// + /// You can use this method when you implement a custom wrapper tokenizer + /// with ``FTS5WrapperTokenizer``: + /// + /// ```swift + /// final class MyTokenizer : FTS5WrapperTokenizer { + /// var wrappedTokenizer: FTS5Tokenizer + /// + /// init(db: Database, arguments: [String]) throws { + /// wrappedTokenizer = try db.makeTokenizer(.unicode61()) + /// } + /// } + /// ``` /// /// It is a programmer error to use the tokenizer outside of a protected /// database queue, or after the database has been closed. - /// - /// Use this method when you implement a custom wrapper tokenizer: - /// - /// final class MyTokenizer : FTS5WrapperTokenizer { - /// var wrappedTokenizer: FTS5Tokenizer - /// - /// init(db: Database, arguments: [String]) throws { - /// wrappedTokenizer = try db.makeTokenizer(.unicode61()) - /// } - /// } public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer { let api = FTS5.api(self) diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 83d746f8a..b12a8acaa 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -1,61 +1,109 @@ #if SQLITE_ENABLE_FTS5 -/// An FTS5 tokenizer, suitable for FTS5 table definitions: +/// The descriptor for an ``FTS5`` tokenizer. /// -/// db.create(virtualTable: "book", using: FTS5()) { t in -/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor -/// } +/// For example: /// -/// See +/// ```swift +/// try db.create(virtualTable: "book", using: FTS5()) { t in +/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor +/// } +/// ``` +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating Tokenizer Descriptors +/// +/// - ``init(components:)`` +/// - ``ascii(separators:tokenCharacters:)`` +/// - ``porter(wrapping:)`` +/// - ``unicode61(diacritics:categories:separators:tokenCharacters:)`` +/// - ``FTS5/Diacritics`` +/// +/// ### Instantiating Tokenizers +/// +/// - ``Database/makeTokenizer(_:)`` public struct FTS5TokenizerDescriptor { - /// The tokenizer components + /// The tokenizer components. /// - /// // ["unicode61"] - /// FTS5TokenizerDescriptor.unicode61().components + /// For example: /// - /// // ["unicode61", "remove_diacritics", "0"] - /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components + /// ```swift + /// // ["unicode61"] + /// FTS5TokenizerDescriptor.unicode61().components + /// + /// // ["unicode61", "remove_diacritics", "0"] + /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components + /// ``` public let components: [String] - /// The tokenizer name + /// The tokenizer name. /// - /// // "unicode61" - /// FTS5TokenizerDescriptor.unicode61().name + /// For example: /// - /// // "unicode61" - /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name + /// ```swift + /// // "unicode61" + /// FTS5TokenizerDescriptor.unicode61().name + /// + /// // "unicode61" + /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name + /// ``` var name: String { components[0] } + /// The tokenizer arguments. + /// + /// For example: + /// + /// ```swift + /// // [] + /// FTS5TokenizerDescriptor.unicode61().components + /// + /// // ["remove_diacritics", "0"] + /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components + /// ``` var arguments: [String] { Array(components.suffix(from: 1)) } /// Creates an FTS5 tokenizer descriptor. /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"]) - /// t.tokenizer = tokenizer - /// } + /// For example: /// - /// - precondition: Components is not empty + /// ```swift + /// try db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = FTS5TokenizerDescriptor(components: [ + /// "porter", + /// "unicode61", + /// "remove_diacritics", + /// "0"]) + /// } + /// ``` + /// + /// - precondition: Components is not empty. public init(components: [String]) { GRDBPrecondition(!components.isEmpty, "FTS5TokenizerDescriptor requires at least one component") assert(!components.isEmpty) self.components = components } - /// The "ascii" tokenizer + /// The "ascii" tokenizer. /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .ascii() - /// } + /// For example: + /// + /// ```swift + /// try db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = .ascii() + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - separators: Unless empty (the default), SQLite will consider /// these characters as token separators. /// - tokenCharacters: Unless empty (the default), SQLite will /// consider these characters as token characters. - /// - /// See public static func ascii( separators: Set = [], tokenCharacters: Set = []) @@ -78,30 +126,39 @@ public struct FTS5TokenizerDescriptor { return FTS5TokenizerDescriptor(components: components) } - /// The "porter" tokenizer + /// The "porter" tokenizer. /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .porter() - /// } + /// For example: /// - /// - parameters: - /// - base: An eventual wrapping tokenizer which replaces the - // default unicode61() base tokenizer. + /// ```swift + /// try db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = .porter() + /// } + /// ``` /// - /// See + /// Related SQLite documentation: + /// + /// - parameter base: An eventual wrapping tokenizer which replaces the + /// default unicode61() base tokenizer. public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor { - if let base = base { + if let base { return FTS5TokenizerDescriptor(components: ["porter"] + base.components) } else { return FTS5TokenizerDescriptor(components: ["porter"]) } } - /// An "unicode61" tokenizer + /// The "unicode61" tokenizer. /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .unicode61() - /// } + /// For example: + /// + /// ```swift + /// try db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = .unicode61() + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - diacritics: By default SQLite will strip diacritics from @@ -112,8 +169,6 @@ public struct FTS5TokenizerDescriptor { /// these characters as token separators. /// - tokenCharacters: Unless empty (the default), SQLite will /// consider these characters as token characters. - /// - /// See public static func unicode61( diacritics: FTS5.Diacritics = .removeLegacy, categories: String = "", diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index 4f804dc5e..7be012bf2 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -3,7 +3,7 @@ import Foundation /// Flags that tell SQLite how to register a token. /// -/// See the `FTS5_TOKEN_*` flags in . +/// See the `FTS5_TOKEN_*` constants in . public struct FTS5TokenFlags: OptionSet { public let rawValue: CInt @@ -11,7 +11,7 @@ public struct FTS5TokenFlags: OptionSet { self.rawValue = rawValue } - /// FTS5_TOKEN_COLOCATED + /// `FTS5_TOKEN_COLOCATED` public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED) } @@ -20,34 +20,18 @@ public struct FTS5TokenFlags: OptionSet { /// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:) public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void -/// The protocol for custom FTS5 tokenizers that wrap another tokenizer. +/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine +/// by wrapping another tokenizer. /// -/// Types that adopt FTS5WrapperTokenizer don't have to implement the -/// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:). +/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md) +/// for more information. /// -/// Instead, they process regular Swift strings. +/// ## Topics /// -/// Here is the implementation for a trivial tokenizer that wraps the -/// built-in ascii tokenizer without any custom processing: +/// ### Tokenizing Text /// -/// class TrivialAsciiTokenizer : FTS5WrapperTokenizer { -/// static let name = "trivial" -/// let wrappedTokenizer: FTS5Tokenizer -/// -/// init(db: Database, arguments: [String]) throws { -/// wrappedTokenizer = try db.makeTokenizer(.ascii()) -/// } -/// -/// func accept( -/// token: String, -/// flags: FTS5TokenFlags, -/// for tokenization: FTS5Tokenization, -/// tokenCallback: FTS5WrapperTokenCallback) -/// throws -/// { -/// try tokenCallback(token, flags) -/// } -/// } +/// - ``accept(token:flags:for:tokenCallback:)`` +/// - ``FTS5WrapperTokenCallback`` public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// The wrapped tokenizer var wrappedTokenizer: any FTS5Tokenizer { get } @@ -57,16 +41,17 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// /// For example: /// - /// func accept( - /// token: String, - /// flags: FTS5TokenFlags, - /// for tokenization: FTS5Tokenization, - /// tokenCallback: FTS5WrapperTokenCallback) - /// throws - /// { - /// // pass through: - /// try tokenCallback(token, flags) - /// } + /// ```swift + /// func accept( + /// token: String, + /// flags: FTS5TokenFlags, + /// for tokenization: FTS5Tokenization, + /// tokenCallback: FTS5WrapperTokenCallback + /// ) throws { + /// // pass through: + /// try tokenCallback(token, flags) + /// } + /// ``` /// /// When implementing the accept method, there are a two rules /// to observe: @@ -74,8 +59,8 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// 1. Errors thrown by the tokenCallback function must not be caught. /// /// 2. The input `flags` should be given unmodified to the tokenCallback - /// function, unless you union it with the .colocated flag when the - /// tokenizer produces synonyms (see + /// function, unless you union it with the ``FTS5TokenFlags/colocated`` flag + /// when the tokenizer produces synonyms (see /// ). /// /// - parameters: @@ -99,7 +84,6 @@ private struct FTS5WrapperContext { } extension FTS5WrapperTokenizer { - /// Default implementation public func tokenize( context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 8ff802b97..5ae7ad85c 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -119,7 +119,7 @@ extension PersistableRecord { public func performSave(_ db: Database) throws { preconditionFailure() } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") public func selectID() -> QueryInterfaceRequest { preconditionFailure() } @@ -144,13 +144,13 @@ extension SelectionRequest { @available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") public func selectID() -> QueryInterfaceRequest { preconditionFailure() } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") public static func selectID() -> QueryInterfaceRequest { preconditionFailure() } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 974fa753b..f13e9b12b 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -490,7 +490,7 @@ extension DatabaseMigrator { /// - parameter writer: A DatabaseWriter. /// where migrations should apply. /// - parameter scheduler: A Combine Scheduler. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func migratePublisher( _ writer: some DatabaseWriter, receiveOn scheduler: some Scheduler = DispatchQueue.main) @@ -508,7 +508,7 @@ extension DatabaseMigrator { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that migrates a database. /// diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index ea04513d6..205414e8c 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -77,7 +77,7 @@ public struct BelongsToAssociation { originIsLeft: true) let associationKey: SQLAssociationKey - if let key = key { + if let key { associationKey = .fixedSingular(key) } else { associationKey = .inflected(destinationTable) diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index 2b3973005..cce49cdc2 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -77,7 +77,7 @@ public struct HasManyAssociation { originIsLeft: false) let associationKey: SQLAssociationKey - if let key = key { + if let key { associationKey = .fixedPlural(key) } else { associationKey = .inflected(destinationTable) diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 36f9e7708..e0ba88751 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -80,7 +80,7 @@ public struct HasOneAssociation { originIsLeft: false) let associationKey: SQLAssociationKey - if let key = key { + if let key { associationKey = .fixedSingular(key) } else { associationKey = .inflected(destinationTable) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 813677ebe..17d192fb2 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -334,7 +334,7 @@ struct SQLCTE { /// The number of columns in the common table expression. func columnCount(_ db: Database) throws -> Int { - if let columns = columns { + if let columns { // No need to hit the database return columns.count } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index dc9924dc9..25fd989e1 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -636,7 +636,7 @@ extension QueryInterfaceRequest { /// - returns: A prepared statement. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` is not empty. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func deleteAndFetchStatement( _ db: Database, selection: [any SQLSelectable]) @@ -668,7 +668,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: A ``RecordCursor`` over deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func deleteAndFetchCursor(_ db: Database) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord @@ -696,7 +696,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: An array of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func deleteAndFetchAll(_ db: Database) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord @@ -723,7 +723,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: A set of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func deleteAndFetchSet(_ db: Database) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable @@ -995,7 +995,7 @@ extension QueryInterfaceRequest { /// - returns: A prepared statement. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` and `assignments` are not empty. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchStatement( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -1043,7 +1043,7 @@ extension QueryInterfaceRequest { /// - returns: A cursor over the updated records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchCursor( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -1081,7 +1081,7 @@ extension QueryInterfaceRequest { /// - returns: An array of updated records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchAll( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -1114,7 +1114,7 @@ extension QueryInterfaceRequest { /// - returns: A set of updated records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchSet( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 553511e19..113f7ef31 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -316,7 +316,8 @@ extension FilteredRequest { /// - ``filter(key:)-2te6v`` /// - ``filter(keys:)-6ggt1`` /// - ``filter(keys:)-8fbn9`` -/// - ``matching(_:)`` +/// - ``matching(_:)-3s3zr`` +/// - ``matching(_:)-7c1e8`` /// /// ### The GROUP BY and HAVING Clauses /// @@ -570,7 +571,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRequest where Self: FilteredRequest, Self: TypedRequest, @@ -1337,7 +1338,8 @@ extension JoinableRequest where Self: SelectionRequest { /// - ``FilteredRequest/filter(literal:)`` /// - ``FilteredRequest/filter(sql:arguments:)`` /// - ``FilteredRequest/filterWhenConnected(_:)`` -/// - ``TableRequest/matching(_:)`` +/// - ``TableRequest/matching(_:)-3s3zr`` +/// - ``TableRequest/matching(_:)-7c1e8`` /// - ``FilteredRequest/none()`` /// /// ### The GROUP BY and HAVING Clauses diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 331789d45..c540eca4d 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -9,7 +9,8 @@ /// ### Deriving SQL Expressions /// /// - ``detached`` -/// - ``match(_:)`` +/// - ``match(_:)-727nk`` +/// - ``match(_:)-1vvo8`` /// /// ### Creating Column Assignments /// diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index e9de5892d..b3cba98b9 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -979,7 +979,7 @@ extension SQLExpression { \(op.sql) \ \(rhs.sql(context, wrappedInParenthesis: true)) """ - if let escape = escape { + if let escape { resultSQL += try " ESCAPE \(escape.sql(context, wrappedInParenthesis: true))" } if wrappedInParenthesis { @@ -1893,13 +1893,13 @@ extension SQLSpecificExpressible { } #elseif !GRDBCIPHER /// An ordering term for ascending order (nulls last). - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ public var ascNullsLast: SQLOrdering { .ascNullsLast(sqlExpression) } /// An ordering term for descending order (nulls first). - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ public var descNullsFirst: SQLOrdering { .descNullsFirst(sqlExpression) } diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 75d4af2cd..3dbe56009 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -22,7 +22,7 @@ struct SQLForeignKeyRequest { /// The (origin, destination) column pairs that join a left table to a right table. func fetchForeignKeyMapping(_ db: Database) throws -> ForeignKeyMapping { - if let originColumns = originColumns, let destinationColumns = destinationColumns { + if let originColumns, let destinationColumns { // Total information: no need to query the database schema. GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match") let mapping = zip(originColumns, destinationColumns).map { @@ -36,14 +36,14 @@ struct SQLForeignKeyRequest { if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() { return false } - if let originColumns = originColumns { + if let originColumns { let originColumns = Set(originColumns.lazy.map { $0.lowercased() }) let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() }) if originColumns != foreignKeyColumns { return false } } - if let destinationColumns = destinationColumns { + if let destinationColumns { // TODO: test let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() }) let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() }) @@ -66,7 +66,7 @@ struct SQLForeignKeyRequest { } // No matching foreign key found: use the destination primary key - if let originColumns = originColumns { + if let originColumns { let destinationColumns = try db.primaryKey(destinationTable).columns if originColumns.count == destinationColumns.count { let mapping = zip(originColumns, destinationColumns).map { diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index bf7759f99..6277924f0 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -126,7 +126,7 @@ extension SQLSpecificExpressible { /// The `IS` SQL operator. public static func === (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { - if let lhs = lhs { + if let lhs { return .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } else { return .compare(.is, rhs.sqlExpression, .null) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 4bd764e29..c94c43ed6 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -635,7 +635,7 @@ struct SQLLimit { let offset: Int? var sql: String { - if let offset = offset { + if let offset { return "\(limit) OFFSET \(offset)" } else { return "\(limit)" diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index d6ec258be..3b5486a7f 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -723,7 +723,7 @@ extension Table { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { /// Returns a request filtered by primary key. /// @@ -1346,7 +1346,7 @@ extension Table { { let association = HasManyThroughAssociation(through: pivot, using: target) - if let key = key { + if let key { return association.forKey(key) } else { return association @@ -1378,7 +1378,7 @@ extension Table { { let association = HasOneThroughAssociation(through: pivot, using: target) - if let key = key { + if let key { return association.forKey(key) } else { return association @@ -1546,7 +1546,7 @@ extension Table { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible @@ -1688,7 +1688,7 @@ extension Table { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 80131277b..7f7724ccd 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -324,7 +324,7 @@ public class TableAlias { switch impl { case let .undefined(userName): - if let userName = userName { + if let userName { // rename assert(base.userName == nil || base.userName == userName) base.setUserName(userName) @@ -332,7 +332,7 @@ public class TableAlias { self.impl = .proxy(base) case let .table(tableName: tableName, userName: userName): assert(tableName == base.tableName) - if let userName = userName { + if let userName { // rename assert(base.userName == nil || base.userName == userName) base.setUserName(userName) @@ -358,7 +358,7 @@ public class TableAlias { // can't merge return nil } - if let userName = userName, let otherUserName = otherUserName, userName != otherUserName { + if let userName, let otherUserName, userName != otherUserName { // can't merge return nil } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 9d393571b..5c39d13e3 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -47,7 +47,7 @@ struct SQLQueryGenerator: Refinable { } let filter = try relation.filterPromise?.resolve(context.db) - if let filter = filter { + if let filter { sql += " WHERE " sql += try filter.sql(context) } @@ -83,7 +83,7 @@ struct SQLQueryGenerator: Refinable { limit = SQLLimit(limit: 1, offset: limit?.offset) } - if let limit = limit { + if let limit { sql += " LIMIT " sql += limit.sql } diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 0cfca9a21..6f2bbb419 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -19,6 +19,16 @@ extension SQLInterpolation { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } + /// Appends the table name. + /// + /// // SELECT * FROM player + /// let playerTable = Table("player") + /// let request: SQLRequest = "SELECT * FROM \(playerTable)" + @_disfavoredOverload + public mutating func appendInterpolation(_ table: Table) { + appendLiteral(table.tableName.quotedDatabaseIdentifier) + } + /// Appends the table name of the record. /// /// // INSERT INTO player ... @@ -74,7 +84,7 @@ extension SQLInterpolation { /// """ @_disfavoredOverload public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) { - if let selection = selection { + if let selection { elements.append(.selection(selection.sqlSelection)) } else { appendLiteral("NULL") @@ -127,7 +137,7 @@ extension SQLInterpolation { /// """ @_disfavoredOverload public mutating func appendInterpolation(_ expressible: (any SQLExpressible)?) { - if let expressible = expressible { + if let expressible { elements.append(.expression(expressible.sqlExpression)) } else { appendLiteral("NULL") diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 9beba1c2c..51fae27e6 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -160,22 +160,29 @@ extension Database { /// ```swift /// // a INTEGER NOT NULL, /// // b TEXT NOT NULL, - /// // PRIMARY KEY (a, b), + /// // PRIMARY KEY (a, b) /// t.primaryKey { /// t.column("a", .integer) /// t.column("b", .text) /// } /// + /// // a INTEGER NOT NULL, + /// // b TEXT NOT NULL, + /// // PRIMARY KEY (a, b) + /// t.column("a", .integer).notNull() + /// t.column("b", .text).notNull() + /// t.primaryKey(["a", "b"]) + /// /// // a INTEGER, /// // b TEXT, - /// // UNIQUE (a, b) ON CONFLICT REPLACE, + /// // UNIQUE (a, b) ON CONFLICT REPLACE /// t.column("a", .integer) /// t.column("b", .text) /// t.uniqueKey(["a", "b"], onConflict: .replace) /// /// // a INTEGER, /// // b TEXT, - /// // FOREIGN KEY (a, b) REFERENCES parents(c, d), + /// // FOREIGN KEY (a, b) REFERENCES parents(c, d) /// t.column("a", .integer) /// t.column("b", .text) /// t.foreignKey(["a", "b"], references: "parents") @@ -469,8 +476,8 @@ public struct TableOptions: OptionSet { /// A `TableDefinition` lets you define the components of a database table. /// -/// You don't create instances of this class. Instead, you use the `Database` -/// ``Database/create(table:options:body:)`` method: +/// See the documentation of the `Database` +/// ``Database/create(table:options:body:)`` method for usage information: /// /// ```swift /// try db.create(table: "player") { t in // t is TableDefinition @@ -493,6 +500,7 @@ public struct TableOptions: OptionSet { /// - ``autoIncrementedPrimaryKey(_:onConflict:)`` /// - ``primaryKey(_:_:onConflict:)`` /// - ``primaryKey(onConflict:body:)`` +/// - ``primaryKey(_:onConflict:)`` /// /// ### Define a Foreign Key /// @@ -508,13 +516,6 @@ public struct TableOptions: OptionSet { /// - ``check(sql:)`` /// - ``constraint(literal:)`` /// - ``constraint(sql:)`` -/// -/// ### Sunsetted Methods -/// -/// Those are legacy interfaces that are preserved for backwards compatibility. -/// Their use is not recommended. -/// -/// - ``primaryKey(_:onConflict:)`` public final class TableDefinition { struct KeyConstraint { var columns: [String] @@ -567,7 +568,7 @@ public final class TableDefinition { self.options = options } - /// Defines the auto-incremented primary key. + /// Appends an auto-incremented primary key column. /// /// For example: /// @@ -601,7 +602,7 @@ public final class TableDefinition { column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) } - /// Defines the primary key on a single column. + /// Appends a primary key column. /// /// For example: /// @@ -636,7 +637,7 @@ public final class TableDefinition { } } - /// Defines the primary key on multiple columns. + /// Defines the primary key on wrapped columns. /// /// For example: /// @@ -656,7 +657,7 @@ public final class TableDefinition { /// } /// ``` /// - /// A NOT NULL constraint is always added to the primary key columns. + /// A NOT NULL constraint is always added to the wrapped primary key columns. public func primaryKey( onConflict conflictResolution: Database.ConflictResolution? = nil, body: () throws -> Void) @@ -744,7 +745,7 @@ public final class TableDefinition { columns.append(.literal(literal)) } - /// Defines the primary key. + /// Adds a primary key constraint. /// /// For example: /// @@ -766,10 +767,6 @@ public final class TableDefinition { /// See /// for more information. /// - /// - warning: This is a legacy interface that is preserved for backwards - /// compatibility. Use of this interface is not recommended: prefer - /// ``TableDefinition/primaryKey(onConflict:body:)`` instead. - /// /// - parameter columns: The primary key columns. /// - parameter conflictResolution: An optional conflict resolution /// (see ). @@ -1109,7 +1106,7 @@ public final class TableDefinition { tableOptions.append("STRICT") } #else - if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { + if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+ if options.contains(.strict) { tableOptions.append("STRICT") } @@ -1267,7 +1264,7 @@ public final class TableAlteration { /// /// - parameter name: the old name of the column. /// - parameter newName: the new name of the column. - @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) + @available(iOS 13, tvOS 13, watchOS 6, *) // SQLite 3.25+ public func rename(column name: String, to newName: String) { _rename(column: name, to: newName) } @@ -1285,7 +1282,7 @@ public final class TableAlteration { /// Related SQLite documentation: /// /// - Parameter name: the name of the column to drop. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func drop(column name: String) { _drop(column: name) } @@ -1810,7 +1807,7 @@ public final class ColumnDefinition { /// - qualification: The generated column's qualification, which /// defaults to ``GeneratedColumnQualification/virtual``. /// - returns: `self` so that you can further refine the column definition. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ (3.31 actually) + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually) @discardableResult public func generatedAs( sql: String, @@ -1850,7 +1847,7 @@ public final class ColumnDefinition { /// - qualification: The generated column's qualification, which /// defaults to ``GeneratedColumnQualification/virtual``. /// - returns: `self` so that you can further refine the column definition. - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ (3.31 actually) + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually) @discardableResult public func generatedAs( _ expression: some SQLExpressible, @@ -1909,13 +1906,13 @@ public final class ColumnDefinition { fileprivate func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) - if let type = type { + if let type { chunks.append(type.rawValue) } if let (conflictResolution, autoincrement) = primaryKey { chunks.append("PRIMARY KEY") - if let conflictResolution = conflictResolution { + if let conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) } @@ -1927,7 +1924,7 @@ public final class ColumnDefinition { switch notNullConflictResolution { case .none: break - case .abort?: + case .abort: chunks.append("NOT NULL") case let conflictResolution?: chunks.append("NOT NULL ON CONFLICT") @@ -1953,11 +1950,11 @@ public final class ColumnDefinition { try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))") } - if let defaultExpression = defaultExpression { + if let defaultExpression { try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))") } - if let collationName = collationName { + if let collationName { chunks.append("COLLATE") chunks.append(collationName) } @@ -2064,7 +2061,7 @@ private struct IndexDefinition { \(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ ) """) - if let condition = condition { + if let condition { try chunks.append("WHERE \(condition.quotedSQL(db))") } return chunks.joined(separator: " ") diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 9aba55308..07bdf7bdd 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -130,7 +130,7 @@ extension Database { // Define virtual table let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists) let definition = module.makeTableDefinition(configuration: configuration) - if let body = body { + if let body { try body(definition) } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 766d06ffa..e86a54814 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -443,7 +443,7 @@ extension TableRecord { { let association = HasManyThroughAssociation(through: pivot, using: target) - if let key = key { + if let key { return association.forKey(key) } else { return association @@ -529,7 +529,7 @@ extension TableRecord { { let association = HasOneThroughAssociation(through: pivot, using: target) - if let key = key { + if let key { return association.forKey(key) } else { return association diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 00ec06396..8044373f3 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -605,7 +605,7 @@ extension TableRecord { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns a request filtered by primary key. /// diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 2d6e5dba4..0782dc6b3 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -94,7 +94,7 @@ private class RecordEncoder: Encoder { // swiftlint:enable comma func encodeIfPresent(_ value: T?, forKey key: Key) throws where T: Encodable { - if let value = value { + if let value { try recordEncoder.encode(value, forKey: key) } else { recordEncoder.persist(nil, forKey: key) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index d74a49c05..c561ccbdf 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -98,7 +98,7 @@ private struct _RowDecoder: Decoder { func contains(_ key: Key) -> Bool { let row = decoder.row - if let _columnForKey = _columnForKey { + if let _columnForKey { if let column = _columnForKey[key.stringValue] { assert(row.hasColumn(column)) return true @@ -299,7 +299,7 @@ private struct _RowDecoder: Decoder { // "book", which is not the name of a column, and not the name of a // scope) has to be decoded right from the base row. But this can // happen only once. - if let decodedRootKey = decodedRootKey { + if let decodedRootKey { let keys = [decodedRootKey.stringValue, key.stringValue].sorted() throw DecodingError.keyNotFound(key, DecodingError.Context( codingPath: codingPath, @@ -369,7 +369,7 @@ private struct _RowDecoder: Decoder { } catch is JSONRequiredError { // Decode from JSON return try row.withUnsafeData(atIndex: index) { data in - guard let data = data else { + guard let data else { throw DecodingError.valueNotFound(Data.self, DecodingError.Context( codingPath: codingPath + [key], debugDescription: "Missing Data")) diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index bce826b5b..97178adeb 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -217,7 +217,7 @@ extension FetchableRecord where Self: TableRecord { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseValueConvertible { // MARK: Fetching by Single-Column Primary Key @@ -359,7 +359,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: DatabaseValueConvertible { /// Returns a set of records identified by their primary keys. /// diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index 83e61018e..6097d12f8 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -285,7 +285,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) @@ -351,7 +351,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -412,7 +412,7 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index 1de6bde59..23afa5984 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -233,7 +233,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) @@ -261,7 +261,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -306,7 +306,7 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index 36e9c5380..472a3cc32 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -532,7 +532,7 @@ extension MutablePersistableRecord { /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) @@ -557,7 +557,7 @@ extension MutablePersistableRecord { /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -586,7 +586,7 @@ extension MutablePersistableRecord { /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -616,7 +616,7 @@ extension MutablePersistableRecord { /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -662,7 +662,7 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -724,7 +724,7 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -768,7 +768,7 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -804,7 +804,7 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -850,7 +850,7 @@ extension MutablePersistableRecord { } #else @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ func updateChangesAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution?, diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index 38f4e41eb..9cca9cd20 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -207,7 +207,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func upsert(_ db: Database) throws { try willSave(db) @@ -302,7 +302,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], @@ -330,7 +330,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func upsertAndFetch( _ db: Database, as returnedType: T.Type, @@ -442,7 +442,7 @@ extension MutablePersistableRecord { // to false in its `aroundInsert` callback. var persistenceContainer = dao.persistenceContainer let rowIDColumn = dao.primaryKey.rowIDColumn - if let rowIDColumn = rowIDColumn { + if let rowIDColumn { persistenceContainer[caseInsensitive: rowIDColumn] = rowid } diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift index 112029d51..232c217d9 100644 --- a/GRDB/Record/PersistableRecord+Insert.swift +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -253,7 +253,7 @@ extension PersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -314,7 +314,7 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index 31e20e73f..4f713cdfb 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -144,7 +144,7 @@ extension PersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -189,7 +189,7 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift index df5df0d3c..af1a68807 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -207,7 +207,7 @@ extension PersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func upsert(_ db: Database) throws { try willSave(db) @@ -302,7 +302,7 @@ extension PersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], @@ -330,7 +330,7 @@ extension PersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func upsertAndFetch( _ db: Database, as returnedType: T.Type, diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 86902314f..02097265c 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -203,7 +203,7 @@ open class Record { // Loop until we find a change, or exhaust columns: while let (column, newValue) = newValueIterator.next() { let newDbValue = newValue?.databaseValue ?? .null - guard let oldRow = oldRow, let oldDbValue: DatabaseValue = oldRow[column] else { + guard let oldRow, let oldDbValue: DatabaseValue = oldRow[column] else { return (column, nil) } if newDbValue != oldDbValue { diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 86d0443c9..27d3e914e 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -80,7 +80,8 @@ import Foundation /// - ``joining(optional:)`` /// - ``joining(required:)`` /// - ``limit(_:offset:)`` -/// - ``matching(_:)`` +/// - ``matching(_:)-22m4o`` +/// - ``matching(_:)-1t8ph`` /// - ``none()`` /// - ``order(_:)-9rc11`` /// - ``order(_:)-2033k`` @@ -309,7 +310,7 @@ extension TableRecord { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns whether a record exists for this primary key. /// @@ -445,7 +446,7 @@ extension TableRecord { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Deletes records identified by their primary keys, and returns the number /// of deleted records. @@ -700,20 +701,20 @@ extension TableRecord { /// Returns an error for a record that does not exist in the database. public static func recordNotFound(key: [String: (any DatabaseValueConvertible)?]) -> RecordError { - return RecordError.recordNotFound( + RecordError.recordNotFound( databaseTableName: databaseTableName, key: key.mapValues { $0?.databaseValue ?? .null }) } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns an error for a record that does not exist in the database. /// /// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or /// any error that prevented the `RecordError` from being constructed. public static func recordNotFound(_ db: Database, id: Self.ID) -> any Error { - return recordNotFound(db, key: id) + recordNotFound(db, key: id) } } diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index 6a5e71d3f..6826014a4 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -14,7 +14,7 @@ import Foundation /// Both two extra scheduling guarantees are used by GRDB in order to be /// able to spawn concurrent database reads right from the database writer /// queue, and fulfill GRDB preconditions. -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) struct OnDemandFuture: Publisher { typealias Promise = (Result) -> Void typealias Output = Output @@ -33,7 +33,7 @@ struct OnDemandFuture: Publisher { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private class OnDemandFutureSubscription: Subscription { typealias Promise = (Result) -> Void diff --git a/GRDB/Utils/ReceiveValuesOn.swift b/GRDB/Utils/ReceiveValuesOn.swift index 9bd6cc2b8..abc688f78 100644 --- a/GRDB/Utils/ReceiveValuesOn.swift +++ b/GRDB/Utils/ReceiveValuesOn.swift @@ -11,7 +11,7 @@ import Foundation /// This scheduling guarantee is used by GRDB in order to be able /// to make promises on the scheduling of database values without surprising /// the users as in . -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) struct ReceiveValuesOn: Publisher { typealias Output = Upstream.Output typealias Failure = Upstream.Failure @@ -30,7 +30,7 @@ struct ReceiveValuesOn: Publisher { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private class ReceiveValuesOnSubscription: Subscription, Subscriber where Upstream: Publisher, @@ -211,7 +211,7 @@ where } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher { /// Specifies the scheduler on which to receive values from the publisher /// diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 49ef225c5..b186d43ae 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -31,9 +31,9 @@ func GRDBPrecondition( file: StaticString = #file, line: UInt = #line) { - /// Custom precondition function which aims at solving - /// and - /// + // Custom precondition function which aims at solving + // and + // if !condition() { fatalError(message(), file: file, line: line) } @@ -112,7 +112,7 @@ func throwingFirstError(execute: () throws -> T, finally: () throws -> Void) firstError = error } } - if let firstError = firstError { + if let firstError { throw firstError } return result! diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index b4e94fc3a..9508ee4a8 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -438,7 +438,7 @@ extension ValueConcurrentObserver { let value = try self.reducer._value(fetchedValue) // Notify - if let value = value { + if let value { self.scheduler.schedule { let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } guard let onChange else { return /* Cancelled */ } @@ -566,7 +566,7 @@ extension ValueConcurrentObserver: TransactionObserver { let value = try self.reducer._value(fetchedValue) // Notify value - if let value = value { + if let value { self.scheduler.schedule { let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } guard let onChange else { return /* Cancelled */ } diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index 404e73de5..c81ac1bcc 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -18,7 +18,11 @@ import Foundation /// reducing stage. /// /// **Notify** is calling user callbacks, in case of database change or error. -final class ValueWriteOnlyObserver { +final class ValueWriteOnlyObserver< + Writer: DatabaseWriter, + Reducer: ValueReducer, + Scheduler: ValueObservationScheduler> +{ // MARK: - Configuration // // Configuration is not mutable. @@ -403,7 +407,7 @@ extension ValueWriteOnlyObserver: TransactionObserver { let value = try self.reducer._value(fetchedValue) // Notify value - if let value = value { + if let value { self.scheduler.schedule { let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } guard let onChange else { return /* Cancelled */ } diff --git a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift index df1eb0ab2..6d2e64e53 100644 --- a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift @@ -81,7 +81,7 @@ extension ValueReducers { guard let value = try base._value(fetched) else { return nil } - if let previousValue = previousValue, predicate(previousValue, value) { + if let previousValue, predicate(previousValue, value) { // Don't notify consecutive identical values return nil } diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 946a6c90f..123c44c28 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -291,7 +291,7 @@ public final class SharedValueObservation { /// print("fresh players: \(players)") /// } /// ``` - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func publisher() -> DatabasePublishers.Value { DatabasePublishers.Value { onError, onChange in self.start(onError: onError, onChange: onChange) @@ -368,7 +368,7 @@ extension SharedValueObservation { /// print("Fresh players: \(players)") /// } /// ``` - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func values(bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation { diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index d3f1bb2cb..9ad5e29a4 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -634,7 +634,7 @@ extension ValueObservation { /// - parameter reader: A DatabaseReader. /// - parameter scheduler: A ValueObservationScheduler. By default, fresh /// values are dispatched asynchronously on the main dispatch queue. - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func values( in reader: some DatabaseReader, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), @@ -669,7 +669,7 @@ extension ValueObservation { /// /// You build an `AsyncValueObservation` from ``ValueObservation`` or /// ``SharedValueObservation``. -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public struct AsyncValueObservation: AsyncSequence { public typealias BufferingPolicy = AsyncThrowingStream.Continuation.BufferingPolicy public typealias AsyncIterator = Iterator @@ -704,7 +704,7 @@ public struct AsyncValueObservation: AsyncSequence { } let iterator = stream.makeAsyncIterator() - if let cancellable = cancellable { + if let cancellable { return Iterator( iterator: iterator, cancellable: cancellable) @@ -771,7 +771,7 @@ extension ValueObservation { /// - parameter scheduler: A ValueObservationScheduler. By default, fresh /// values are dispatched asynchronously on the main dispatch queue. /// - returns: A Combine publisher - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func publisher( in reader: some DatabaseReader, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main)) @@ -788,7 +788,7 @@ extension ValueObservation { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that publishes the values of a ``ValueObservation``. /// diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3b15a8f99..3d8f50e2f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -240,6 +240,8 @@ 56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AE6428222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */; }; 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; + 56AFEF3229969F7E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */; }; + 56AFEF3A2996B9EE00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */; }; 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; }; @@ -722,6 +724,8 @@ 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; + 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = ""; }; + 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = ""; }; 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; @@ -1364,6 +1368,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */, 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, + 56AFEF382996B9EE00CA1E51 /* TransactionDateTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, ); name = Core; @@ -1463,6 +1468,7 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, + 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56564F3828637C9900A19E9F /* WALSnapshot.swift */, 5605F1471C672E4000235C62 /* Support */, @@ -1923,6 +1929,7 @@ 5656A8852295BD56001FF3FF /* SQLOrdering.swift in Sources */, F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */, F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, + 56AFEF3229969F7E00CA1E51 /* TransactionClock.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, @@ -2190,6 +2197,7 @@ 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 56AFEF3A2996B9EE00CA1E51 /* TransactionDateTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, 563F4CB4242F7F140052E96C /* ValueObservationTests.swift in Sources */, 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, diff --git a/Package.swift b/Package.swift index 521f5799f..3372d1313 100644 --- a/Package.swift +++ b/Package.swift @@ -4,13 +4,14 @@ import Foundation import PackageDescription -// Don't rely on those environment variables. They are ONLY testing conveniences: -// $ SQLITE_ENABLE_FTS5=1 SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM -var swiftSettings: [SwiftSetting] = [] +var swiftSettings: [SwiftSetting] = [ + .define("SQLITE_ENABLE_FTS5"), +] var cSettings: [CSetting] = [] -if ProcessInfo.processInfo.environment["SQLITE_ENABLE_FTS5"] == "1" { - swiftSettings.append(.define("SQLITE_ENABLE_FTS5")) -} +var dependencies: [PackageDescription.Package.Dependency] = [] + +// Don't rely on those environment variables. They are ONLY testing conveniences: +// $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { swiftSettings.append(.define("SQLITE_ENABLE_PREUPDATE_HOOK")) cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK")) @@ -22,7 +23,6 @@ if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { // for more information. // // SPI_BUILDER also enables the `make docs-localhost` command. -var dependencies: [PackageDescription.Package.Dependency] = [] if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" { dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0")) } diff --git a/README.md b/README.md index 7707bf83b..3f42125ca 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: January 15, 2023 β€’ [version 6.6.1](https://github.com/groue/GRDB.swift/tree/v6.6.1) β€’ [CHANGELOG](CHANGELOG.md) β€’ [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: February 19, 2023 β€’ [version 6.7.0](https://github.com/groue/GRDB.swift/tree/v6.7.0) β€’ [CHANGELOG](CHANGELOG.md) β€’ [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **v6.6.1** | +| **Swift 5.7+** | **v6.7.0** | | Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -2080,13 +2080,14 @@ Extending structs with record protocols is more "swifty". Subclassing the Record - [TableRecord Protocol](#tablerecord-protocol) - [PersistableRecord Protocol](#persistablerecord-protocol) - [Persistence Methods] - - [Persistence Methods and the `RETURNING` clause](#persistence-methods-and-the-returning-clause) + - [Persistence Methods and the `RETURNING` clause] - [Persistence Callbacks] - [Identifiable Records] - [Codable Records] - [Record Class](#record-class) - [Record Comparison] - [Record Customization Options] +- [Record Timestamps and Transaction Date] **Records in a Glance** @@ -5684,11 +5685,11 @@ For even better control over the lifetime of the passphrase in memory, use a Dat // RECOMMENDED: only load the passphrase when it is needed and reset its content immediately after use var config = Configuration() config.prepareDatabase { db in - let passphrase = try getPassphraseData() // Data + var passphraseData = try getPassphraseData() // Data defer { - passphrase.resetBytes(in: 0../dev/null; then - swiftlint --config "${SRCROOT}/Scripts/swiftlint.yml" + # Ignore swiftlint error, because GRBD has no dependency on any Swiftlint version. + # See https://github.com/groue/GRDB.swift/issues/1327 + swiftlint --config "${SRCROOT}/Scripts/swiftlint.yml" || true else echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint" fi diff --git a/Scripts/swiftlint.yml b/Scripts/swiftlint.yml index dc8568d0c..00f9d3c47 100644 --- a/Scripts/swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -6,13 +6,14 @@ disabled_rules: - cyclomatic_complexity - duplicate_enum_cases - file_length + - for_where - force_cast - force_try - - for_where - function_body_length - function_parameter_count - identifier_name - is_disjoint + - large_tuple - nesting - opening_brace - redundant_optional_initialization @@ -25,11 +26,10 @@ disabled_rules: - unused_setter_value opt_in_rules: - - anyobject_protocol - array_init - - capture_variable - closure_spacing - collection_alignment + - comma_inheritance - contains_over_filter_count - contains_over_filter_is_empty - contains_over_first_not_nil @@ -48,20 +48,29 @@ opt_in_rules: - last_where - legacy_multiple - legacy_random + - local_doc_comment - lower_acl_than_parent - modifier_order - no_extension_access_modifier + - optional_enum_case_matching - overridden_super_call - pattern_matching_keywords - prohibited_super_call - reduce_into - redundant_type_annotation + - shorthand_optional_binding - sorted_first_last - sorted_imports - toggle_bool + - unused_capture_list + - vertical_parameter_alignment_on_call + - yoda_condition + +analyzer_rules: + - capture_variable + - typesafe_array_init - unused_declaration - unused_import - - yoda_condition vertical_whitespace: max_empty_lines: 2 diff --git a/Support/GRDBDeploymentTarget.xcconfig b/Support/GRDBDeploymentTarget.xcconfig index a3458605c..753467b40 100644 --- a/Support/GRDBDeploymentTarget.xcconfig +++ b/Support/GRDBDeploymentTarget.xcconfig @@ -2,10 +2,11 @@ IPHONEOS_DEPLOYMENT_TARGET = 11.0 MACOSX_DEPLOYMENT_TARGET = 10.13 TVOS_DEPLOYMENT_TARGET = 11.0 WATCHOS_DEPLOYMENT_TARGET = 4.0 +OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 //// Compile with all opt-in APIs //GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 -//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK +//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK // Enable concurrency warning in Swift 5.5 // https://twitter.com/olebegemann/status/1421144304127463427?lang=en diff --git a/Support/Info.plist b/Support/Info.plist index bde6bee8a..8de2a5d91 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.6.1 + 6.7.0 CFBundleSignature ???? CFBundleVersion diff --git a/Tests/CocoaPods/GRDBiOS-framework/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile index 098cd8168..4225f7023 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -7,7 +7,7 @@ post_install do |installer| installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| target.build_configurations.each do |config| # Enable extra GRDB APIs - config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK" + config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" # Enable extra SQLite APIs config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" end diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile index 351d37564..58476053c 100644 --- a/Tests/CocoaPods/GRDBiOS-static/Podfile +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -6,7 +6,7 @@ post_install do |installer| installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| target.build_configurations.each do |config| # Enable extra GRDB APIs - config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK" + config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" # Enable extra SQLite APIs config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" end diff --git a/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift index 82947bcca..402b3f553 100644 --- a/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift +++ b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift @@ -1,7 +1,7 @@ #if canImport(Combine) import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the timeout to expire, or /// the recorded publisher to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Finished.swift b/Tests/CombineExpectations/PublisherExpectations/Finished.swift index 39fa11bfa..0a47d09f6 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Finished.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Finished.swift @@ -17,7 +17,7 @@ import XCTest // try wait(for: recorder.finished.inverted, timeout: 1) // } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher /// to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Inverted.swift b/Tests/CombineExpectations/PublisherExpectations/Inverted.swift index 076611d34..c7f8d72cc 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Inverted.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Inverted.swift @@ -1,7 +1,7 @@ #if canImport(Combine) import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation that fails if the base expectation is fulfilled. /// diff --git a/Tests/CombineExpectations/PublisherExpectations/Map.swift b/Tests/CombineExpectations/PublisherExpectations/Map.swift index 087efbd33..ab4f95c73 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Map.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Map.swift @@ -1,7 +1,7 @@ #if canImport(Combine) import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation that transforms the value of a base expectation. /// @@ -20,7 +20,7 @@ extension PublisherExpectations { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectation { /// Returns a publisher expectation that transforms the value of the /// base expectation. diff --git a/Tests/CombineExpectations/PublisherExpectations/Next.swift b/Tests/CombineExpectations/PublisherExpectations/Next.swift index 937e3b427..76ad0c105 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Next.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Next.swift @@ -1,7 +1,7 @@ #if canImport(Combine) import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher to emit /// `count` elements, or to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/NextOne.swift b/Tests/CombineExpectations/PublisherExpectations/NextOne.swift index 6333b6b20..84ee6233e 100644 --- a/Tests/CombineExpectations/PublisherExpectations/NextOne.swift +++ b/Tests/CombineExpectations/PublisherExpectations/NextOne.swift @@ -1,7 +1,7 @@ #if canImport(Combine) import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher to emit /// one element, or to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Prefix.swift b/Tests/CombineExpectations/PublisherExpectations/Prefix.swift index 274050898..11aced69d 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Prefix.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Prefix.swift @@ -1,7 +1,7 @@ #if canImport(Combine) import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher to emit /// `maxLength` elements, or to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Recording.swift b/Tests/CombineExpectations/PublisherExpectations/Recording.swift index 97d76d394..0b95292dc 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Recording.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Recording.swift @@ -2,7 +2,7 @@ import Combine import XCTest -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher /// to complete. @@ -49,7 +49,7 @@ extension PublisherExpectations { /// } public func get() throws -> Record.Recording { try recorder.value { (elements, completion, remainingElements, consume) in - if let completion = completion { + if let completion { consume(remainingElements.count) return Record.Recording(output: elements, completion: completion) } else { diff --git a/Tests/CombineExpectations/Recorder.swift b/Tests/CombineExpectations/Recorder.swift index 6b91f405c..48e981b27 100644 --- a/Tests/CombineExpectations/Recorder.swift +++ b/Tests/CombineExpectations/Recorder.swift @@ -13,7 +13,7 @@ import XCTest /// /// let elements = try wait(for: recorder.elements, timeout: 1) /// XCTAssertEqual(elements, ["foo", "bar", "baz"]) -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public class Recorder: Subscriber { public typealias Input = Input public typealias Failure = Failure @@ -253,7 +253,7 @@ public class Recorder: Subscriber { synchronized { switch state { case let .subscribed(_, exp, elements): - if let exp = exp { + if let exp { switch exp { case let .onCompletion(expectation): expectation.fulfill() @@ -275,7 +275,7 @@ public class Recorder: Subscriber { // MARK: - Publisher Expectations -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// The type of the publisher expectation returned by `Recorder.completion`. public typealias Completion = Map, Subscribers.Completion> @@ -290,7 +290,7 @@ extension PublisherExpectations { public typealias Single = Map, Input> } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Recorder { /// Returns a publisher expectation which waits for the timeout to expire, /// or the recorded publisher to complete. @@ -572,7 +572,7 @@ extension Recorder { // MARK: - Publisher + Recorder -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher { /// Returns a subscribed Recorder. /// diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index 1f002f238..2b1cf9394 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -22,7 +22,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -128,7 +128,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // frame #71: 0x00007fff72311cc9 libdyld.dylib`start + 1 // frame #72: 0x00007fff72311cc9 libdyld.dylib`start + 1 func testReadPublisherError() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -157,7 +157,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherIsAsynchronous() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -197,7 +197,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherDefaultScheduler() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -237,7 +237,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherCustomScheduler() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -278,7 +278,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherIsReadonly() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } diff --git a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift index a870a0066..e126c54b3 100644 --- a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift @@ -20,7 +20,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { class DatabaseRegionObservationPublisherTests : XCTestCase { func testChangesNotifications() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -61,7 +61,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { // TODO: do the same, but asynchronously. If this is too hard, update the // public API so that users can easily do it. func testPrependInitialDatabaseSync() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index 4f07e7960..791d8201a 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -22,7 +22,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -49,7 +49,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherValue() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -76,7 +76,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherError() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -99,7 +99,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } func testWritePublisherErrorRollbacksTransaction() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -132,7 +132,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherIsAsynchronous() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -168,7 +168,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherDefaultScheduler() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -206,7 +206,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherCustomScheduler() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -247,7 +247,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // TODO: Fix flaky test with both pool and on-disk queue: // - Expectation timeout func testWriteThenReadPublisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -274,7 +274,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWriteThenReadPublisherIsReadonly() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -299,7 +299,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWriteThenReadPublisherWriteError() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -322,7 +322,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } func testWriteThenReadPublisherWriteErrorRollbacksTransaction() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -359,7 +359,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // TODO: Fix flaky test with both pool and on-disk queue: // - Expectation timeout func testWriteThenReadPublisherReadError() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -386,7 +386,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // Regression test against deadlocks created by concurrent completion // and cancellations triggered by .switchToLatest().prefix(1) func testDeadlockPrevention() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } diff --git a/Tests/GRDBCombineTests/Support.swift b/Tests/GRDBCombineTests/Support.swift index bf9c1d3a7..d8f2ec838 100644 --- a/Tests/GRDBCombineTests/Support.swift +++ b/Tests/GRDBCombineTests/Support.swift @@ -51,7 +51,7 @@ final class Test { } } -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) final class AsyncTest { // Raise the repeatCount in order to help spotting flaky tests. private let repeatCount: Int @@ -100,7 +100,7 @@ final class AsyncTest { } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func assertNoFailure( _ completion: Subscribers.Completion, file: StaticString = #file, @@ -111,7 +111,7 @@ public func assertNoFailure( } } -@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func assertFailure( _ completion: Subscribers.Completion, file: StaticString = #file, diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index eedd4afc3..b55fd98c6 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -22,7 +22,7 @@ class ValueObservationPublisherTests : XCTestCase { // MARK: - Default Scheduler func testDefaultSchedulerChangesNotifications() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -64,7 +64,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testDefaultSchedulerFirstValueIsEmittedAsynchronously() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -97,7 +97,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testDefaultSchedulerError() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -123,7 +123,7 @@ class ValueObservationPublisherTests : XCTestCase { // MARK: - Immediate Scheduler func testImmediateSchedulerChangesNotifications() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -165,7 +165,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testImmediateSchedulerEmitsFirstValueSynchronously() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -201,7 +201,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testImmediateSchedulerError() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -226,7 +226,7 @@ class ValueObservationPublisherTests : XCTestCase { // MARK: - Demand - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private class DemandSubscriber: Subscriber { private var subscription: Subscription? let subject = PassthroughSubject() @@ -257,7 +257,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandNoneReceivesNoElement() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -292,7 +292,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandOneReceivesOneElement() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -330,7 +330,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandOneDoesNotReceiveTwoElements() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -372,7 +372,7 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandTwoReceivesTwoElements() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -418,7 +418,7 @@ class ValueObservationPublisherTests : XCTestCase { /// Regression test for https://github.com/groue/GRDB.swift/issues/1194 func testIssue1194() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift index 83c265e8f..f2b95d91c 100644 --- a/Tests/GRDBTests/DataMemoryTests.swift +++ b/Tests/GRDBTests/DataMemoryTests.swift @@ -37,6 +37,7 @@ class DataMemoryTests: GRDBTestCase { do { // This data should not be copied + // (The deprecation warning is expected: we test a deprecated method.) let nonCopiedData = row.dataNoCopy(atIndex: 0)! XCTAssertEqual(nonCopiedData, data) nonCopiedData.withUnsafeBytes { @@ -74,6 +75,7 @@ class DataMemoryTests: GRDBTestCase { do { // This data should not be copied + // (The deprecation warning is expected: we test a deprecated method.) let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)! XCTAssertEqual(nonCopiedData, data) nonCopiedData.withUnsafeBytes { @@ -109,6 +111,7 @@ class DataMemoryTests: GRDBTestCase { } do { // This data should not be copied: + // (The deprecation warning is expected: we test a deprecated method.) let nonCopiedData = row.dataNoCopy(atIndex: 0)! XCTAssertEqual(nonCopiedData, data) nonCopiedData.withUnsafeBytes { nonCopiedBuffer in diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index b0d4d2714..f217c17f0 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -39,7 +39,7 @@ class DatabaseConfigurationTests: GRDBTestCase { var configuration = Configuration() configuration.prepareDatabase { db in - if let error = error { + if let error { throw error } } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index aa4b996fa..c58ed207f 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -50,7 +50,7 @@ private struct RecordWithDate: EncodableRecord, Enco var date: Date } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithDate: Identifiable { var id: Date { date } } @@ -60,7 +60,7 @@ private struct RecordWithOptionalDate: EncodableReco var date: Date? } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithOptionalDate: Identifiable { var id: Date? { date } } @@ -255,7 +255,7 @@ extension DatabaseDateEncodingStrategyTests { } func testFilterID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Identifiable not available") } @@ -335,7 +335,7 @@ extension DatabaseDateEncodingStrategyTests { } func testDeleteID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Identifiable not available") } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 144686272..97977acfe 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -35,7 +35,7 @@ class DatabaseMigratorTests : GRDBTestCase { } func testEmptyMigratorPublisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -147,7 +147,7 @@ class DatabaseMigratorTests : GRDBTestCase { } func testNonEmptyMigratorPublisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -203,7 +203,7 @@ class DatabaseMigratorTests : GRDBTestCase { } func testEmptyMigratorPublisherIsAsynchronous() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -229,7 +229,7 @@ class DatabaseMigratorTests : GRDBTestCase { } func testNonEmptyMigratorPublisherIsAsynchronous() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -256,7 +256,7 @@ class DatabaseMigratorTests : GRDBTestCase { } func testMigratorPublisherDefaultScheduler() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -285,7 +285,7 @@ class DatabaseMigratorTests : GRDBTestCase { } func testMigratorPublisherCustomScheduler() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 6e338372a..30df8d81b 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -238,7 +238,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { s2.signal() } let block2 = { [weak dbPool] () in - if let dbPool = dbPool { + if let dbPool { try! dbPool.read { db in s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -282,7 +282,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { let block2 = { [weak dbPool] () in var statement: Statement? = nil do { - if let dbPool = dbPool { + if let dbPool { do { try dbPool.write { db in statement = try db.makeStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") diff --git a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift index 0fcbd6329..613d6b5ad 100644 --- a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift @@ -103,7 +103,7 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - if let concurrencyError = concurrencyError { + if let concurrencyError { XCTAssertEqual(concurrencyError.resultCode, .SQLITE_BUSY) XCTAssertEqual(concurrencyError.sql, "INSERT INTO stuffs (id) VALUES (NULL)") } else { @@ -159,7 +159,7 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - if let concurrencyError = concurrencyError { + if let concurrencyError { XCTAssertEqual(concurrencyError.resultCode, .SQLITE_BUSY) XCTAssertEqual(concurrencyError.sql, "BEGIN EXCLUSIVE TRANSACTION") } else { @@ -215,7 +215,7 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - if let concurrencyError = concurrencyError { + if let concurrencyError { XCTAssertEqual(concurrencyError.resultCode, .SQLITE_BUSY) XCTAssertEqual(concurrencyError.sql, "BEGIN IMMEDIATE TRANSACTION") } else { diff --git a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift index 6868f8bb0..7c5b9428e 100644 --- a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift @@ -73,7 +73,7 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { s2.signal() } let block2 = { [weak dbQueue] () in - if let dbQueue = dbQueue { + if let dbQueue { try! dbQueue.write { db in s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -118,7 +118,7 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { let block2 = { [weak dbQueue] () in var statement: Statement? = nil do { - if let dbQueue = dbQueue { + if let dbQueue { do { try dbQueue.write { db in statement = try db.makeStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index fec7c02f5..81496473b 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -33,7 +33,7 @@ class DatabaseReaderTests : GRDBTestCase { #endif } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadCanRead() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -75,7 +75,7 @@ class DatabaseReaderTests : GRDBTestCase { #endif } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadPreventsDatabaseModification() async throws { func test(_ dbReader: DatabaseReader) async throws { do { @@ -119,7 +119,7 @@ class DatabaseReaderTests : GRDBTestCase { #endif } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_UnsafeReadCanRead() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index eb66ff237..6176865e8 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -220,7 +220,7 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try XCTAssertEqual(dbPool.read(counter.value), 2) } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func test_read_async() async throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) // 0 diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index d898df7e7..bba11e1f1 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -23,7 +23,7 @@ private struct RecordWithUUID: EncodableRecord, Enco var uuid: UUID } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithUUID: Identifiable { var id: UUID { uuid } } @@ -33,7 +33,7 @@ private struct RecordWithOptionalUUID: EncodableReco var uuid: UUID? } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithOptionalUUID: Identifiable { var id: UUID? { uuid } } @@ -180,7 +180,7 @@ extension DatabaseUUIDEncodingStrategyTests { } func testFilterID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Identifiable not available") } @@ -299,7 +299,7 @@ extension DatabaseUUIDEncodingStrategyTests { } func testDeleteID() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Identifiable not available") } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 76a7eb88d..6a49d50d5 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -195,7 +195,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testVacuumInto() throws { - guard #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { throw XCTSkip("VACUUM INTO is not available") } // Prevent SQLCipher failures @@ -266,7 +266,7 @@ class DatabaseWriterTests : GRDBTestCase { try DatabaseQueue().backup(to: dbQueue) } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_write() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -286,7 +286,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_writeWithoutTransaction() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -309,7 +309,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_barrierWriteWithoutTransaction() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -332,7 +332,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_erase() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -350,7 +350,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_vacuum() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -366,7 +366,7 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(macOS 10.16, iOS 14, tvOS 14, watchOS 7, *) // async + vacuum into + @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // async + vacuum into func testAsyncAwait_vacuumInto() async throws { // Prevent SQLCipher failures guard sqlite3_libversion_number() >= 3027000 else { diff --git a/Tests/GRDBTests/FTS3TableBuilderTests.swift b/Tests/GRDBTests/FTS3TableBuilderTests.swift index cd51aab51..b2434da37 100644 --- a/Tests/GRDBTests/FTS3TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS3TableBuilderTests.swift @@ -76,7 +76,7 @@ class FTS3TableBuilderTests: GRDBTestCase { } #elseif !GRDBCIPHER func testUnicode61TokenizerDiacriticsRemove() throws { - guard #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { throw XCTSkip() } let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/FTS5TableBuilderTests.swift b/Tests/GRDBTests/FTS5TableBuilderTests.swift index 9bccf6c11..3f6da1618 100644 --- a/Tests/GRDBTests/FTS5TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS5TableBuilderTests.swift @@ -130,7 +130,7 @@ class FTS5TableBuilderTests: GRDBTestCase { } #elseif !GRDBCIPHER func testUnicode61TokenizerDiacriticsRemove() throws { - guard #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { throw XCTSkip() } diff --git a/Tests/GRDBTests/FoundationNSUUIDTests.swift b/Tests/GRDBTests/FoundationNSUUIDTests.swift index 0aaf75e2f..8cac824f7 100644 --- a/Tests/GRDBTests/FoundationNSUUIDTests.swift +++ b/Tests/GRDBTests/FoundationNSUUIDTests.swift @@ -4,7 +4,7 @@ import GRDB class FoundationNSUUIDTests: GRDBTestCase { private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws { try makeDatabaseQueue().read { db in - if let expectedUUID = expectedUUID { + if let expectedUUID { let decodedUUID = try NSUUID.fetchOne(db, sql: "SELECT ?", arguments: [value]) XCTAssertEqual(decodedUUID, expectedUUID) } else if value == nil { diff --git a/Tests/GRDBTests/FoundationUUIDTests.swift b/Tests/GRDBTests/FoundationUUIDTests.swift index d5f05ab30..4f0280500 100644 --- a/Tests/GRDBTests/FoundationUUIDTests.swift +++ b/Tests/GRDBTests/FoundationUUIDTests.swift @@ -5,7 +5,7 @@ import GRDB class FoundationUUIDTests: GRDBTestCase { private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws { try makeDatabaseQueue().read { db in - if let expectedUUID = expectedUUID { + if let expectedUUID { let decodedUUID = try UUID.fetchOne(db, sql: "SELECT ?", arguments: [value]) XCTAssertEqual(decodedUUID, expectedUUID) } else if value == nil { diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 61f94e027..812ab716b 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -92,7 +92,7 @@ private struct FlatModel: FetchableRecord { self.t5count = row.scopes[Scopes.suffix]!["t5count"] } - @available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static func modernAll() -> some FetchRequest { all() } @@ -138,7 +138,7 @@ private struct CodableFlatModel: FetchableRecord, Codable { var t3: T3? var t5count: Int - @available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static func modernAll() -> some FetchRequest { all() } @@ -186,7 +186,7 @@ private struct CodableNestedModel: FetchableRecord, Codable { var t3: T3? var t5count: Int - @available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static func modernAll() -> some FetchRequest { all() } diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 0978f74fe..18a15c1ee 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -1253,7 +1253,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1274,7 +1274,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1324,7 +1324,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1415,7 +1415,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1436,7 +1436,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1562,7 +1562,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1692,7 +1692,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1743,7 +1743,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1793,7 +1793,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1847,7 +1847,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1901,7 +1901,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1962,7 +1962,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -2022,7 +2022,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -2088,7 +2088,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -2237,7 +2237,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -2393,7 +2393,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -2496,7 +2496,7 @@ extension MutablePersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index ce4dde873..d919eeb98 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -1332,7 +1332,7 @@ extension PersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1381,7 +1381,7 @@ extension PersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1434,7 +1434,7 @@ extension PersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1557,7 +1557,7 @@ extension PersistableRecordTests { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -1684,7 +1684,7 @@ extension PersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -1821,7 +1821,7 @@ extension PersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -1966,7 +1966,7 @@ extension PersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -2069,7 +2069,7 @@ extension PersistableRecordTests { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index fa3c35f1c..5a86db88f 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -764,7 +764,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.order(Col.age.descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") #elseif !GRDBCIPHER - if #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age.ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") @@ -794,7 +794,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") #elseif !GRDBCIPHER - if #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") @@ -843,7 +843,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.order(Col.age.ascNullsLast).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") #elseif !GRDBCIPHER - if #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age.descNullsFirst).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") @@ -873,7 +873,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).descNullsFirst).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") #elseif !GRDBCIPHER - if #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).ascNullsLast).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 81240e7c2..358cc0680 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -41,7 +41,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension MinimalNonOptionalPrimaryKeySingle: Identifiable { } class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { @@ -460,7 +460,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [String] = [] let cursor = try MinimalNonOptionalPrimaryKeySingle.fetchCursor(db, ids: ids) @@ -499,7 +499,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [String] = [] let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchAll(db, ids: ids) @@ -537,7 +537,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [String] = [] let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchSet(db, ids: ids) @@ -572,7 +572,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.fetchOne(db, id: record.id)! XCTAssertTrue(fetchedRecord.id == record.id) @@ -600,7 +600,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { _ = try MinimalNonOptionalPrimaryKeySingle.find(db, key: "missing") XCTFail("Expected RecordError") @@ -640,7 +640,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [String] = [] let cursor = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchCursor(db) @@ -679,7 +679,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [String] = [] let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchAll(db) @@ -717,7 +717,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [String] = [] let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchSet(db) @@ -752,7 +752,7 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.filter(id: record.id).fetchOne(db)! XCTAssertTrue(fetchedRecord.id == record.id) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 4bdc85eca..da9e7bc9f 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -45,7 +45,7 @@ class MinimalRowID : Record, Hashable { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension MinimalRowID: Identifiable { } class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { @@ -494,7 +494,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let cursor = try MinimalRowID.fetchCursor(db, ids: ids) @@ -533,7 +533,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try MinimalRowID.fetchAll(db, ids: ids) @@ -571,7 +571,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try MinimalRowID.fetchSet(db, ids: ids) @@ -606,7 +606,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try MinimalRowID.fetchOne(db, id: record.id!)! XCTAssertTrue(fetchedRecord.id == record.id) @@ -637,7 +637,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { _ = try MinimalRowID.find(db, id: -1) XCTFail("Expected RecordError") @@ -680,7 +680,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let cursor = try MinimalRowID.filter(ids: ids).fetchCursor(db) @@ -719,7 +719,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchAll(db) @@ -757,7 +757,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchSet(db) @@ -792,7 +792,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try MinimalRowID.filter(id: record.id!).fetchOne(db)! XCTAssertTrue(fetchedRecord.id == record.id) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 86bf02fcb..81e5975c4 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -39,7 +39,7 @@ class MinimalSingle: Record, Hashable { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension MinimalSingle: Identifiable { /// Test non-optional ID type var id: String { UUID! } @@ -518,7 +518,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let UUIDs: [String] = [] let cursor = try MinimalSingle.fetchCursor(db, ids: UUIDs) @@ -559,7 +559,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let UUIDs: [String] = [] let fetchedRecords = try MinimalSingle.fetchAll(db, ids: UUIDs) @@ -599,7 +599,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let UUIDs: [String] = [] let fetchedRecords = try MinimalSingle.fetchSet(db, ids: UUIDs) @@ -635,7 +635,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try MinimalSingle.fetchOne(db, id: record.UUID!)! XCTAssertTrue(fetchedRecord.UUID == record.UUID) @@ -664,7 +664,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { _ = try MinimalSingle.find(db, id: "missing") XCTFail("Expected RecordError") @@ -706,7 +706,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let UUIDs: [String] = [] let cursor = try MinimalSingle.filter(ids: UUIDs).fetchCursor(db) @@ -747,7 +747,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let UUIDs: [String] = [] let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchAll(db) @@ -787,7 +787,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let UUIDs: [String] = [] let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchSet(db) @@ -823,7 +823,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try MinimalSingle.filter(id: record.UUID!).fetchOne(db)! XCTAssertTrue(fetchedRecord.UUID == record.UUID) diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index bd9e4d0eb..3bb0562ed 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -77,7 +77,7 @@ private class Person : Record, Hashable { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Person: Identifiable { } class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { @@ -586,7 +586,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let cursor = try Person.fetchCursor(db, ids: ids) @@ -625,7 +625,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try Person.fetchAll(db, ids: ids) @@ -663,7 +663,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try Person.fetchSet(db, ids: ids) @@ -701,7 +701,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try Person.fetchOne(db, id: record.id!)! XCTAssertTrue(fetchedRecord.id == record.id) @@ -738,7 +738,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { _ = try Person.find(db, id: -1) XCTFail("Expected RecordError") @@ -784,7 +784,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let cursor = try Person.filter(ids: ids).fetchCursor(db) @@ -823,7 +823,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try Person.filter(ids: ids).fetchAll(db) @@ -861,7 +861,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let ids: [Int64] = [] let fetchedRecords = try Person.filter(ids: ids).fetchSet(db) @@ -899,7 +899,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { do { let fetchedRecord = try Person.filter(id: record.id!).fetchOne(db)! XCTAssertTrue(fetchedRecord.id == record.id) diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index bcf7a3f68..7fa4f3c36 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -631,7 +631,7 @@ class AdapterRowTests : RowTestCase { copiedRow = baseRow.copy() } - if let copiedRow = copiedRow { + if let copiedRow { XCTAssertEqual(copiedRow.count, 3) XCTAssertEqual(copiedRow["a"] as Int, 0) XCTAssertEqual(copiedRow["b"] as Int, 1) @@ -668,7 +668,7 @@ class AdapterRowTests : RowTestCase { row = baseRow.copy() XCTAssertEqual(row, baseRow) } - if let row = row { + if let row { let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } else { diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 8e50c6bf6..14434c777 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -249,6 +249,21 @@ extension SQLLiteralTests { func testTableInterpolation() throws { try makeDatabaseQueue().inDatabase { db in struct Player: TableRecord { } + do { + // Table + let table = Table("player") + let query: SQL = """ + SELECT * + FROM \(table) + """ + + let (sql, arguments) = try query.build(db) + XCTAssertEqual(sql, """ + SELECT * + FROM "player" + """) + XCTAssert(arguments.isEmpty) + } do { // Non-existential let query: SQL = """ diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index e510fc73e..ca53c61d9 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -104,7 +104,7 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_immediate_publisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -381,7 +381,7 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_async_publisher() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -511,7 +511,7 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_error_recovery_observationLifetime() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -567,7 +567,7 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_error_recovery_whileObserved() throws { - guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") } @@ -621,7 +621,7 @@ class SharedValueObservationTests: GRDBTestCase { } #endif - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait() async throws { let dbQueue = try makeDatabaseQueue() try await dbQueue.write { db in diff --git a/Tests/GRDBTests/SingletonRecordTest.swift b/Tests/GRDBTests/SingletonRecordTest.swift index 13bf62384..ea8008c25 100644 --- a/Tests/GRDBTests/SingletonRecordTest.swift +++ b/Tests/GRDBTests/SingletonRecordTest.swift @@ -192,7 +192,7 @@ class SingletonRecordTest: GRDBTestCase { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif @@ -215,7 +215,7 @@ class SingletonRecordTest: GRDBTestCase { throw XCTSkip("UPSERT is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("UPSERT is not available") } #endif diff --git a/Tests/GRDBTests/StatementArguments+FoundationTests.swift b/Tests/GRDBTests/StatementArguments+FoundationTests.swift index 61ec4b075..3d5094eb5 100644 --- a/Tests/GRDBTests/StatementArguments+FoundationTests.swift +++ b/Tests/GRDBTests/StatementArguments+FoundationTests.swift @@ -47,14 +47,14 @@ class StatementArgumentsFoundationTests: GRDBTestCase { } } - func testStatementArgumentsNSArrayInitializerFromInvalidNSArray() { - let persons = [ // NSArray, because of the heterogeneous values - ["Arthur", NonDatabaseConvertibleObject()], - ["Barbara", NonDatabaseConvertibleObject()], - ] - - for person in persons { - XCTAssertNil(StatementArguments(person)) + func testStatementArgumentsInitializerFromInvalidArray() { + do { + let array: [Any] = ["Arthur", NonDatabaseConvertibleObject()] + XCTAssertNil(StatementArguments(array)) + } + do { + let array: NSArray = ["Arthur", NonDatabaseConvertibleObject()] + XCTAssertNil(StatementArguments(array as! [Any])) } } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index ffefeb44a..1f1a97f8d 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -362,7 +362,7 @@ class TableDefinitionTests: GRDBTestCase { throw XCTSkip("Generated columns are not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("Generated columns are not available") } #endif @@ -725,7 +725,7 @@ class TableDefinitionTests: GRDBTestCase { throw XCTSkip("ALTER TABLE RENAME COLUMN is not available") } #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) else { + guard #available(iOS 13, tvOS 13, watchOS 6, *) else { throw XCTSkip("ALTER TABLE RENAME COLUMN is not available") } #endif @@ -753,7 +753,7 @@ class TableDefinitionTests: GRDBTestCase { throw XCTSkip("ALTER TABLE RENAME COLUMN is not available") } #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) else { + guard #available(iOS 13, tvOS 13, watchOS 6, *) else { throw XCTSkip("ALTER TABLE RENAME COLUMN is not available") } #endif @@ -777,7 +777,7 @@ class TableDefinitionTests: GRDBTestCase { throw XCTSkip("Generated columns are not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("Generated columns are not available") } #endif @@ -812,7 +812,7 @@ class TableDefinitionTests: GRDBTestCase { throw XCTSkip("ALTER TABLE DROP COLUMN is not available") } #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("ALTER TABLE DROP COLUMN is not available") } #endif @@ -836,7 +836,7 @@ class TableDefinitionTests: GRDBTestCase { throw XCTSkip("ALTER TABLE DROP COLUMN is not available") } #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("ALTER TABLE DROP COLUMN is not available") } #endif diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 19182f7aa..a141e18e9 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -259,7 +259,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, Reader.order(Col.age.descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") #elseif !GRDBCIPHER - if #available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { XCTAssertEqual( sql(dbQueue, Reader.order(Col.age.ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") @@ -357,7 +357,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { } func testExistsIdentifiable() throws { - guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { throw XCTSkip("Identifiable is not available") } diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index ee8f21011..e88a87c65 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -6,7 +6,7 @@ private struct Hacker : TableRecord { var id: Int64? // Optional } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Hacker: Identifiable { } private struct Person : Codable, PersistableRecord, FetchableRecord, Hashable { @@ -16,7 +16,7 @@ private struct Person : Codable, PersistableRecord, FetchableRecord, Hashable { var email: String } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Person: Identifiable { } private struct Citizenship : TableRecord { @@ -46,7 +46,7 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertTrue(deleted) XCTAssertEqual(try Hacker.fetchCount(db), 0) - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [1, "Arthur"]) try XCTAssertFalse(Hacker.deleteOne(db, id: nil)) deleted = try Hacker.deleteOne(db, id: 1) @@ -62,7 +62,7 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertEqual(deletedCount, 2) XCTAssertEqual(try Hacker.fetchCount(db), 1) - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [2, "Barbara"]) try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [3, "Craig"]) let deletedCount = try Hacker.deleteAll(db, ids: [2, 3, 4]) @@ -85,7 +85,7 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertTrue(deleted) XCTAssertEqual(try Person.fetchCount(db), 0) - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) deleted = try Person.deleteOne(db, id: 1) XCTAssertTrue(deleted) @@ -100,7 +100,7 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertEqual(deletedCount, 2) XCTAssertEqual(try Person.fetchCount(db), 1) - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) let deletedCount = try Person.deleteAll(db, ids: [2, 3, 4]) @@ -190,7 +190,7 @@ class TableRecordDeleteTests: GRDBTestCase { try Person.filter(keys: [1, 2]).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2)") - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { try Person.filter(id: 1).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1") @@ -235,7 +235,7 @@ class TableRecordDeleteTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -255,7 +255,7 @@ class TableRecordDeleteTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -278,7 +278,7 @@ 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 #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") @@ -308,7 +308,7 @@ class TableRecordDeleteTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -336,7 +336,7 @@ class TableRecordDeleteTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -422,7 +422,7 @@ class TableRecordDeleteTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -589,7 +589,7 @@ class TableRecordDeleteTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index eeabd3bfc..0b66595c3 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -17,7 +17,7 @@ private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable { } } -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Player: Identifiable { } private enum Columns: String, ColumnExpression { @@ -56,7 +56,7 @@ class TableRecordUpdateTests: GRDBTestCase { UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2) """) - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { try Player.filter(id: 1).updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 WHERE "id" = 1 @@ -123,7 +123,7 @@ class TableRecordUpdateTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -146,7 +146,7 @@ class TableRecordUpdateTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -173,7 +173,7 @@ class TableRecordUpdateTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif @@ -201,7 +201,7 @@ class TableRecordUpdateTests: GRDBTestCase { throw XCTSkip("RETURNING clause is not available") } #else - guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { throw XCTSkip("RETURNING clause is not available") } #endif diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index 6b67e8092..46c8f5a19 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -117,7 +117,7 @@ class TableTests: GRDBTestCase { """) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { struct Player: Identifiable { var id: Int64 } let t = Table("player") @@ -129,7 +129,7 @@ class TableTests: GRDBTestCase { """) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { struct Player: Identifiable { var id: Int64? } let t = Table("player") @@ -806,7 +806,7 @@ class TableTests: GRDBTestCase { """) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { // Non-optional ID struct Country: Identifiable { var id: String } @@ -821,7 +821,7 @@ class TableTests: GRDBTestCase { """) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { // Optional ID struct Country: Identifiable { var id: String? } @@ -920,7 +920,7 @@ class TableTests: GRDBTestCase { """) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { // Non-optional ID struct Country: Identifiable { var id: String } @@ -930,7 +930,7 @@ class TableTests: GRDBTestCase { """) } - if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { // Optional ID struct Country: Identifiable { var id: String? } diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift new file mode 100644 index 000000000..5a9383b20 --- /dev/null +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -0,0 +1,97 @@ +import XCTest +import GRDB + +class TransactionDateTests: GRDBTestCase { + func testTransactionDateOutsideOfTransaction() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, dates) + } + + func testTransactionDateInsideTransaction_commit() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try db.execute(sql: "COMMIT") + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + } + + func testTransactionDateInsideTransaction_rollback() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try db.execute(sql: "ROLLBACK") + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + } + + func testTransactionDateInsideTransaction_rollbackingError() throws { + let dates = [ + Date.distantPast, + Date(), + Date.distantFuture, + ] + var dateIterator = dates.makeIterator() + dbConfiguration.transactionClock = .custom { _ in + dateIterator.next()! + } + + var collectedDates: [Date] = [] + try makeDatabaseQueue().inDatabase { db in + try collectedDates.append(db.transactionDate) + try db.execute(sql: "BEGIN") + try collectedDates.append(db.transactionDate) + try collectedDates.append(db.transactionDate) + try? db.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY ON CONFLICT ROLLBACK); + INSERT INTO t VALUES (1); + INSERT INTO t VALUES (1); -- fails and rollbacks + """) + try collectedDates.append(db.transactionDate) + } + XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]]) + } +} diff --git a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift index fd700a450..b0df5932b 100644 --- a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift +++ b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift @@ -40,16 +40,16 @@ class TransactionObserverSavepointsTests: GRDBTestCase { private func match(preUpdateEvent event: DatabasePreUpdateEvent, kind: DatabasePreUpdateEvent.Kind, tableName: String, initialRowID: Int64?, finalRowID: Int64?, initialValues: [DatabaseValue]?, finalValues: [DatabaseValue]?, depth: CInt = 0) -> Bool { func check(_ dbValues: [DatabaseValue]?, expected: [DatabaseValue]?) -> Bool { - if let dbValues = dbValues { - guard let expected = expected else { return false } + if let dbValues { + guard let expected else { return false } return dbValues == expected } else { return expected == nil } } var count : Int = 0 - if let initialValues = initialValues { count = initialValues.count } - if let finalValues = finalValues { count = max(count, finalValues.count) } + if let initialValues { count = initialValues.count } + if let finalValues { count = max(count, finalValues.count) } guard (event.kind == kind) else { return false } guard (event.tableName == tableName) else { return false } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 446927342..386bbe21d 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -16,7 +16,7 @@ private class Observer : TransactionObserver { } deinit { - if let deinitBlock = deinitBlock { + if let deinitBlock { deinitBlock() } } @@ -57,7 +57,7 @@ private class Observer : TransactionObserver { func databaseWillCommit() throws { willCommitCount += 1 - if let commitError = commitError { + if let commitError { throw commitError } } @@ -144,16 +144,16 @@ class TransactionObserverTests: GRDBTestCase { private func match(preUpdateEvent event: DatabasePreUpdateEvent, kind: DatabasePreUpdateEvent.Kind, tableName: String, initialRowID: Int64?, finalRowID: Int64?, initialValues: [DatabaseValue]?, finalValues: [DatabaseValue]?, depth: CInt = 0) -> Bool { func check(_ dbValues: [DatabaseValue]?, expected: [DatabaseValue]?) -> Bool { - if let dbValues = dbValues { - guard let expected = expected else { return false } + if let dbValues { + guard let expected else { return false } return dbValues == expected } else { return expected == nil } } var count : Int = 0 - if let initialValues = initialValues { count = initialValues.count } - if let finalValues = finalValues { count = max(count, finalValues.count) } + if let initialValues { count = initialValues.count } + if let finalValues { count = max(count, finalValues.count) } guard (event.kind == kind) else { return false } guard (event.tableName == tableName) else { return false } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 2b585a740..297d54662 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -668,7 +668,7 @@ extension ValueObservationExpectations { consume(1) return next } - if let error = error { + if let error { throw error } else { throw ValueRecordingError.notEnoughValues @@ -696,7 +696,7 @@ extension ValueObservationExpectations { if remainingValues.isEmpty == false { return } - if let error = error { + if let error { throw error } } @@ -732,7 +732,7 @@ extension ValueObservationExpectations { consume(count) return Array(remainingValues.prefix(count)) } - if let error = error { + if let error { throw error } else { throw ValueRecordingError.notEnoughValues @@ -783,7 +783,7 @@ extension ValueObservationExpectations { consume(extraCount) return Array(values.prefix(matchedCount)) } - if let error = error { + if let error { throw error } consume(remainingValues.count) @@ -807,7 +807,7 @@ extension ValueObservationExpectations { public func get() throws -> (values: [Value], error: Error) { try recorder.value { (values, error, remainingValues, consume) in - if let error = error { + if let error { consume(remainingValues.count) return (values: values, error: error) } else { diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 3a2a7d49a..754b73046 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -756,7 +756,7 @@ class ValueObservationTests: GRDBTestCase { // MARK: - Async Await - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -790,7 +790,7 @@ class ValueObservationTests: GRDBTestCase { try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix_immediate_scheduling() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -824,7 +824,7 @@ class ValueObservationTests: GRDBTestCase { try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_break() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -862,7 +862,7 @@ class ValueObservationTests: GRDBTestCase { try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_immediate_break() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -897,7 +897,7 @@ class ValueObservationTests: GRDBTestCase { try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } - @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_cancelled() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change