From 512764403f2527df6e731cc5b614dc9fe120c49d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 15:39:40 +0100 Subject: [PATCH 01/12] Prepare for fixits for removed deprecated methods --- GRDB.xcodeproj/project.pbxproj | 20 +- GRDB/Fixit/GRDB-4.0.swift | 271 --------------------------- GRDB/Fixit/GRDB-5.0.swift | 1 + GRDBCustom.xcodeproj/project.pbxproj | 12 +- 4 files changed, 17 insertions(+), 287 deletions(-) delete mode 100644 GRDB/Fixit/GRDB-4.0.swift create mode 100644 GRDB/Fixit/GRDB-5.0.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a1939a142..f2c4a36b1 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -455,9 +455,9 @@ 567DAF221EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; - 567ECE4F2222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; - 567ECE502222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; - 567ECE512222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; + 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; + 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; + 567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -908,7 +908,7 @@ AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; }; AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; - AAA4DCD3230F1E0600C74B15 /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; }; + AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; }; AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; @@ -1362,7 +1362,7 @@ 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; - 567ECE4E2222E431009245CA /* GRDB-4.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-4.0.swift"; sourceTree = ""; }; + 567ECE4E2222E431009245CA /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; @@ -2225,7 +2225,7 @@ 56D7E449221595FE0052464B /* Fixit */ = { isa = PBXGroup; children = ( - 567ECE4E2222E431009245CA /* GRDB-4.0.swift */, + 567ECE4E2222E431009245CA /* GRDB-5.0.swift */, ); path = Fixit; sourceTree = ""; @@ -2787,7 +2787,7 @@ 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, 569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, - 567ECE512222E431009245CA /* GRDB-4.0.swift in Sources */, + 567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, @@ -2977,7 +2977,7 @@ 569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, - 567ECE502222E431009245CA /* GRDB-4.0.swift in Sources */, + 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */, @@ -3522,7 +3522,7 @@ AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */, AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */, AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */, - AAA4DCD3230F1E0600C74B15 /* GRDB-4.0.swift in Sources */, + AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */, AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */, AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */, AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */, @@ -3862,7 +3862,7 @@ 569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, - 567ECE4F2222E431009245CA /* GRDB-4.0.swift in Sources */, + 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift deleted file mode 100644 index 1c6c41220..000000000 --- a/GRDB/Fixit/GRDB-4.0.swift +++ /dev/null @@ -1,271 +0,0 @@ -import Dispatch - -// Fixits for changes introduced by GRDB 4.0.0 - -extension Cursor { - @available(*, unavailable, renamed: "compactMap") - public func flatMap( - _ transform: @escaping (Element) throws -> ElementOfResult?) - -> MapCursor>, ElementOfResult> - { preconditionFailure() } -} - -extension DatabaseWriter { - @available(*, unavailable, message: "Use concurrentRead instead") - public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() } -} - -extension ValueObservation { - @available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure") - public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) - -> ValueObservation - { preconditionFailure() } - - @available(*, unavailable, message: "Use removeDuplicates() instead") - public static func tracking( - _ regions: DatabaseRegionConvertible..., - fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation>> - where Value: Equatable - { preconditionFailure() } -} - -@available(*, unavailable, renamed: "FastDatabaseValueCursor") -public typealias ColumnCursor = FastDatabaseValueCursor - where Value: DatabaseValueConvertible & StatementColumnConvertible - -@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor") -public typealias NullableColumnCursor = FastNullableDatabaseValueCursor - where Value: DatabaseValueConvertible & StatementColumnConvertible - -extension Database { - @available(*, unavailable, renamed: "execute(sql:arguments:)") - public func execute(_ sql: String, arguments: StatementArguments? = nil) throws { preconditionFailure() } - - @available(*, unavailable, renamed: "makeSelectStatement(sql:)") - public func makeSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() } - - @available(*, unavailable, renamed: "cachedSelectStatement(sql:)") - public func cachedSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() } - - @available(*, unavailable, renamed: "makeUpdateStatement(sql:)") - public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() } - - @available(*, unavailable, renamed: "cachedUpdateStatement(sql:)") - public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() } -} - -extension DatabaseValueConvertible { - @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> DatabaseValueCursor - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> [Self] - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> Self? - { preconditionFailure() } -} - -extension Optional where Wrapped: DatabaseValueConvertible { - @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> NullableDatabaseValueCursor - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> [Wrapped?] - { preconditionFailure() } -} - -extension Row { - @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> RowCursor - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> [Row] - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> Row? - { preconditionFailure() } -} - -extension DatabaseValueConvertible where Self: StatementColumnConvertible { - @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> FastDatabaseValueCursor - { preconditionFailure() } -} - -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> FastNullableDatabaseValueCursor - { preconditionFailure() } -} - -extension FetchableRecord { - @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> RecordCursor - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> [Self] - { preconditionFailure() } - - @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne( - _ db: Database, - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) - throws -> Self? - { preconditionFailure() } -} - -extension SQLRequest { - @available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)") - public init( - _ sql: String, - arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil, - cached: Bool = false) - { preconditionFailure() } -} - -extension SQLExpressionLiteral { - @available(*, unavailable, renamed: "init(sql:arguments:)") - public init(_ sql: String, arguments: StatementArguments? = nil) { preconditionFailure() } -} - -extension SQLExpression { - @available(*, unavailable, message: "Use sqlLiteral property instead") - public var literal: SQLExpressionLiteral { preconditionFailure() } -} - -extension FTS3TokenizerDescriptor { - @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61( - removeDiacritics: Bool, - separators: Set = [], - tokenCharacters: Set = []) - -> FTS3TokenizerDescriptor - { preconditionFailure() } -} - -#if SQLITE_ENABLE_FTS5 -extension FTS5TokenizerDescriptor { - @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61( - removeDiacritics: Bool = true, - separators: Set = [], - tokenCharacters: Set = []) - -> FTS5TokenizerDescriptor - { preconditionFailure() } -} -#endif - -extension DatabaseValue { - @available(*, unavailable) - public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) - -> T - where T: DatabaseValueConvertible - { preconditionFailure() } - - @available(*, unavailable) - public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) - -> T? - where T: DatabaseValueConvertible - { preconditionFailure() } -} - -extension ValueScheduling { - @available(*, unavailable, renamed: "async(onQueue:startImmediately:)") - public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) - -> ValueScheduling - { preconditionFailure() } -} - -extension ValueObservation { - // swiftlint:disable:next line_length - @available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.") - public var extent: Database.TransactionObservationExtent { - get { preconditionFailure() } - set { preconditionFailure() } - } -} - -extension Configuration { - @available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.prepareDatabase instead.") - public var cipherPageSize: Int { - get { preconditionFailure() } - set { preconditionFailure() } - } - - @available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.prepareDatabase instead.") - public var kdfIterations: Int { - get { preconditionFailure() } - set { preconditionFailure() } - } -} diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift new file mode 100644 index 000000000..e3253a669 --- /dev/null +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -0,0 +1 @@ +// Fixits for changes introduced by GRDB 5.0.0 diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7da5d343e..ee5cc855f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -28,8 +28,8 @@ 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; 5613EDA321A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; }; 5613EDA421A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; }; - 561408A0221596A100DAD589 /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-4.0.swift */; }; - 561408A1221596A100DAD589 /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-4.0.swift */; }; + 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; }; + 561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; }; 5615B258222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; 5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; 5615B26D222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B26C222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift */; }; @@ -745,7 +745,7 @@ 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; - 5614089E221596A100DAD589 /* GRDB-4.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-4.0.swift"; sourceTree = ""; }; + 5614089E221596A100DAD589 /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = ""; }; 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = ""; }; 5615B26C222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughRowScopeTests.swift; sourceTree = ""; }; 5615B277222B109500061C1C /* AssociationHasOneThroughFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughFetchableRecordTests.swift; sourceTree = ""; }; @@ -1206,7 +1206,7 @@ 5614089D221596A100DAD589 /* Fixit */ = { isa = PBXGroup; children = ( - 5614089E221596A100DAD589 /* GRDB-4.0.swift */, + 5614089E221596A100DAD589 /* GRDB-5.0.swift */, ); path = Fixit; sourceTree = ""; @@ -2250,7 +2250,7 @@ F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, 5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 561408A1221596A100DAD589 /* GRDB-4.0.swift in Sources */, + 561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56FBFED72210731100945324 /* SQLRequest.swift in Sources */, 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */, @@ -2589,7 +2589,7 @@ F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 561408A0221596A100DAD589 /* GRDB-4.0.swift in Sources */, + 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, 564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */, From 130e510f8c116e9fdbaace50e78289d5f87c0aac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 15:54:09 +0100 Subject: [PATCH 02/12] Remove deprecated passphrase methods --- GRDB/Core/Configuration.swift | 16 --- GRDB/Core/Database.swift | 14 --- GRDB/Core/DatabasePool.swift | 24 +--- GRDB/Core/DatabaseQueue.swift | 13 --- GRDB/Fixit/GRDB-5.0.swift | 20 ++++ Tests/GRDBTests/EncryptionTests.swift | 158 -------------------------- 6 files changed, 22 insertions(+), 223 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 8a08bae7a..a84df3197 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -111,22 +111,6 @@ public struct Configuration { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) public var observesSuspensionNotifications = false - // MARK: - Encryption - - #if SQLITE_HAS_CODEC - // TODO: remove when the deprecated passphrase turns unavailable. - var _passphrase: String? - - /// The passphrase for the encrypted database. - /// - /// Default: nil - @available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") - public var passphrase: String? { - get { return _passphrase } - set { _passphrase = newValue } - } - #endif - // MARK: - Managing SQLite Connections /// A function that is run when an SQLite connection is opened, before the diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1c0611318..de9da985b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -220,9 +220,6 @@ public final class Database { #if SQLITE_HAS_CODEC try validateSQLCipher() - if let passphrase = configuration._passphrase { - try _usePassphrase(passphrase) - } #endif // Last step before we can start accessing the database. @@ -1178,17 +1175,6 @@ extension Database { /// try db.usePassphrase("secret") /// } public func usePassphrase(_ passphrase: String) throws { - // Support for the deprecated method change(passphrase:). - // After it has been called, the passphrase used for opening the - // database must be ignored. - if configuration._passphrase != nil { - return - } - try _usePassphrase(passphrase) - } - - /// See usePassphrase(_:) - private func _usePassphrase(_ passphrase: String) throws { let data = passphrase.data(using: .utf8)! let code = data.withUnsafeBytes { sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count)) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index a8b877863..98669c7a6 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -15,9 +15,6 @@ import UIKit public final class DatabasePool: DatabaseWriter { private let writer: SerializedDatabase private var readerPool: Pool! - // TODO: remove when the deprecated change(passphrase:) method turns unavailable. - private var readerConfiguration: Configuration - private var functions = Set() private var collations = Set() private var tokenizerRegistrations: [(Database) -> Void] = [] @@ -59,7 +56,7 @@ public final class DatabasePool: DatabaseWriter { purpose: "writer") // Readers - readerConfiguration = configuration + var readerConfiguration = configuration readerConfiguration.readonly = true // Readers use deferred transactions by default. @@ -96,7 +93,7 @@ public final class DatabasePool: DatabaseWriter { readerCount += 1 // protected by pool (TODO: documented this protection behavior) let reader = try SerializedDatabase( path: path, - configuration: self.readerConfiguration, + configuration: readerConfiguration, schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabasePool", purpose: "reader.\(readerCount)") @@ -262,23 +259,6 @@ extension DatabasePool { #endif } -#if SQLITE_HAS_CODEC -extension DatabasePool { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - @available(*, deprecated, message: "Use Database.changePassphrase(_:) instead") - public func change(passphrase: String) throws { - try readerPool.barrier { - try writer.sync { try $0.changePassphrase(passphrase) } - readerPool.removeAll() - readerConfiguration._passphrase = passphrase - } - } -} -#endif - extension DatabasePool: DatabaseReader { // MARK: - Interrupting Database Operations diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 347c74d1d..4382dddbd 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -140,19 +140,6 @@ extension DatabaseQueue { #endif } -#if SQLITE_HAS_CODEC -extension DatabaseQueue { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - @available(*, deprecated, message: "Use Database.changePassphrase(_:) instead") - public func change(passphrase: String) throws { - try writer.sync { try $0.changePassphrase(passphrase) } - } -} -#endif - extension DatabaseQueue { // MARK: - Interrupting Database Operations diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index e3253a669..37cfb6f5c 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -1 +1,21 @@ // Fixits for changes introduced by GRDB 5.0.0 + +#if SQLITE_HAS_CODEC +extension Configuration { + @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") + public var passphrase: String? { + get { preconditionFailure() } + set { preconditionFailure() } + } +} + +extension DatabasePool { + @available(*, unavailable, message: "Use Database.changePassphrase(_:) instead") + public func change(passphrase: String) throws { preconditionFailure() } +} + +extension DatabaseQueue { + @available(*, unavailable, message: "Use Database.changePassphrase(_:) instead") + public func change(passphrase: String) throws { preconditionFailure() } +} +#endif diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index 59cf49ac2..5b75f1e69 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -606,163 +606,5 @@ class EncryptionTests: GRDBTestCase { } } } - - // MARK: - Deprecated - - func testDeprecatedPassphrase() throws { - do { - var config = Configuration() - config.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE data (value INTEGER)") - try db.execute(sql: "INSERT INTO data (value) VALUES (1)") - } - } - - do { - var config = Configuration() - config.passphrase = "secret" - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.inDatabase { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1) - } - } - - do { - var config = Configuration() - config.passphrase = nil - do { - _ = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - XCTFail("Expected error") - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_NOTADB) - XCTAssertEqual(error.message!, "file is not a database") - } - } - } - - func testDeprecatedDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws { - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("secret") - } - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE data (value INTEGER)") - try db.execute(sql: "INSERT INTO data (value) VALUES (1)") - } - } - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("secret") - } - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.change(passphrase: "newSecret") - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO data (value) VALUES (2)") - } - try dbQueue.inDatabase { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - } - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("newSecret") - } - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.inDatabase { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - } - } - - func testDeprecatedDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws { - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("secret") - } - let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config) - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE data (value INTEGER)") - try db.execute(sql: "INSERT INTO data (value) VALUES (1)") - } - } - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("secret") - } - let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.change(passphrase: "newSecret") - try dbPool.write { db in - try db.execute(sql: "INSERT INTO data (value) VALUES (2)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - try dbPool.read { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - } - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("newSecret") - } - let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.read { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - } - } - - func testDeprecatedDatabasePoolWithPassphraseToDatabasePoolWithNewPassphrase() throws { - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("secret") - } - let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE data (value INTEGER)") - try db.execute(sql: "INSERT INTO data (value) VALUES (1)") - } - } - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("secret") - } - let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.change(passphrase: "newSecret") - try dbPool.write { db in - try db.execute(sql: "INSERT INTO data (value) VALUES (2)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - try dbPool.read { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - } - - do { - var config = Configuration() - config.prepareDatabase = { db in - try db.usePassphrase("newSecret") - } - let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config) - try dbPool.read { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2) - } - } - } } #endif From bfdd0696daba114ed13ce37a5f904ac1f3da0edd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 16:08:12 +0100 Subject: [PATCH 03/12] Remove deprecated setupMemoryManagement methods --- GRDB/Core/DatabasePool.swift | 13 +++---------- GRDB/Core/DatabaseQueue.swift | 12 +++--------- GRDB/Fixit/GRDB-5.0.swift | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 98669c7a6..1143bdbf8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -135,12 +135,12 @@ public final class DatabasePool: DatabaseWriter { // Be a nice iOS citizen, and don't consume too much memory // See https://github.com/groue/GRDB.swift/#memory-management #if os(iOS) - setupAutomaticMemoryManagement() + setupMemoryManagement() #endif } deinit { - // Undo job done in setupAutomaticMemoryManagement() + // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error // Explicit unregistration is required before iOS 9 and OS X 10.11. @@ -202,14 +202,7 @@ extension DatabasePool { } } - #if os(iOS) - // swiftlint:disable:next line_length - @available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.") - public func setupMemoryManagement(in application: UIApplication) { - // No op. - } - /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release /// as much memory as possible. @@ -217,7 +210,7 @@ extension DatabasePool { /// - param application: The UIApplication that will start a background /// task to let the database pool release its memory when the application /// enters background. - private func setupAutomaticMemoryManagement() { + private func setupMemoryManagement() { let center = NotificationCenter.default center.addObserver( self, diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 4382dddbd..b157f5b2d 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -44,7 +44,7 @@ public final class DatabaseQueue: DatabaseWriter { // Be a nice iOS citizen, and don't consume too much memory // See https://github.com/groue/GRDB.swift/#memory-management #if os(iOS) - setupAutomaticMemoryManagement() + setupMemoryManagement() #endif } @@ -65,7 +65,7 @@ public final class DatabaseQueue: DatabaseWriter { } deinit { - // Undo job done in setupAutomaticMemoryManagement() + // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error // Explicit unregistration is required before iOS 9 and OS X 10.11. @@ -85,12 +85,6 @@ extension DatabaseQueue { } #if os(iOS) - // swiftlint:disable:next line_length - @available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.") - public func setupMemoryManagement(in application: UIApplication) { - // No op. - } - /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release /// as much memory as possible. @@ -98,7 +92,7 @@ extension DatabaseQueue { /// - param application: The UIApplication that will start a background /// task to let the database queue release its memory when the application /// enters background. - private func setupAutomaticMemoryManagement() { + private func setupMemoryManagement() { let center = NotificationCenter.default center.addObserver( self, diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 37cfb6f5c..cdb4c5ba0 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -1,5 +1,9 @@ // Fixits for changes introduced by GRDB 5.0.0 +#if os(iOS) +import UIKit +#endif + #if SQLITE_HAS_CODEC extension Configuration { @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") @@ -19,3 +23,17 @@ extension DatabaseQueue { public func change(passphrase: String) throws { preconditionFailure() } } #endif + +extension DatabasePool { + #if os(iOS) + @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") + public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } + #endif +} + +extension DatabaseQueue { + #if os(iOS) + @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") + public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } + #endif +} From 0f503fe0db0c6bc15c59f80485db135aef378d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 16:16:45 +0100 Subject: [PATCH 04/12] Remove deprecated FetchRequest.prepare(_: forSingleResult:) --- GRDB/Core/FetchRequest.swift | 50 ------------------- GRDB/Fixit/GRDB-5.0.swift | 40 +++++++++------ .../AssociationBelongsToRowScopeTests.swift | 2 +- ...ssociationHasOneThroughRowScopeTests.swift | 2 +- Tests/GRDBTests/FetchRequestTests.swift | 27 ---------- .../QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/SQLRequestTests.swift | 24 ++++----- 7 files changed, 41 insertions(+), 106 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 02a7925d2..2854b89ae 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -49,20 +49,6 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder - // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method - /// This method is deprecated. Use - /// `makePreparedRequest(_:forSingleResult:)` instead. - /// - /// Returns a tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - /// - /// - parameter db: A database connection. - /// - parameter singleResult: A hint that a single result row will be - /// consumed. Implementations can optionally use this to optimize the - /// prepared statement. - /// - returns: A prepared statement and an eventual row adapter. - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) - /// Returns a PreparedRequest that is ready to be executed. /// /// - parameter db: A database connection. @@ -114,21 +100,6 @@ extension FetchRequest { let request = try makePreparedRequest(db, forSingleResult: false) return request.statement.databaseRegion } - - // Support for legacy requests which only define prepare(_:forSingleResult:) - // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method - /// :nodoc: - public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - let (statement, adapter) = try prepare(db, forSingleResult: singleResult) - return PreparedRequest(statement: statement, adapter: adapter) - } - - // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method - /// :nodoc: - public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - let request = try makePreparedRequest(db, forSingleResult: singleResult) - return (request.statement, request.adapter) - } } // MARK: - AdaptedFetchRequest @@ -189,27 +160,6 @@ public struct AnyFetchRequest: FetchRequest { _databaseRegion = request.databaseRegion } - /// Creates a request whose `prepare()` method wraps and forwards - /// operations the argument closure. - @available(*, deprecated, message: "Define your own FetchRequest type instead.") - public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) { - _preparedRequest = { db, singleResult in - let (statement, adapter) = try prepare(db, singleResult) - return PreparedRequest(statement: statement, adapter: adapter) - } - - _fetchCount = { db in - let (statement, _) = try prepare(db, false) - let sql = "SELECT COUNT(*) FROM (\(statement.sql))" - return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)! - } - - _databaseRegion = { db in - let (statement, _) = try prepare(db, false) - return statement.databaseRegion - } - } - /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { return try _preparedRequest(db, singleResult) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index cdb4c5ba0..a42140a7d 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -4,6 +4,32 @@ import UIKit #endif +extension AnyFetchRequest { + @available(*, unavailable, message: "Define your own FetchRequest type instead.") + public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) + { preconditionFailure() } +} + +extension DatabasePool { + #if os(iOS) + @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") + public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } + #endif +} + +extension DatabaseQueue { + #if os(iOS) + @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") + public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } + #endif +} + +extension FetchRequest { + @available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.") + func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) + { preconditionFailure() } +} + #if SQLITE_HAS_CODEC extension Configuration { @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") @@ -23,17 +49,3 @@ extension DatabaseQueue { public func change(passphrase: String) throws { preconditionFailure() } } #endif - -extension DatabasePool { - #if os(iOS) - @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") - public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } - #endif -} - -extension DatabaseQueue { - #if os(iOS) - @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") - public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() } - #endif -} diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 7b0ae1bb3..e39d64826 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -45,7 +45,7 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = Player.joining(required: Player.defaultTeam) - let (_, adapter) = try request.prepare(db, forSingleResult: false) + let adapter = try request.makePreparedRequest(db, forSingleResult: false).adapter XCTAssertNil(adapter) } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift index 515ca5b1e..689b12e80 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift @@ -61,7 +61,7 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = A.joining(required: A.defaultC) - let (_, adapter) = try request.prepare(db, forSingleResult: false) + let adapter = try request.makePreparedRequest(db, forSingleResult: false).adapter XCTAssertNil(adapter) } } diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index ca7d1feaf..9da752b03 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -7,33 +7,6 @@ import XCTest class FetchRequestTests: GRDBTestCase { - // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method - func testDeprecatedPrepareMethod() throws { - struct CustomRequest : FetchRequest { - typealias RowDecoder = Row - // This method is deprecated but we must support it - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement(sql: "SELECT * FROM table1"), nil) - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES") - try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES") - - let request = CustomRequest() - let rows = try request.fetchAll(db) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0], ["id": 1]) - XCTAssertEqual(rows[1], ["id": 2]) - } - } - func testRequestFetchRows() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Row diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 84fde16d2..e7f65d0e2 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -44,7 +44,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testSimpleRequestDoesNotUseAnyRowAdapter() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let (_, adapter) = try Reader.all().prepare(db, forSingleResult: false) + let adapter = try Reader.all().makePreparedRequest(db, forSingleResult: false).adapter XCTAssertNil(adapter) } } diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index b22cec5f9..0d4f47035 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -11,9 +11,9 @@ class SQLRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = SQLRequest(sql: "SELECT 1") - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - XCTAssertEqual(statement.sql, "SELECT 1") - XCTAssertNil(adapter) + let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false) + XCTAssertEqual(preparedRequest.statement.sql, "SELECT 1") + XCTAssertNil(preparedRequest.adapter) let row = try request.fetchOne(db) XCTAssertEqual(row, ["1": 1]) } @@ -23,9 +23,9 @@ class SQLRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = SQLRequest(sql: "SELECT ?, ?", arguments: [1, 2], adapter: SuffixRowAdapter(fromIndex: 1)) - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - XCTAssertEqual(statement.sql, "SELECT ?, ?") - XCTAssertNotNil(adapter) + let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false) + XCTAssertEqual(preparedRequest.statement.sql, "SELECT ?, ?") + XCTAssertNotNil(preparedRequest.adapter) let int = try request.fetchOne(db)! XCTAssertEqual(int, 2) } @@ -35,9 +35,9 @@ class SQLRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = SQLRequest(sql: "SELECT 1") - let (statement1, _) = try request.prepare(db, forSingleResult: false) - let (statement2, _) = try request.prepare(db, forSingleResult: false) - XCTAssertTrue(statement1 !== statement2) + let preparedRequest1 = try request.makePreparedRequest(db, forSingleResult: false) + let preparedRequest2 = try request.makePreparedRequest(db, forSingleResult: false) + XCTAssertTrue(preparedRequest1.statement !== preparedRequest2.statement) } } @@ -45,9 +45,9 @@ class SQLRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = SQLRequest(sql: "SELECT 1", cached: true) - let (statement1, _) = try request.prepare(db, forSingleResult: false) - let (statement2, _) = try request.prepare(db, forSingleResult: false) - XCTAssertTrue(statement1 === statement2) + let preparedRequest1 = try request.makePreparedRequest(db, forSingleResult: false) + let preparedRequest2 = try request.makePreparedRequest(db, forSingleResult: false) + XCTAssertTrue(preparedRequest1.statement === preparedRequest2.statement) } } From 02890a6d3a17815356da2abf17af45b457fe0d0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 16:28:44 +0100 Subject: [PATCH 05/12] Remove deprecated SQLLiteral.mapSQL(_:) --- GRDB/Core/SQLLiteral.swift | 12 --- GRDB/Fixit/GRDB-5.0.swift | 6 ++ .../QueryInterfaceExtensibilityTests.swift | 78 +------------------ Tests/GRDBTests/SQLLiteralTests.swift | 4 +- 4 files changed, 9 insertions(+), 91 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 41a12f473..d2ad20df4 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -18,8 +18,6 @@ public struct SQLLiteral { case selectable(SQLSelectable) case orderingTerm(SQLOrderingTerm) case subQuery(SQLLiteral) - // TODO: remove when the deprecated SQLLiteral.mapSQL(_:) is removed. - case map(SQLLiteral, (String) -> String) // TODO: remove and use default case argument when compiler >= 5.1 static func sql(_ sql: String) -> Element { @@ -43,8 +41,6 @@ public struct SQLLiteral { return orderingTerm.orderingTermSQL(&context) case let .subQuery(sqlLiteral): return "(" + sqlLiteral.sql(&context) + ")" - case let .map(sqlLiteral, transform): - return transform(sqlLiteral.sql(&context)) } } @@ -61,8 +57,6 @@ public struct SQLLiteral { case .subQuery: // subqueries are not requalified return self - case let .map(sqlLiteral, transform): - return .map(sqlLiteral.qualified(with: alias), transform) } } } @@ -108,12 +102,6 @@ public struct SQLLiteral { self.init(elements: [.expression(expression)]) } - // TODO: deprecate when SQL interpolation is always available - /// Returns a literal whose SQL is transformed by the given closure. - public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral { - return SQLLiteral(elements: [.map(self, transform)]) - } - func sql(_ context: inout SQLGenerationContext) -> String { return elements.map { $0.sql(&context) }.joined() } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index a42140a7d..ac4158a26 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -30,6 +30,12 @@ extension FetchRequest { { preconditionFailure() } } +extension SQLLiteral { + @available(*, unavailable, message: "Use SQL interpolation instead.") + public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral + { preconditionFailure() } +} + #if SQLITE_HAS_CODEC extension Configuration { @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 60e74e297..40741059d 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -37,21 +37,7 @@ func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression { // CAST -private func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { - let literal = value.sqlExpression.sqlLiteral - let castLiteral = literal.mapSQL { sql in - "CAST(\(sql) AS \(type.rawValue))" - } - return SQLExpressionLiteral(literal: castLiteral) -} - -private func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression { - return SQLLiteral(value.sqlExpression) - .mapSQL({ sql in "CAST(\(sql) AS \(type.rawValue))" }) - .sqlExpression -} - -private func castInterpolated(_ value: T, as type: Database.ColumnType) -> SQLExpression { +private func cast(_ value: T, as type: Database.ColumnType) -> SQLExpression { return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression } @@ -96,37 +82,6 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } - func testCastDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "records") { t in - t.column("text", .text) - } - struct Record : TableRecord { - static let databaseTableName = "records" - } - - try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"]) - - do { - let request = Record.select(castDeprecated(Column("text"), as: .blob)) - let dbValue = try DatabaseValue.fetchOne(db, request)! - switch dbValue.storage { - case .blob: - break - default: - XCTFail("Expected data blob") - } - XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1") - } - do { - let request = Record.select(castDeprecated(Column("text"), as: .blob) && true) - _ = try DatabaseValue.fetchOne(db, request)! - XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1") - } - } - } - func testCast() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -157,35 +112,4 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { } } } - - func testCastInterpolated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "records") { t in - t.column("text", .text) - } - struct Record : TableRecord { - static let databaseTableName = "records" - } - - try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"]) - - do { - let request = Record.select(castInterpolated(Column("text"), as: .blob)) - let dbValue = try DatabaseValue.fetchOne(db, request)! - switch dbValue.storage { - case .blob: - break - default: - XCTFail("Expected data blob") - } - XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1") - } - do { - let request = Record.select(castInterpolated(Column("text"), as: .blob) && true) - _ = try DatabaseValue.fetchOne(db, request)! - XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1") - } - } - } } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 3878cada4..825bc0231 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -129,8 +129,8 @@ class SQLLiteralTests: GRDBTestCase { } do { - // Test mapSQL plus qualification - let literal = SQLLiteral(Column("name")).mapSQL { sql in "\(sql) || 'foo'" } + // Test qualification of interpolated literal + let literal: SQLLiteral = "\(Column("name")) || 'foo'" let request = Player.aliased(TableAlias(name: "p")).select(literal.sqlExpression) try assertEqualSQL(db, request, """ SELECT "p"."name" || 'foo' FROM "player" "p" From 456d2aee7541fe48ff49a786fc62060daadd3c0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 16:57:29 +0100 Subject: [PATCH 06/12] Remove deprecated SQLExpressionLiteral --- GRDB/Core/SQLLiteral.swift | 68 +++++++++++--------------------------- GRDB/Fixit/GRDB-5.0.swift | 18 ++++++++++ 2 files changed, 37 insertions(+), 49 deletions(-) diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index d2ad20df4..9b913beab 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -153,21 +153,21 @@ extension SQLLiteral { } extension SQLLiteral { - /// Creates an SQL literal expression. + /// Creates a literal SQL expression. /// /// SQLLiteral(sql: "1 + 2").sqlExpression /// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression /// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression public var sqlExpression: SQLExpression { - return SQLExpressionLiteral(sqlLiteral: self) + return _SQLExpressionLiteral(sqlLiteral: self) } var sqlSelectable: SQLSelectable { - return SQLSelectionLiteral(sqlLiteral: self) + return _SQLSelectionLiteral(sqlLiteral: self) } var sqlOrderingTerm: SQLOrderingTerm { - return SQLOrderingLiteral(sqlLiteral: self) + return _SQLOrderingLiteral(sqlLiteral: self) } } @@ -233,7 +233,7 @@ extension SQLLiteral: ExpressibleByStringInterpolation { } } -// MARK: - SQLExpressionLiteral +// MARK: - _SQLExpressionLiteral /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -245,50 +245,17 @@ extension SQLLiteral: ExpressibleByStringInterpolation { /// /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) -public struct SQLExpressionLiteral: SQLExpression { +private struct _SQLExpressionLiteral: SQLExpression { private let sqlLiteral: SQLLiteral - public var sql: String { return sqlLiteral.sql } - - public var arguments: StatementArguments { return sqlLiteral.arguments } - // Prefer SQLLiteral.sqlExpression - fileprivate init(sqlLiteral: SQLLiteral) { + init(sqlLiteral: SQLLiteral) { self.sqlLiteral = sqlLiteral } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an SQL literal expression. - /// - /// SQLExpressionLiteral(sql: "1 + 2") - /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) - /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) - @available(*, deprecated, message: "Use SQLiteral.sqlExpression instead") - public init(sql: String, arguments: StatementArguments = StatementArguments()) { - self.init(sqlLiteral: SQLLiteral(sql: sql, arguments: arguments)) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an SQL literal expression. - /// - /// SQLExpressionLiteral(literal: SQLLiteral(sql: "1 + 2") - /// SQLExpressionLiteral(literal: SQLLiteral(sql: "? + ?", arguments: [1, 2])) - /// SQLExpressionLiteral(literal: SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])) - /// - /// With Swift 5, you can safely embed raw values in your SQL queries, - /// without any risk of syntax errors or SQL injection: - /// - /// SQLExpressionLiteral(literal: "\(1) + \(2)") - @available(*, deprecated, message: "Use SQLiteral.sqlExpression instead") - public init(literal sqlLiteral: SQLLiteral) { - self.init(sqlLiteral: sqlLiteral) - } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { + func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { if wrappedInParenthesis { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } @@ -297,14 +264,14 @@ public struct SQLExpressionLiteral: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return sqlLiteral.qualified(with: alias).sqlExpression } } -// MARK: - SQLSelectionLiteral +// MARK: - _SQLSelectionLiteral -private struct SQLSelectionLiteral: SQLSelectable { +private struct _SQLSelectionLiteral: SQLSelectable { private let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlSelectable @@ -319,21 +286,24 @@ private struct SQLSelectionLiteral: SQLSelectable { func countedSQL(_ context: inout SQLGenerationContext) -> String { fatalError(""" Selection literals can't be counted. \ - To resolve this error, select one or several SQLExpressionLiteral instead. + To resolve this error, select one or several literal expressions instead. \ + See SQLLiteral.sqlExpression. """) } func count(distinct: Bool) -> SQLCount? { fatalError(""" Selection literals can't be counted. \ - To resolve this error, select one or several SQLExpressionLiteral instead. + To resolve this error, select one or several literal expressions instead. \ + See SQLLiteral.sqlExpression. """) } func columnCount(_ db: Database) throws -> Int { fatalError(""" Selection literals don't known how many columns they contain. \ - To resolve this error, select one or several SQLExpressionLiteral instead. + To resolve this error, select one or several literal expressions instead. \ + See SQLLiteral.sqlExpression. """) } @@ -342,9 +312,9 @@ private struct SQLSelectionLiteral: SQLSelectable { } } -// MARK: - SQLOrderingLiteral +// MARK: - _SQLOrderingLiteral -private struct SQLOrderingLiteral: SQLOrderingTerm { +private struct _SQLOrderingLiteral: SQLOrderingTerm { private let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlOrderingTerm diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index ac4158a26..9df63f015 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -30,6 +30,24 @@ extension FetchRequest { { preconditionFailure() } } +@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") +public struct SQLExpressionLiteral: SQLExpression { + public var sql: String { preconditionFailure() } + public var arguments: StatementArguments { preconditionFailure() } + + public init(sql: String, arguments: StatementArguments = StatementArguments()) + { preconditionFailure() } + + public init(literal sqlLiteral: SQLLiteral) + { preconditionFailure() } + + public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String + { preconditionFailure() } + + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression + { preconditionFailure() } +} + extension SQLLiteral { @available(*, unavailable, message: "Use SQL interpolation instead.") public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral From b9d4a5215a2e1597fee394bd6fae33d36abf6131 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 17:04:43 +0100 Subject: [PATCH 07/12] Remove deprecated DatabaseMigrator methods --- GRDB/Core/Statement.swift | 49 ----- GRDB/Fixit/GRDB-5.0.swift | 34 ++++ GRDB/Migration/DatabaseMigrator.swift | 64 +------ Tests/GRDBTests/DatabaseMigratorTests.swift | 198 -------------------- 4 files changed, 35 insertions(+), 310 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 4a9653575..77564cc48 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -153,27 +153,6 @@ public class Statement { _ = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false) } - /// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all - /// statement arguments. - /// - /// For example: - /// - /// let statement = try db.makeUpdateArgument(sql: """ - /// INSERT INTO player (id, name) VALUES (?, ?) - /// """) - /// - /// // OK - /// statement.validate([1, "Arthur"]) - /// - /// // Throws - /// statement.validate([1]) - /// - /// See also setArguments(_:) - @available(*, deprecated, renamed: "validateArguments(_:)") - public func validate(arguments: StatementArguments) throws { - try validateArguments(arguments) - } - /// Set arguments without any validation. Trades safety for performance. /// /// Only call this method if you are sure input arguments match all expected @@ -214,34 +193,6 @@ public class Statement { } } - /// Set arguments without any validation. Trades safety for performance. - /// - /// Only call this method if you are sure input arguments match all expected - /// arguments of the statement. - /// - /// For example: - /// - /// let statement = try db.makeUpdateArgument(sql: """ - /// INSERT INTO player (id, name) VALUES (?, ?) - /// """) - /// - /// // OK - /// statement.unsafeSetArguments([1, "Arthur"]) - /// - /// // OK - /// let arguments: StatementArguments = ... // some untrusted arguments - /// try statement.validateArguments(arguments) - /// statement.unsafeSetArguments(arguments) - /// - /// // NOT OK - /// statement.unsafeSetArguments([1]) - /// - /// See also setArguments(_:) - @available(*, deprecated, renamed: "setUncheckedArguments(_:)") - public func unsafeSetArguments(_ arguments: StatementArguments) { - setUncheckedArguments(arguments) - } - /// Set the statement arguments, or throws a DatabaseError of code /// SQLITE_ERROR if arguments don't fill all statement arguments. /// diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 9df63f015..20372ac37 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -10,6 +10,30 @@ extension AnyFetchRequest { { preconditionFailure() } } +extension DatabaseMigrator { + @available(*, unavailable, renamed: "registerMigration(_:migrate:)") + public mutating func registerMigrationWithDeferredForeignKeyCheck( + _ identifier: String, + migrate: @escaping (Database) throws -> Void) + { preconditionFailure() } + + @available(*, unavailable, message: "Wrap this method: reader.read(migrator.appliedMigrations) }") + public func appliedMigrations(in reader: DatabaseReader) throws -> Set + { preconditionFailure() } + + @available(*, unavailable, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }") + public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool + { preconditionFailure() } + + @available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)") + public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool + { preconditionFailure() } + + @available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).last") + public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? + { preconditionFailure() } +} + extension DatabasePool { #if os(iOS) @available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.") @@ -54,6 +78,16 @@ extension SQLLiteral { { preconditionFailure() } } +extension Statement { + @available(*, unavailable, renamed: "setUncheckedArguments(_:)") + public func unsafeSetArguments(_ arguments: StatementArguments) + { preconditionFailure() } + + @available(*, unavailable, renamed: "validateArguments(_:)") + public func validate(arguments: StatementArguments) throws + { preconditionFailure() } +} + #if SQLITE_HAS_CODEC extension Configuration { @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b34618f59..3619ad6c2 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -93,28 +93,6 @@ public struct DatabaseMigrator { registerMigration(Migration(identifier: identifier, migrate: migrate)) } - /// Registers a migration. - /// - /// migrator.registerMigrationWithDeferredForeignKeyCheck("createAuthors") { db in - /// try db.create(table: "author") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("creationDate", .datetime) - /// t.column("name", .text).notNull() - /// } - /// } - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - @available(*, deprecated, renamed: "registerMigration(_:migrate:)") - public mutating func registerMigrationWithDeferredForeignKeyCheck( - _ identifier: String, - migrate: @escaping (Database) throws -> Void) - { - registerMigration(identifier, migrate: migrate) - } - // MARK: - Applying Migrations /// Iterate migrations in the same order as they were registered. If a @@ -176,15 +154,6 @@ public struct DatabaseMigrator { // MARK: - Querying Migrations - /// Returns the set of applied migration identifiers. - /// - /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). - /// - throws: An eventual database error. - @available(*, deprecated, message: "Wrap this method: reader.read(migrator.appliedMigrations) }") - public func appliedMigrations(in reader: DatabaseReader) throws -> Set { - return try Set(reader.read(appliedMigrations)) - } - /// Returns the applied migration identifiers, in the same order as /// registered migrations. /// @@ -216,15 +185,6 @@ public struct DatabaseMigrator { .map { $0.0 }) } - /// Returns true if all migrations are applied. - /// - /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). - /// - throws: An eventual database error. - @available(*, deprecated, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }") - public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool { - return try reader.read(hasCompletedMigrations) - } - /// Returns true if all migrations are applied. /// /// - parameter db: A database connection. @@ -232,29 +192,7 @@ public struct DatabaseMigrator { public func hasCompletedMigrations(_ db: Database) throws -> Bool { return try completedMigrations(db).last == migrations.last?.identifier } - - /// Returns true if all migrations up to the provided target are applied, - /// and maybe further. - /// - /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). - /// - parameter targetIdentifier: The identifier of a registered migration. - /// - throws: An eventual database error. - @available(*, deprecated, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)") - public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool { - return try reader.read(completedMigrations).contains(targetIdentifier) - } - - /// Returns the identifier of the last migration for which all predecessors - /// have been applied. - /// - /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). - /// - returns: An eventual migration identifier. - /// - throws: An eventual database error. - @available(*, deprecated, message: "Prefer reader.read(migrator.completedMigrations).last") - public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? { - return try reader.read(completedMigrations).last - } - + // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index fdfc06236..4523554dc 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -230,112 +230,6 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testMigrationWithDeferredForeignKeyChecksDeprecated() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - var migrator = DatabaseMigrator() - migrator.registerMigration("createPersons") { db in - try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)") - try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)") - try db.execute(sql: "INSERT INTO persons (name) VALUES ('Arthur')") - let personId = db.lastInsertedRowID - try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, 'Bobby')", arguments:[personId]) - } - migrator.registerMigrationWithDeferredForeignKeyCheck("removePersonTmpColumn") { db in - // Test the technique described at https://www.sqlite.org/lang_altertable.html#otheralter - try db.execute(sql: "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT)") - try db.execute(sql: "INSERT INTO new_persons SELECT id, name FROM persons") - try db.execute(sql: "DROP TABLE persons") - try db.execute(sql: "ALTER TABLE new_persons RENAME TO persons") - } - migrator.registerMigrationWithDeferredForeignKeyCheck("foreignKeyError") { db in - // Make sure foreign keys are checked at the end. - try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')") - do { - // triggers foreign key error, but not now. - try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) - } catch { - XCTFail("Error not expected at this point") - } - } - - let dbQueue = try makeDatabaseQueue() - do { - try migrator.migrate(dbQueue) - XCTFail("Expected error") - } catch let error as DatabaseError { - // Migration 1 and 2 should be committed. - // Migration 3 should not be committed. - - XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!, "FOREIGN KEY constraint failed") - XCTAssertTrue(error.sql == nil) - XCTAssertEqual(error.description, "SQLite error 19: FOREIGN KEY constraint failed") - - try dbQueue.inDatabase { db in - // Arthur inserted (migration 1), Barbara (migration 3) not inserted. - var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") - XCTAssertEqual(rows.count, 1) - var row = rows.first! - XCTAssertEqual(row["name"] as String, "Arthur") - - // persons table has no "tmp" column (migration 2) - XCTAssertEqual(Array(row.columnNames), ["id", "name"]) - - // Bobby inserted (migration 1), not deleted by migration 2. - rows = try Row.fetchAll(db, sql: "SELECT * FROM pets") - XCTAssertEqual(rows.count, 1) - row = rows.first! - XCTAssertEqual(row["name"] as String, "Bobby") - } - } - } - - func testAppliedMigrationsDeprecated() throws { - var migrator = DatabaseMigrator() - - // No migration - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) - } - - // One migration - - migrator.registerMigration("1") { db in - try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text) - t.column("score", .integer) - } - } - - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) - } - - // Two migrations - - migrator.registerMigration("2") { db in - try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") - } - - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) - try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"]) - } - } - func testAppliedMigrations() throws { var migrator = DatabaseMigrator() @@ -378,98 +272,6 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testHasCompletedMigrationsDeprecated() throws { - var migrator = DatabaseMigrator() - - // No migration - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) - } - - // One migration - - migrator.registerMigration("1") { db in - try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text) - t.column("score", .integer) - } - } - - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) - } - - // Two migrations - - migrator.registerMigration("2") { db in - try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") - } - - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) - try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) - try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) - try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) - } - } - - func testLastCompletedMigrationDeprecated() throws { - var migrator = DatabaseMigrator() - - // No migration - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) - } - - // One migration - - migrator.registerMigration("1") { db in - try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text) - t.column("score", .integer) - } - } - - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1") - } - - // Two migrations - - migrator.registerMigration("2") { db in - try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") - } - - do { - let dbQueue = try makeDatabaseQueue() - try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1") - try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "2") - } - } - func testCompletedMigrations() throws { var migrator = DatabaseMigrator() From 5dd86d2453f376c8f6742226f4386a81e6406d33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 17:53:39 +0100 Subject: [PATCH 08/12] Remove deprecated ValueObservation methods --- GRDB/Fixit/GRDB-5.0.swift | 62 +++++++ .../ValueObservation+Count.swift | 35 ---- ...Observation+DatabaseValueConvertible.swift | 116 ------------ .../ValueObservation+FetchableRecord.swift | 80 --------- .../ValueObservation+Row.swift | 75 -------- .../ValueReducer/CompactMap.swift | 4 - .../ValueObservation/ValueReducer/Fetch.swift | 4 - GRDB/ValueObservation/ValueReducer/Map.swift | 4 - .../ValueReducer/RemoveDuplicates.swift | 21 --- .../ValueObservationCountTests.swift | 34 ---- ...rvationDatabaseValueConvertibleTests.swift | 116 ------------ .../ValueObservationFetchTests.swift | 32 ---- ...bservationQueryInterfaceRequestTests.swift | 165 +----------------- .../ValueObservationRecordTests.swift | 74 +------- .../GRDBTests/ValueObservationRowTests.swift | 72 -------- 15 files changed, 64 insertions(+), 830 deletions(-) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 20372ac37..70a69aab6 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -88,6 +88,68 @@ extension Statement { { preconditionFailure() } } +extension ValueObservation where Reducer == Void { + @available(*, unavailable, message: "Use request.observationForCount() instead") + public static func trackingCount(_ request: Request) + -> ValueObservation>> + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForAll() instead") + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForFirst() instead") + public static func trackingOne(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForAll() instead") + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: _OptionalProtocol, + Request.RowDecoder._Wrapped: DatabaseValueConvertible + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForAll() instead") + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: FetchableRecord + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForFirst() instead") + public static func trackingOne(_ request: Request) -> + ValueObservation> + where Request.RowDecoder: FetchableRecord + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForAll() instead") + public static func trackingAll(_ request: Request) + -> ValueObservation + where Request.RowDecoder == Row + { preconditionFailure() } + + @available(*, unavailable, message: "Use request.observationForFirst() instead") + public static func trackingOne(_ request: Request) + -> ValueObservation + where Request.RowDecoder == Row + { preconditionFailure() } +} + +extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable { + @available(*, unavailable, renamed: "removeDuplicates") + public func distinctUntilChanged() -> ValueObservation> + { preconditionFailure() } +} + +extension ValueReducer where Value: Equatable { + @available(*, unavailable, renamed: "removeDuplicates") + public func distinctUntilChanged() -> ValueReducers.RemoveDuplicates + { preconditionFailure() } +} + #if SQLITE_HAS_CODEC extension Configuration { @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift index a53c64089..05ef992f6 100644 --- a/GRDB/ValueObservation/ValueObservation+Count.swift +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -64,38 +64,3 @@ extension TableRecord { return all().observationForCount() } } - -extension ValueObservation where Reducer == Void { - - // MARK: - Count Observation - - /// Creates a ValueObservation which observes *request*, and notifies its - /// count whenever it is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = ValueObservation.trackingCount(request) - /// - /// let observer = try observation.start(in: dbQueue) { count: Int in - /// print("Number of players has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForCount() instead") - public static func trackingCount(_ request: Request) - -> ValueObservation>> - { - return request.observationForCount() - } -} diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 298832ba5..5946ef3b4 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -124,107 +124,6 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: } } -extension ValueObservation where Reducer == Void { - - // MARK: - DatabaseValueConvertible Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: String.self) - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { names: [String] in - /// print("Player names have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForAll() instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { - return request.observationForAll() - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh value whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.select(max(Column("score")), as: Int.self) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { maxScore: Int? in - /// print("Maximum score has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForFirst() instead") - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { - return request.observationForFirst() - } - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: Optional.self) - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { names: [String?] in - /// print("Player names have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForAll() instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: _OptionalProtocol, - Request.RowDecoder._Wrapped: DatabaseValueConvertible - { - return request.observationForAll() - } -} - extension ValueReducers { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -332,18 +231,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.AllValues") -public typealias DatabaseValuesReducer = ValueReducers.AllValues - where RowDecoder: DatabaseValueConvertible - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.OneValue") -public typealias DatabaseValueReducer = ValueReducers.OneValue - where RowDecoder: DatabaseValueConvertible - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.AllOptionalValues") -public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues - where RowDecoder: DatabaseValueConvertible diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index f54b4cae5..75c82eea5 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -118,74 +118,6 @@ extension TableRecord where Self: FetchableRecord { } } -extension ValueObservation where Reducer == Void { - - // MARK: - FetchableRecord Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh records whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForAll() instead") - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: FetchableRecord - { - return request.observationForAll() - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh record whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.filter(key: 1) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { player: Player? in - /// print("Player has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForFirst() instead") - public static func trackingOne(_ request: Request) -> - ValueObservation> - where Request.RowDecoder: FetchableRecord - { - return request.observationForFirst() - } -} - extension ValueReducers { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -247,15 +179,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.AllRecords") -public typealias FetchableRecordsReducer - = ValueReducers.AllRecords - where RowDecoder: FetchableRecord - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.OneRecord") -public typealias FetchableRecordReducer - = ValueReducers.OneRecord - where RowDecoder: FetchableRecord diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index 43f748231..9a4a6a763 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -59,73 +59,6 @@ extension FetchRequest where RowDecoder == Row { } } -extension ValueObservation where Reducer == Void { - - // MARK: - Row Observation - - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh rows whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest(sql: "SELECT * FROM player") - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { rows: [Row] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForAll() instead") - public static func trackingAll(_ request: Request) - -> ValueObservation - where Request.RowDecoder == Row - { - return request.observationForAll() - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh row whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest(sql: "SELECT * FROM player WHERE id = ?", arguments: [1]) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { row: Row? in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - @available(*, deprecated, message: "Use request.observationForFirst() instead") - public static func trackingOne(_ request: Request) - -> ValueObservation - where Request.RowDecoder == Row - { - return request.observationForFirst() - } -} - extension ValueReducers { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -183,11 +116,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.AllRows") -public typealias RowsReducer = ValueReducers.AllRows - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.OneRow") -public typealias RowReducer = ValueReducers.OneRow diff --git a/GRDB/ValueObservation/ValueReducer/CompactMap.swift b/GRDB/ValueObservation/ValueReducer/CompactMap.swift index d0adb3620..00ed7eafd 100644 --- a/GRDB/ValueObservation/ValueReducer/CompactMap.swift +++ b/GRDB/ValueObservation/ValueReducer/CompactMap.swift @@ -44,7 +44,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.CompactMap") -public typealias CompactMapValueReducer = ValueReducers.CompactMap where Base: ValueReducer diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index 95cef1e14..0a4620ea8 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -20,7 +20,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.Fetch") -public typealias RawValueReducer = ValueReducers.Fetch diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index 5a5ef7796..2e1f1d7e9 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -47,7 +47,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.Map") -public typealias MapValueReducer = ValueReducers.Map where Base: ValueReducer diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index fbffa9efa..d7fd33a72 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -1,12 +1,4 @@ extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable { - /// Returns a ValueObservation which filters out consecutive equal values. - @available(*, deprecated, renamed: "removeDuplicates") - public func distinctUntilChanged() - -> ValueObservation> - { - return removeDuplicates() - } - /// Returns a ValueObservation which filters out consecutive equal values. public func removeDuplicates() -> ValueObservation> @@ -16,14 +8,6 @@ extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable } extension ValueReducer where Value: Equatable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns a ValueReducer which filters out consecutive equal values. - @available(*, deprecated, renamed: "removeDuplicates") - public func distinctUntilChanged() -> ValueReducers.RemoveDuplicates { - return removeDuplicates() - } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns a ValueReducer which filters out consecutive equal values. @@ -63,8 +47,3 @@ extension ValueReducers { } } } - -/// :nodoc: -@available(*, deprecated, renamed: "ValueReducers.RemoveDuplicates") -public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates - where Base: ValueReducer, Base.Value: Equatable diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 8d64788b6..708ee60d6 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -11,40 +11,6 @@ import XCTest #endif class ValueObservationCountTests: GRDBTestCase { - func testCountDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 5 - - struct T: TableRecord { } - let observation = ValueObservation.trackingCount(T.all()) - let observer = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 - try db.execute(sql: "UPDATE t SET id = id") // = - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "DELETE FROM t WHERE id = 1") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2, 3, 2]) - } - } - func testCount() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 6bf7e7ca1..bdeafd4ef 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -28,42 +28,6 @@ private struct Name: DatabaseValueConvertible { } class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { - func testAllDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Name]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = ValueObservation.trackingAll(SQLRequest(sql: "SELECT name FROM t ORDER BY id")) - let observer = try observation.start(in: dbQueue) { names in - results.append(names) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [ - [], - ["foo"], - ["foo", "bar"], - ["bar"]]) - } - } - func testAll() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } @@ -100,50 +64,6 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } } - func testOneDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Name?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 7 - - let observation = ValueObservation.trackingOne(SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC")) - let observer = try observation.start(in: dbQueue) { name in - results.append(name) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") - try db.inTransaction { - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'baz')") - try db.execute(sql: "UPDATE t SET name = NULL") - try db.execute(sql: "DELETE FROM t") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)") - try db.execute(sql: "UPDATE t SET name = 'qux'") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [ - nil, - "foo", - "bar", - nil, - "baz", - nil, - "qux"]) - } - } - func testOne() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } @@ -188,42 +108,6 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { } } - func testAllOptionalDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Name?]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = ValueObservation.trackingAll(SQLRequest(sql: "SELECT name FROM t ORDER BY id")) - let observer = try observation.start(in: dbQueue) { names in - results.append(names) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, NULL)") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map { $0?.rawValue }}, [ - [], - ["foo"], - ["foo", nil], - [nil]]) - } - } - func testAllOptional() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index b53bb44f5..11f332597 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -52,38 +52,6 @@ class ValueObservationFetchTests: GRDBTestCase { try test(makeDatabasePool()) } - func testDistinctUntilChangedDeprecated() throws { - func test(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }).distinctUntilChanged() - let observer = try observation.start(in: dbWriter) { count in - counts.append(count) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbWriter.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try db.execute(sql: "UPDATE t SET id = id") - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - func testRemoveDuplicated() throws { func test(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 8deae9f20..afd95067f 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -49,41 +49,6 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } } - func testOneRowWithPrefetchedRowsDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - - var results: [Row?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: Row.self) - let observation = ValueObservation.trackingOne(request) - let observer = try observation.start(in: dbQueue) { row in - results.append(row) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.count, 2) - - XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[0]!.prefetchedRows["children"], [ - ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], - ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) - - XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[1]!.prefetchedRows["children"], []) - } - } - func testOneRowWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() @@ -118,49 +83,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(results[1]!.prefetchedRows["children"], []) } } - - func testAllRowsWithPrefetchedRowsDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - - var results: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: Row.self) - let observation = ValueObservation.trackingAll(request) - let observer = try observation.start(in: dbQueue) { rows in - results.append(rows) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.count, 2) - - XCTAssertEqual(results[0].count, 2) - XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[0][0].prefetchedRows["children"], [ - ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], - ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) - XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"]) - XCTAssertEqual(results[0][1].prefetchedRows["children"], [ - ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) - - XCTAssertEqual(results[1].count, 2) - XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[1][0].prefetchedRows["children"], []) - XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"]) - XCTAssertEqual(results[1][1].prefetchedRows["children"], []) - } - } - + func testAllRowsWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() @@ -203,43 +126,6 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } } - func testOneRecordWithPrefetchedRowsDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - - var results: [ParentInfo?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: ParentInfo.self) - let observation = ValueObservation.trackingOne(request) - let observer = try observation.start(in: dbQueue) { parentInfo in - results.append(parentInfo) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ - ParentInfo( - parent: Parent(id: 1, name: "foo"), - children: [ - Child(id: 1, parentId: 1, name: "fooA"), - Child(id: 2, parentId: 1, name: "fooB"), - ]), - ParentInfo( - parent: Parent(id: 1, name: "foo"), - children: []), - ]) - } - } - func testOneRecordWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() @@ -277,55 +163,6 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } } - func testAllRecordsWithPrefetchedRowsDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - - var results: [[ParentInfo]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let request = Parent - .including(all: Parent.children.orderByPrimaryKey()) - .orderByPrimaryKey() - .asRequest(of: ParentInfo.self) - let observation = ValueObservation.trackingAll(request) - let observer = try observation.start(in: dbQueue) { parentInfos in - results.append(parentInfos) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ - [ - ParentInfo( - parent: Parent(id: 1, name: "foo"), - children: [ - Child(id: 1, parentId: 1, name: "fooA"), - Child(id: 2, parentId: 1, name: "fooB"), - ]), - ParentInfo( - parent: Parent(id: 2, name: "bar"), - children: [ - Child(id: 3, parentId: 2, name: "barA"), - ]), - ], - [ - ParentInfo( - parent: Parent(id: 1, name: "foo"), - children: []), - ParentInfo( - parent: Parent(id: 2, name: "bar"), - children: []), - ], - ]) - } - } - func testAllRecordsWithPrefetchedRows() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index a5e9b6e80..4de5c0ff3 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -26,42 +26,6 @@ private struct Player: TableRecord, FetchableRecord { } class ValueObservationRecordTests: GRDBTestCase { - func testAllDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Player]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = ValueObservation.trackingAll(SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - let observer = try observation.start(in: dbQueue) { players in - results.append(players) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map { $0.row }}, [ - [], - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) - } - } - func testAll() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } @@ -133,43 +97,7 @@ class ValueObservationRecordTests: GRDBTestCase { [["id":2, "name":"bar"]]]) } } - - func testOneDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Player?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = ValueObservation.trackingOne(SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC")) - let observer = try observation.start(in: dbQueue) { player in - results.append(player) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results.map { $0.map { $0.row }}, [ - nil, - ["id":1, "name":"foo"], - ["id":2, "name":"bar"], - nil]) - } - } - + func testOne() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index 4e3c8dc58..b152099b1 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -11,42 +11,6 @@ import XCTest #endif class ValueObservationRowTests: GRDBTestCase { - func testAllDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = ValueObservation.trackingAll(SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - let observer = try observation.start(in: dbQueue) { rows in - results.append(rows) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ - [], - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) - } - } - func testAll() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } @@ -83,42 +47,6 @@ class ValueObservationRowTests: GRDBTestCase { } } - func testOneDeprecated() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [Row?] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let observation = ValueObservation.trackingOne(SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC")) - let observer = try observation.start(in: dbQueue) { row in - results.append(row) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 - try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // = - try db.inTransaction { // +1 - try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')") - try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')") - try db.execute(sql: "DELETE FROM t WHERE id = 3") - return .commit - } - try db.execute(sql: "DELETE FROM t") // -1 - } - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [ - nil, - ["id":1, "name":"foo"], - ["id":2, "name":"bar"], - nil]) - } - func testOne() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } From 694adcec6436dd13c9e770770f7e9ac246387216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 18:03:11 +0100 Subject: [PATCH 09/12] Remove other deprecated methods --- GRDB/Fixit/GRDB-5.0.swift | 29 ++++++++++++++ .../Association/AssociationAggregate.swift | 34 ---------------- .../SQL/SQLExpression+QueryInterface.swift | 13 ------- ...QLSpecificExpressible+QueryInterface.swift | 39 ------------------- .../GRDBTests/CompilationProtocolTests.swift | 2 - 5 files changed, 29 insertions(+), 88 deletions(-) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 70a69aab6..b33d419d9 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -10,6 +10,16 @@ extension AnyFetchRequest { { preconditionFailure() } } +extension AssociationAggregate { + @available(*, unavailable, renamed: "forKey(_:)") + public func aliased(_ name: String) -> AssociationAggregate + { preconditionFailure() } + + @available(*, unavailable, renamed: "forKey(_:)") + public func aliased(_ key: CodingKey) -> AssociationAggregate + { preconditionFailure() } +} + extension DatabaseMigrator { @available(*, unavailable, renamed: "registerMigration(_:migrate:)") public mutating func registerMigrationWithDeferredForeignKeyCheck( @@ -54,6 +64,12 @@ extension FetchRequest { { preconditionFailure() } } +extension SQLExpression { + @available(*, unavailable, message: "Use SQLLiteral initializer instead") + public var sqlLiteral: SQLLiteral + { preconditionFailure() } +} + @available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") public struct SQLExpressionLiteral: SQLExpression { public var sql: String { preconditionFailure() } @@ -78,6 +94,19 @@ extension SQLLiteral { { preconditionFailure() } } +@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator") +typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator + +extension SQLSpecificExpressible { + @available(*, unavailable, renamed: "forKey(_:)") + public func aliased(_ name: String) -> SQLSelectable + { preconditionFailure() } + + @available(*, unavailable, renamed: "forKey(_:)") + public func aliased(_ key: CodingKey) -> SQLSelectable + { preconditionFailure() } +} + extension Statement { @available(*, unavailable, renamed: "setUncheckedArguments(_:)") public func unsafeSetArguments(_ arguments: StatementArguments) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index ef211815a..7ac1c68a0 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -71,20 +71,6 @@ public struct AssociationAggregate { } extension AssociationAggregate: KeyPathRefining { - /// Returns an aggregate that is selected in a column with the given name. - /// - /// For example: - /// - /// let aggregate = Author.books.count.aliased("numberOfBooks") - /// let request = Author.annotated(with: aggregate) - /// if let row = try Row.fetchOne(db, request) { - /// let numberOfBooks: Int = row["numberOfBooks"] - /// } - @available(*, deprecated, renamed: "forKey(_:)") - public func aliased(_ name: String) -> AssociationAggregate { - return forKey(name) - } - /// Returns an aggregate that is selected in a column with the given name. /// /// For example: @@ -98,26 +84,6 @@ extension AssociationAggregate: KeyPathRefining { return with(\.key, key) } - /// Returns an aggregate that is selected in a column named like the given - /// coding key. - /// - /// For example: - /// - /// struct AuthorInfo: Decodable, FetchableRecord { - /// var author: Author - /// var numberOfBooks: Int - /// - /// static func fetchAll(_ db: Database) throws -> [AuthorInfo] { - /// let aggregate = Author.books.count.aliased(CodingKeys.numberOfBooks) - /// let request = Author.annotated(with: aggregate) - /// return try AuthorInfo.fetchAll(db, request) - /// } - /// } - @available(*, deprecated, renamed: "forKey(_:)") - public func aliased(_ key: CodingKey) -> AssociationAggregate { - return forKey(key) - } - /// Returns an aggregate that is selected in a column named like the given /// coding key. /// diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 34e432094..3eefbf8bd 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -1,16 +1,6 @@ // MARK: - SQLExpression extension SQLExpression { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Converts an expression to an SQLLiteral - /// - /// :nodoc: - @available(*, deprecated, message: "Use SQLLiteral initializer instead") - public var sqlLiteral: SQLLiteral { - return SQLLiteral(self) - } - /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// /// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'"" @@ -243,9 +233,6 @@ public struct SQLAssociativeBinaryOperator: Hashable { } } -@available(*, deprecated, renamed: "SQLAssociativeBinaryOperator") -typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator - /// SQLExpressionBinary is an expression made of two expressions joined with a /// binary operator. /// diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index 8d6ce9af8..b1db8666d 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -39,22 +39,6 @@ extension SQLSpecificExpressible { /// :nodoc: extension SQLSpecificExpressible { - - /// Give the expression the given SQL name. - /// - /// For example: - /// - /// // SELECT (width * height) AS area FROM shape - /// let area = (Column("width") * Column("height")).aliased("area") - /// let request = Shape.select(area) - /// if let row = try Row.fetchOne(db, request) { - /// let area: Int = row["area"] - /// } - @available(*, deprecated, renamed: "forKey(_:)") - public func aliased(_ name: String) -> SQLSelectable { - return forKey(name) - } - /// Give the expression the given SQL name. /// /// For example: @@ -69,29 +53,6 @@ extension SQLSpecificExpressible { return SQLAliasedExpression(sqlExpression, name: key) } - /// Give the expression the same SQL name as the coding key. - /// - /// For example: - /// - /// struct Shape: Decodable, FetchableRecord, TableRecord { - /// let width: Int - /// let height: Int - /// let area: Int - /// - /// static let databaseSelection: [SQLSelectable] = [ - /// Column(CodingKeys.width), - /// Column(CodingKeys.height), - /// (Column(CodingKeys.width) * Column(CodingKeys.height)).aliased(CodingKeys.area), - /// ] - /// } - /// - /// // SELECT width, height, (width * height) AS area FROM shape - /// let shapes: [Shape] = try Shape.fetchAll(db) - @available(*, deprecated, renamed: "forKey(_:)") - public func aliased(_ key: CodingKey) -> SQLSelectable { - return forKey(key) - } - /// Give the expression the same SQL name as the coding key. /// /// For example: diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 27bfa05e5..5771f8212 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -110,8 +110,6 @@ private class UserPersistableRecord2 : PersistableRecord { private struct UserRowRequest : FetchRequest { struct CustomType { } typealias RowDecoder = CustomType - // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { preconditionFailure() } } From 41e0885bceba5a5dde6c97b77c50a9e98d740649 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 18:10:02 +0100 Subject: [PATCH 10/12] Fix deprecation warning --- Tests/GRDBTests/DatabaseConfigurationTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 896d81323..7566b7e49 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -176,7 +176,7 @@ class DatabaseConfigurationTests: GRDBTestCase { let s1 = DispatchSemaphore(value: 0) let s2 = DispatchSemaphore(value: 0) - let queue = DispatchQueue.global(priority: .default) + let queue = DispatchQueue.global(qos: .default) let group = DispatchGroup() queue.async(group: group) { From 00b0dc2a047c34390e14b809aa798fc03348205a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 19:08:15 +0100 Subject: [PATCH 11/12] Remove availability checks for macOS 10.10 (forgotten in #719) --- GRDB/Core/Configuration.swift | 13 +- GRDB/Core/Database.swift | 48 --- GRDB/Core/DatabaseError.swift | 11 - GRDB/Core/DatabasePool.swift | 5 +- GRDB/Core/DatabaseQueue.swift | 10 +- GRDB/Core/DatabaseReader.swift | 6 +- GRDB/FTS/FTS3Pattern.swift | 44 --- GRDB/FTS/FTS3TokenizerDescriptor.swift | 40 --- GRDB/FTS/FTS4.swift | 26 -- .../Schema/TableDefinition.swift | 166 --------- README.md | 2 +- Tests/GRDBTests/DatabaseErrorTests.swift | 45 +-- Tests/GRDBTests/DatabaseMigratorTests.swift | 9 +- Tests/GRDBTests/DatabasePoolBackupTests.swift | 1 - .../DatabasePoolConcurrencyTests.swift | 156 +++++---- Tests/GRDBTests/DatabaseTests.swift | 8 - Tests/GRDBTests/FTS3PatternTests.swift | 18 - Tests/GRDBTests/FTS3TableBuilderTests.swift | 24 -- Tests/GRDBTests/FTS3TokenizerTests.swift | 24 -- Tests/GRDBTests/FTS4TableBuilderTests.swift | 31 +- Tests/GRDBTests/PoolTests.swift | 320 +++++++++--------- Tests/GRDBTests/TableDefinitionTests.swift | 31 +- .../ValueObservationSchedulingTests.swift | 1 - Tests/GRDBTests/VirtualTableModuleTests.swift | 16 - 24 files changed, 265 insertions(+), 790 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index a84df3197..254cf80dd 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -181,8 +181,8 @@ public struct Configuration { /// /// The quality of service is ignored if you supply a target queue. /// - /// Default: .default (.unspecified on macOS < 10.10) - public var qos: DispatchQoS + /// Default: .default + public var qos: DispatchQoS = .default /// The target queue for all database accesses. /// @@ -200,14 +200,7 @@ public struct Configuration { // MARK: - Factory Configuration /// Creates a factory configuration - public init() { - if #available(OSX 10.10, *) { - qos = .default - } else { - qos = .unspecified - } - } - + public init() { } // MARK: - Not Public diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index de9da985b..02abfcf55 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -423,48 +423,6 @@ public final class Database { } private static func closeConnection(_ sqliteConnection: SQLiteConnection) { - // sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER - closeConnection_v2(sqliteConnection, sqlite3_close_v2) - #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { - closeConnection_v2(sqliteConnection, sqlite3_close_v2) - } else { - closeConnection_v1(sqliteConnection) - } - #endif - } - - private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) { - // https://www.sqlite.org/c3ref/close.html - // > If the database connection is associated with unfinalized prepared - // > statements or unfinished sqlite3_backup objects then - // > sqlite3_close() will leave the database connection open and - // > return SQLITE_BUSY. - let code = sqlite3_close(sqliteConnection) - if code != SQLITE_OK, let log = logError { - // A rare situation where GRDB doesn't fatalError on - // unprocessed errors. - let message = String(cString: sqlite3_errmsg(sqliteConnection)) - log(ResultCode(rawValue: code), "could not close database: \(message)") - if code == SQLITE_BUSY { - // Let the user know about unfinalized statements that did - // prevent the connection from closing properly. - var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil) - while stmt != nil { - log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))") - stmt = sqlite3_next_stmt(sqliteConnection, stmt) - } - } - } - } - - private static func closeConnection_v2( - _ sqliteConnection: SQLiteConnection, - _ sqlite3_close_v2: @convention(c) (OpaquePointer?) -> Int32) - { // https://www.sqlite.org/c3ref/close.html // > If sqlite3_close_v2() is called with unfinalized prepared // > statements and/or unfinished sqlite3_backups, then the database @@ -545,9 +503,6 @@ public final class Database { func beginReadOnly() throws { if configuration.readonly { return } if _readOnlyDepth == 0 { - // PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute() } _readOnlyDepth += 1 @@ -557,9 +512,6 @@ public final class Database { if configuration.readonly { return } _readOnlyDepth -= 1 if _readOnlyDepth == 0 { - // PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 10b04be4c..3d2caea51 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -159,18 +159,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { // CustomStringConvertible extension ResultCode { var errorString: String? { - // sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER return String(cString: sqlite3_errstr(rawValue)) - #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { - return String(cString: sqlite3_errstr(rawValue)) - } else { - return nil - } - #endif } /// :nodoc: diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 1143bdbf8..09073e356 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -365,9 +365,8 @@ extension DatabasePool: DatabaseReader { /// } /// } /// - /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and - /// SQLCipher), attempts to write in the database from this method throw a - /// DatabaseError of resultCode `SQLITE_READONLY`. + /// Attempts to write in the database from this method throw a DatabaseError + /// of resultCode `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. public func asyncRead(_ block: @escaping (Result) -> Void) { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b157f5b2d..50f3e3cf5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -189,9 +189,8 @@ extension DatabaseQueue { /// /// This method is *not* reentrant. /// - /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and - /// SQLCipher), attempts to write in the database from this method throw a - /// DatabaseError of resultCode `SQLITE_READONLY`. + /// Attempts to write in the database from this method throw a DatabaseError + /// of resultCode `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. @@ -212,9 +211,8 @@ extension DatabaseQueue { /// } /// } /// - /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and - /// SQLCipher), attempts to write in the database from this method throw a - /// DatabaseError of resultCode `SQLITE_READONLY`. + /// Attempts to write in the database from this method throw a DatabaseError + /// of resultCode `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. public func asyncRead(_ block: @escaping (Result) -> Void) { diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ed094b23a..f1dbfa8e9 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -107,8 +107,7 @@ public protocol DatabaseReader: AnyObject { /// let count = try Player.fetchCount(db) /// } /// - /// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds - /// and SQLCipher, attempts to write in the database throw a DatabaseError + /// Guarantee 2: attempts to write in the database throw a DatabaseError /// whose resultCode is `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. @@ -134,8 +133,7 @@ public protocol DatabaseReader: AnyObject { /// } /// } /// - /// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds - /// and SQLCipher, attempts to write in the database throw a DatabaseError + /// Guarantee 2: attempts to write in the database throw a DatabaseError /// whose resultCode is `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 4859285ee..47bf9f454 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -31,7 +31,6 @@ public struct FTS3Pattern { self.rawPattern = rawPattern } - #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a pattern that matches any token found in the input string; /// returns nil if no pattern could be built. /// @@ -70,49 +69,6 @@ public struct FTS3Pattern { guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } - #else - /// Creates a pattern that matches any token found in the input string; - /// returns nil if no pattern could be built. - /// - /// FTS3Pattern(matchingAnyTokenIn: "") // nil - /// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar - /// - /// - parameter string: The string to turn into an FTS3 pattern - @available(OSX 10.10, *) - public init?(matchingAnyTokenIn string: String) { - let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) - guard !tokens.isEmpty else { return nil } - 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. - /// - /// FTS3Pattern(matchingAllTokensIn: "") // nil - /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar - /// - /// - parameter string: The string to turn into an FTS3 pattern - @available(OSX 10.10, *) - public init?(matchingAllTokensIn string: String) { - let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) - guard !tokens.isEmpty else { return nil } - try? self.init(rawPattern: tokens.joined(separator: " ")) - } - - /// Creates a pattern that matches a contiguous string; returns nil if no - /// pattern could be built. - /// - /// FTS3Pattern(matchingPhrase: "") // nil - /// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar" - /// - /// - parameter string: The string to turn into an FTS3 pattern - @available(OSX 10.10, *) - public init?(matchingPhrase string: String) { - let tokens = FTS3TokenizerDescriptor.simple.tokenize(string) - guard !tokens.isEmpty else { return nil } - try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") - } - #endif } extension FTS3Pattern: DatabaseValueConvertible { diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 8f4f6a401..06bbd0259 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -32,7 +32,6 @@ public struct FTS3TokenizerDescriptor { /// See https://www.sqlite.org/fts3.html#tokenizer public static let porter = FTS3TokenizerDescriptor("porter") - #if GRDBCUSTOMSQLITE || GRDBCIPHER /// The "unicode61" tokenizer. /// /// db.create(virtualTable: "book", using: FTS4()) { t in @@ -56,35 +55,6 @@ public struct FTS3TokenizerDescriptor { { return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } - #else - /// The "unicode61" tokenizer. - /// - /// db.create(virtualTable: "book", using: FTS4()) { t in - /// t.tokenizer = .unicode61() - /// } - /// - /// - parameters: - /// - diacritics: By default SQLite will strip diacritics from - /// latin characters. - /// - 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 https://www.sqlite.org/fts3.html#tokenizer - @available(OSX 10.10, *) - public static func unicode61( - diacritics: FTS3.Diacritics = .removeLegacy, - separators: Set = [], - tokenCharacters: Set = []) - -> FTS3TokenizerDescriptor - { - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) - } - #endif private static func _unicode61( diacritics: FTS3.Diacritics, @@ -118,24 +88,14 @@ public struct FTS3TokenizerDescriptor { return FTS3TokenizerDescriptor("unicode61", arguments: arguments) } - #if GRDBCUSTOMSQLITE || GRDBCIPHER func tokenize(_ string: String) -> [String] { return _tokenize(string) } - #else - @available(OSX 10.10, *) - func tokenize(_ string: String) -> [String] { - return _tokenize(string) - } - #endif /// Returns an array of tokens found in the string argument. /// /// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"] private func _tokenize(_ string: String) -> [String] { - // fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) return DatabaseQueue().inDatabase { db in var tokenizerChunks: [String] = [] tokenizerChunks.append(name) diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 29cfc4b85..7eae77947 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -261,7 +261,6 @@ public final class FTS4ColumnDefinition { self.isLanguageId = false } - #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Excludes the column from the full-text index. /// /// try db.create(virtualTable: "document", using: FTS4()) { t in @@ -272,36 +271,11 @@ public final class FTS4ColumnDefinition { /// See https://www.sqlite.org/fts3.html#the_notindexed_option /// /// - returns: Self so that you can further refine the column definition. - /// :nodoc: @discardableResult public func notIndexed() -> Self { - // notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) self.isIndexed = false return self } - #else - /// Excludes the column from the full-text index. - /// - /// try db.create(virtualTable: "document", using: FTS4()) { t in - /// t.column("a") - /// t.column("b").notIndexed() - /// } - /// - /// See https://www.sqlite.org/fts3.html#the_notindexed_option - /// - /// - returns: Self so that you can further refine the column definition. - @available(OSX 10.10, *) - @discardableResult - public func notIndexed() -> Self { - // notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - self.isIndexed = false - return self - } - #endif /// Uses the column as the Int32 language id hidden column. /// diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 76be73766..2a1881123 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -2,7 +2,6 @@ extension Database { // MARK: - Database Schema - #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a database table. /// /// try db.create(table: "place") { t in @@ -42,88 +41,6 @@ extension Database { let sql = try definition.sql(self) try execute(sql: sql) } - #else - /// Creates a database table. - /// - /// try db.create(table: "place") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("title", .text) - /// t.column("favorite", .boolean).notNull().default(false) - /// t.column("longitude", .double).notNull() - /// t.column("latitude", .double).notNull() - /// } - /// - /// See https://www.sqlite.org/lang_createtable.html and - /// https://www.sqlite.org/withoutrowid.html - /// - /// - parameters: - /// - name: The table name. - /// - temporary: If true, creates a temporary table. - /// - ifNotExists: If false (the default), an error is thrown if the - /// table already exists. Otherwise, the table is created unless it - /// already exists. - /// - withoutRowID: If true, uses WITHOUT ROWID optimization. - /// - body: A closure that defines table columns and constraints. - /// - throws: A DatabaseError whenever an SQLite error occurs. - @available(OSX 10.10, *) - public func create( - table name: String, - temporary: Bool = false, - ifNotExists: Bool = false, - withoutRowID: Bool, - body: (TableDefinition) -> Void) - throws - { - // WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = TableDefinition( - name: name, - temporary: temporary, - ifNotExists: ifNotExists, - withoutRowID: withoutRowID) - body(definition) - let sql = try definition.sql(self) - try execute(sql: sql) - } - - /// Creates a database table. - /// - /// try db.create(table: "place") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("title", .text) - /// t.column("favorite", .boolean).notNull().default(false) - /// t.column("longitude", .double).notNull() - /// t.column("latitude", .double).notNull() - /// } - /// - /// See https://www.sqlite.org/lang_createtable.html - /// - /// - parameters: - /// - name: The table name. - /// - temporary: If true, creates a temporary table. - /// - ifNotExists: If false (the default), an error is thrown if the - /// table already exists. Otherwise, the table is created unless it - /// already exists. - /// - body: A closure that defines table columns and constraints. - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create( - table name: String, - temporary: Bool = false, - ifNotExists: Bool = false, - body: (TableDefinition) -> Void) - throws - { - let definition = TableDefinition( - name: name, - temporary: temporary, - ifNotExists: ifNotExists, - withoutRowID: false) - body(definition) - let sql = try definition.sql(self) - try execute(sql: sql) - } - #endif /// Renames a database table. /// @@ -162,7 +79,6 @@ extension Database { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } - #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates an index. /// /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) @@ -192,9 +108,6 @@ extension Database { condition: SQLExpressible? = nil) throws { - // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) let definition = IndexDefinition( name: name, table: table, @@ -205,85 +118,6 @@ extension Database { let sql = definition.sql() try execute(sql: sql) } - #else - /// Creates an index. - /// - /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) - /// - /// SQLite can also index expressions (https://www.sqlite.org/expridx.html) - /// and use specific collations. To create such an index, use a raw SQL - /// query. - /// - /// try db.execute(sql: "CREATE INDEX ...") - /// - /// See https://www.sqlite.org/lang_createindex.html - /// - /// - parameters: - /// - name: The index name. - /// - table: The name of the indexed table. - /// - columns: The indexed columns. - /// - unique: If true, creates a unique index. - /// - ifNotExists: If false, no error is thrown if index already exists. - public func create( - index name: String, - on table: String, - columns: [String], - unique: Bool = false, - ifNotExists: Bool = false) - throws - { - // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition( - name: name, - table: table, - columns: columns, - unique: unique, - ifNotExists: ifNotExists, - condition: nil) - let sql = definition.sql() - try execute(sql: sql) - } - - /// Creates a partial index. - /// - /// try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil) - /// - /// See https://www.sqlite.org/lang_createindex.html, and - /// https://www.sqlite.org/partialindex.html - /// - /// - parameters: - /// - name: The index name. - /// - table: The name of the indexed table. - /// - columns: The indexed columns. - /// - unique: If true, creates a unique index. - /// - ifNotExists: If false, no error is thrown if index already exists. - /// - condition: The condition that indexed rows must verify. - @available(OSX 10.10, *) - public func create( - index name: String, - on table: String, - columns: [String], - unique: Bool = false, - ifNotExists: Bool = false, - condition: SQLExpressible) - throws - { - // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition( - name: name, - table: table, - columns: columns, - unique: unique, - ifNotExists: ifNotExists, - condition: condition.sqlExpression) - let sql = definition.sql() - try execute(sql: sql) - } - #endif /// Deletes a database index. /// diff --git a/README.md b/README.md index 74203a591..aae6b2849 100644 --- a/README.md +++ b/README.md @@ -1742,7 +1742,7 @@ When the same query will be used several times in the lifetime of your applicati **Don't cache statements yourself.** -> :point_up: **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement. On systems earlier than OSX 10.10 that don't have the [sqlite3_close_v2 function](https://www.sqlite.org/c3ref/close.html), SQLite connections won't close properly if statements have been kept alive. +> :point_up: **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement. Instead, use the `cachedUpdateStatement` and `cachedSelectStatement` methods. GRDB does all the hard caching and [memory management](#memory-management) stuff for you: diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index ddd9d65a3..dad1adaa1 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -8,14 +8,11 @@ import XCTest class DatabaseErrorTests: GRDBTestCase { func testDatabaseErrorMessage() { - // Error messages are not always available - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { - // We don't test for actual messages, since they may depend on SQLite version - XCTAssertEqual(DatabaseError().resultCode, .SQLITE_ERROR) - XCTAssertNotNil(DatabaseError().message) - XCTAssertNotNil(DatabaseError(resultCode: .SQLITE_BUSY).message) - XCTAssertNotEqual(DatabaseError().message, DatabaseError(resultCode: .SQLITE_BUSY).message) - } + // We don't test for actual messages, since they may depend on SQLite version + XCTAssertEqual(DatabaseError().resultCode, .SQLITE_ERROR) + XCTAssertNotNil(DatabaseError().message) + XCTAssertNotNil(DatabaseError(resultCode: .SQLITE_BUSY).message) + XCTAssertNotEqual(DatabaseError().message, DatabaseError(resultCode: .SQLITE_BUSY).message) } func testDatabaseErrorInTransaction() throws { @@ -30,9 +27,7 @@ class DatabaseErrorTests: GRDBTestCase { return .commit } } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") @@ -67,9 +62,7 @@ class DatabaseErrorTests: GRDBTestCase { } } } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") @@ -90,9 +83,7 @@ class DatabaseErrorTests: GRDBTestCase { try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"]) XCTFail() } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") @@ -107,9 +98,7 @@ class DatabaseErrorTests: GRDBTestCase { try statement.execute(arguments: [1, "Bobby"]) XCTFail() } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") @@ -125,9 +114,7 @@ class DatabaseErrorTests: GRDBTestCase { try statement.execute() XCTFail() } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") @@ -147,9 +134,7 @@ class DatabaseErrorTests: GRDBTestCase { """) XCTFail() } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')") @@ -166,9 +151,7 @@ class DatabaseErrorTests: GRDBTestCase { do { try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)") } catch let error as DatabaseError { - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode.rawValue, 19) // primary SQLITE_CONSTRAINT } } @@ -184,9 +167,7 @@ class DatabaseErrorTests: GRDBTestCase { } catch let error as NSError { XCTAssertEqual(DatabaseError.errorDomain, "GRDB.DatabaseError") XCTAssertEqual(error.domain, DatabaseError.errorDomain) - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert([19, 787].contains(error.code)) + XCTAssertEqual(error.code, 787) } } } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 4523554dc..f7ab80fa5 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -159,9 +159,7 @@ class DatabaseMigratorTests : GRDBTestCase { // The first migration should be committed. // The second migration should be rollbacked. - // SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version @@ -173,11 +171,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testForeignKeyViolation() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)") diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 29acdc2e4..6853dd2e1 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -36,7 +36,6 @@ class DatabasePoolBackupTests: GRDBTestCase { } // TODO: fix flaky test -// @available(OSX 10.10, *) // func testConcurrentWriteDuringBackup() throws { // let source = try makeDatabasePool(filename: "source.sqlite") // let destination = try makeDatabasePool(filename: "destination.sqlite") diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 1308a0862..5611042e2 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1185,91 +1185,87 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // MARK: - Barrier func testBarrierLocksReads() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - } - var fetchedValue: Int? - let s1 = DispatchSemaphore(value: 0) - let s2 = DispatchSemaphore(value: 0) - let s3 = DispatchSemaphore(value: 0) - - DispatchQueue.global().async { - try! dbPool.barrierWriteWithoutTransaction { db in - try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") - s1.signal() - s2.wait() - } - } - - DispatchQueue.global().async { - // Wait for barrier to start - s1.wait() - - fetchedValue = try! dbPool.read { db in - try Int.fetchOne(db, sql: "SELECT id FROM items")! - } - expectation.fulfill() - s3.signal() - } - - // Assert that read is blocked - waitForExpectations(timeout: 1) - - // Release barrier - s2.signal() - - // Wait for read to complete - s3.wait() - XCTAssertEqual(fetchedValue, 1) + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") } + var fetchedValue: Int? + let s1 = DispatchSemaphore(value: 0) + let s2 = DispatchSemaphore(value: 0) + let s3 = DispatchSemaphore(value: 0) + + DispatchQueue.global().async { + try! dbPool.barrierWriteWithoutTransaction { db in + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + s1.signal() + s2.wait() + } + } + + DispatchQueue.global().async { + // Wait for barrier to start + s1.wait() + + fetchedValue = try! dbPool.read { db in + try Int.fetchOne(db, sql: "SELECT id FROM items")! + } + expectation.fulfill() + s3.signal() + } + + // Assert that read is blocked + waitForExpectations(timeout: 1) + + // Release barrier + s2.signal() + + // Wait for read to complete + s3.wait() + XCTAssertEqual(fetchedValue, 1) } func testBarrierIsLockedByOneUnfinishedRead() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - } - - let s1 = DispatchSemaphore(value: 0) - let s2 = DispatchSemaphore(value: 0) - let s3 = DispatchSemaphore(value: 0) - let s4 = DispatchSemaphore(value: 0) - - DispatchQueue.global().async { - try! dbPool.read { _ in - s1.signal() - s2.signal() - s3.wait() - } - } - - DispatchQueue.global().async { - // Wait for read to start - s1.wait() - - dbPool.barrierWriteWithoutTransaction { _ in } - expectation.fulfill() - s4.signal() - } - - // Assert that barrier is blocked - waitForExpectations(timeout: 1) - - // Release read - s3.signal() - - // Wait for barrier to complete - s4.wait() + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") } + + let s1 = DispatchSemaphore(value: 0) + let s2 = DispatchSemaphore(value: 0) + let s3 = DispatchSemaphore(value: 0) + let s4 = DispatchSemaphore(value: 0) + + DispatchQueue.global().async { + try! dbPool.read { _ in + s1.signal() + s2.signal() + s3.wait() + } + } + + DispatchQueue.global().async { + // Wait for read to start + s1.wait() + + dbPool.barrierWriteWithoutTransaction { _ in } + expectation.fulfill() + s4.signal() + } + + // Assert that barrier is blocked + waitForExpectations(timeout: 1) + + // Release read + s3.signal() + + // Wait for barrier to complete + s4.wait() } // MARK: - Concurrent opening diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index f2c7e5d10..6a2f928fa 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -266,14 +266,6 @@ class DatabaseTests : GRDBTestCase { } func testFailedCommitIsRollbacked() throws { - // PRAGMA defer_foreign_keys = ON was introduced in SQLite 3.12.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE parent (id INTEGER PRIMARY KEY)") diff --git a/Tests/GRDBTests/FTS3PatternTests.swift b/Tests/GRDBTests/FTS3PatternTests.swift index 8109a451c..39bcbf3c3 100644 --- a/Tests/GRDBTests/FTS3PatternTests.swift +++ b/Tests/GRDBTests/FTS3PatternTests.swift @@ -70,12 +70,6 @@ class FTS3PatternTests: GRDBTestCase { } func testFTS3PatternWithAnyToken() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"] for string in wrongInputs { if let pattern = FTS3Pattern(matchingAnyTokenIn: string) { @@ -106,12 +100,6 @@ class FTS3PatternTests: GRDBTestCase { } func testFTS3PatternWithAllTokens() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"] for string in wrongInputs { if let pattern = FTS3Pattern(matchingAllTokensIn: string) { @@ -142,12 +130,6 @@ class FTS3PatternTests: GRDBTestCase { } func testFTS3PatternWithPhrase() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"] for string in wrongInputs { if let pattern = FTS3Pattern(matchingPhrase: string) { diff --git a/Tests/GRDBTests/FTS3TableBuilderTests.swift b/Tests/GRDBTests/FTS3TableBuilderTests.swift index 97665379f..0a0bd4a11 100644 --- a/Tests/GRDBTests/FTS3TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS3TableBuilderTests.swift @@ -61,12 +61,6 @@ class FTS3TableBuilderTests: GRDBTestCase { } func testUnicode61Tokenizer() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in @@ -77,12 +71,6 @@ class FTS3TableBuilderTests: GRDBTestCase { } func testUnicode61TokenizerDiacriticsKeep() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in @@ -105,12 +93,6 @@ class FTS3TableBuilderTests: GRDBTestCase { #endif func testUnicode61TokenizerSeparators() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in @@ -121,12 +103,6 @@ class FTS3TableBuilderTests: GRDBTestCase { } func testUnicode61TokenizerTokenCharacters() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in diff --git a/Tests/GRDBTests/FTS3TokenizerTests.swift b/Tests/GRDBTests/FTS3TokenizerTests.swift index a9adb35a1..fc7fd79d6 100644 --- a/Tests/GRDBTests/FTS3TokenizerTests.swift +++ b/Tests/GRDBTests/FTS3TokenizerTests.swift @@ -58,12 +58,6 @@ class FTS3TokenizerTests: GRDBTestCase { } func testUnicode61Tokenizer() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in @@ -85,12 +79,6 @@ class FTS3TokenizerTests: GRDBTestCase { } func testUnicode61TokenizerDiacriticsKeep() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in @@ -135,12 +123,6 @@ class FTS3TokenizerTests: GRDBTestCase { #endif func testUnicode61TokenizerSeparators() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in @@ -155,12 +137,6 @@ class FTS3TokenizerTests: GRDBTestCase { } func testUnicode61TokenizerTokenCharacters() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS3()) { t in diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index 4069ca0a1..d5254d193 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -61,12 +61,6 @@ class FTS4TableBuilderTests: GRDBTestCase { } func testUnicode61Tokenizer() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in @@ -77,12 +71,6 @@ class FTS4TableBuilderTests: GRDBTestCase { } func testUnicode61TokenizerDiacriticsKeep() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in @@ -92,6 +80,7 @@ class FTS4TableBuilderTests: GRDBTestCase { } } + // TODO: why only custom SQLite build? #if GRDBCUSTOMSQLITE func testUnicode61TokenizerDiacriticsRemove() throws { let dbQueue = try makeDatabaseQueue() @@ -105,12 +94,6 @@ class FTS4TableBuilderTests: GRDBTestCase { #endif func testUnicode61TokenizerSeparators() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in @@ -121,12 +104,6 @@ class FTS4TableBuilderTests: GRDBTestCase { } func testUnicode61TokenizerTokenCharacters() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in @@ -156,12 +133,6 @@ class FTS4TableBuilderTests: GRDBTestCase { } func testNotIndexedColumns() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "books", using: FTS4()) { t in diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index a6e8eeacd..7f23da544 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -67,188 +67,178 @@ class PoolTests: XCTestCase { } func testBarrierLocksElements() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let pool = makeCounterPool(maximumCount: 1) - var element: Int? - let s1 = DispatchSemaphore(value: 0) - let s2 = DispatchSemaphore(value: 0) - let s3 = DispatchSemaphore(value: 0) - - DispatchQueue.global().async { - pool.barrier { - s1.signal() - s2.wait() - } + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let pool = makeCounterPool(maximumCount: 1) + var element: Int? + let s1 = DispatchSemaphore(value: 0) + let s2 = DispatchSemaphore(value: 0) + let s3 = DispatchSemaphore(value: 0) + + DispatchQueue.global().async { + pool.barrier { + s1.signal() + s2.wait() } - - DispatchQueue.global().async { - // Wait for barrier to start - s1.wait() - - let first = try! pool.get() - element = first.element - first.release() - expectation.fulfill() - s3.signal() - } - - // Assert that get() is blocked - waitForExpectations(timeout: 1) - - // Release barrier - s2.signal() - - // Wait for get() to complete - s3.wait() - XCTAssertEqual(element, 1) } + + DispatchQueue.global().async { + // Wait for barrier to start + s1.wait() + + let first = try! pool.get() + element = first.element + first.release() + expectation.fulfill() + s3.signal() + } + + // Assert that get() is blocked + waitForExpectations(timeout: 1) + + // Release barrier + s2.signal() + + // Wait for get() to complete + s3.wait() + XCTAssertEqual(element, 1) } func testBarrierIsLockedByOneUsedElementOutOfOne() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let pool = makeCounterPool(maximumCount: 1) - - // Get element - let first = try pool.get() - XCTAssertEqual(first.element, 1) - - let s = DispatchSemaphore(value: 0) - DispatchQueue.global().async { - pool.barrier { } - expectation.fulfill() - s.signal() - } - - // Assert that barrier is blocked - waitForExpectations(timeout: 1) - - // Release element - first.release() - - // Wait for barrier to complete - s.wait() - - // Get and release recycled element - let second = try pool.get() - XCTAssertEqual(second.element, 1) - second.release() + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let pool = makeCounterPool(maximumCount: 1) + + // Get element + let first = try pool.get() + XCTAssertEqual(first.element, 1) + + let s = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + pool.barrier { } + expectation.fulfill() + s.signal() } + + // Assert that barrier is blocked + waitForExpectations(timeout: 1) + + // Release element + first.release() + + // Wait for barrier to complete + s.wait() + + // Get and release recycled element + let second = try pool.get() + XCTAssertEqual(second.element, 1) + second.release() } func testBarrierIsLockedByOneUsedElementOutOfTwo() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let pool = makeCounterPool(maximumCount: 2) - - // Get elements - let first = try pool.get() - XCTAssertEqual(first.element, 1) - let second = try pool.get() - XCTAssertEqual(second.element, 2) - - // Release first element - first.release() - - let s = DispatchSemaphore(value: 0) - DispatchQueue.global().async { - pool.barrier { } - expectation.fulfill() - s.signal() - } - - // Assert that barrier is blocked - waitForExpectations(timeout: 1) - - // Release second element - second.release() - - // Wait for barrier to complete - s.wait() - - // Get and release recycled element - let third = try pool.get() - XCTAssertEqual(third.element, 1) - third.release() + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let pool = makeCounterPool(maximumCount: 2) + + // Get elements + let first = try pool.get() + XCTAssertEqual(first.element, 1) + let second = try pool.get() + XCTAssertEqual(second.element, 2) + + // Release first element + first.release() + + let s = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + pool.barrier { } + expectation.fulfill() + s.signal() } + + // Assert that barrier is blocked + waitForExpectations(timeout: 1) + + // Release second element + second.release() + + // Wait for barrier to complete + s.wait() + + // Get and release recycled element + let third = try pool.get() + XCTAssertEqual(third.element, 1) + third.release() } func testBarrierIsLockedByTwoUsedElementsOutOfTwo() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let pool = makeCounterPool(maximumCount: 2) - - // Get elements - let first = try pool.get() - XCTAssertEqual(first.element, 1) - let second = try pool.get() - XCTAssertEqual(second.element, 2) - - let s = DispatchSemaphore(value: 0) - DispatchQueue.global().async { - pool.barrier { } - expectation.fulfill() - s.signal() - } - - // Assert that barrier is blocked - waitForExpectations(timeout: 1) - - // Release elements - first.release() - second.release() - - // Wait for barrier to complete - s.wait() - - // Get and release recycled element - let third = try pool.get() - XCTAssertEqual(third.element, 1) - third.release() + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let pool = makeCounterPool(maximumCount: 2) + + // Get elements + let first = try pool.get() + XCTAssertEqual(first.element, 1) + let second = try pool.get() + XCTAssertEqual(second.element, 2) + + let s = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + pool.barrier { } + expectation.fulfill() + s.signal() } + + // Assert that barrier is blocked + waitForExpectations(timeout: 1) + + // Release elements + first.release() + second.release() + + // Wait for barrier to complete + s.wait() + + // Get and release recycled element + let third = try pool.get() + XCTAssertEqual(third.element, 1) + third.release() } func testBarrierRemoveAll() throws { - if #available(OSX 10.10, *) { - let expectation = self.expectation(description: "lock") - expectation.isInverted = true - - let pool = makeCounterPool(maximumCount: 1) - - // Get element - let first = try pool.get() - XCTAssertEqual(first.element, 1) - - let s = DispatchSemaphore(value: 0) - DispatchQueue.global().async { - // No deadlock - pool.barrier { pool.removeAll() } - expectation.fulfill() - s.signal() - } - - // Assert that barrier is blocked - waitForExpectations(timeout: 1) - - // Release element - first.release() - - // Wait for barrier to complete - s.wait() - - // Get and release new element - let second = try pool.get() - XCTAssertEqual(second.element, 2) - second.release() + let expectation = self.expectation(description: "lock") + expectation.isInverted = true + + let pool = makeCounterPool(maximumCount: 1) + + // Get element + let first = try pool.get() + XCTAssertEqual(first.element, 1) + + let s = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + // No deadlock + pool.barrier { pool.removeAll() } + expectation.fulfill() + s.signal() } + + // Assert that barrier is blocked + waitForExpectations(timeout: 1) + + // Release element + first.release() + + // Wait for barrier to complete + s.wait() + + // Get and release new element + let second = try pool.get() + XCTAssertEqual(second.element, 2) + second.release() } } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 54e7c152d..e86035000 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -35,25 +35,14 @@ class TableDefinitionTests: GRDBTestCase { func testTableCreationOptions() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - if #available(iOS 8.2, OSX 10.10, *) { - try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in - t.column("id", .integer).primaryKey() - } - assertEqualSQL( - lastSQLQuery, - ("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" + - "\"id\" INTEGER PRIMARY KEY" + - ") WITHOUT ROWID") as String) - } else { - try db.create(table: "test", temporary: true, ifNotExists: true) { t in - t.column("id", .integer).primaryKey() - } - assertEqualSQL( - lastSQLQuery, - ("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" + - "\"id\" INTEGER PRIMARY KEY" + - ")") as String) + try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in + t.column("id", .integer).primaryKey() } + assertEqualSQL( + lastSQLQuery, + ("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" + + "\"id\" INTEGER PRIMARY KEY" + + ") WITHOUT ROWID") as String) } } @@ -568,12 +557,6 @@ class TableDefinitionTests: GRDBTestCase { } func testCreatePartialIndex() throws { - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index af898fbe8..af010e799 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -50,7 +50,6 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - @available(OSX 10.10, *) // DispatchQueue qos func testMainQueueObservationStartedFromAnotherQueue() throws { func test(_ dbWriter: DatabaseWriter) throws { // We need something to change diff --git a/Tests/GRDBTests/VirtualTableModuleTests.swift b/Tests/GRDBTests/VirtualTableModuleTests.swift index d2ba6ca57..ab6a3ec9a 100644 --- a/Tests/GRDBTests/VirtualTableModuleTests.swift +++ b/Tests/GRDBTests/VirtualTableModuleTests.swift @@ -49,14 +49,6 @@ private final class FTS3TokenizeTableDefinition { class VirtualTableModuleTests: GRDBTestCase { func testCustomVirtualTableModule() throws { - // fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "test", using: FTS3TokenizeModule()) { t in @@ -68,14 +60,6 @@ class VirtualTableModuleTests: GRDBTestCase { } func testThrowingCustomVirtualTableModule() throws { - // fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { From a5044528461830e40159f71d2368fc7f331346cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Mar 2020 19:10:48 +0100 Subject: [PATCH 12/12] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 709e8c659..a2aa61850 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,6 +91,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## GRDB5 Branch - [#719](https://github.com/groue/GRDB.swift/pull/719): Bump required Swift version to 5.2 +- [#720](https://github.com/groue/GRDB.swift/pull/720): Turn deprecated APIs into unavailable ones ## 4.11.0