diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 000000000..9b7be2474 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,57 @@ +included: + - GRDB + +disabled_rules: + - cyclomatic_complexity + - file_length + - force_cast + - force_try + - function_body_length + - function_parameter_count + - identifier_name + - is_disjoint + - nesting + - opening_brace + - redundant_optional_initialization + - syntactic_sugar + - todo + - trailing_comma + - trailing_whitespace + - type_body_length + - type_name + - unused_setter_value + +opt_in_rules: + - anyobject_protocol + - array_init + - attributes + - closure_spacing + - collection_alignment + - contains_over_first_not_nil + - convenience_type + - empty_count + - empty_string + - explicit_init + - fatal_error_message + - first_where + - joined_default_parameter + - last_where + - legacy_multiple + - legacy_random + - modifier_order + - no_extension_access_modifier + - overridden_super_call + - pattern_matching_keywords + - prohibited_super_call + - reduce_into + - redundant_type_annotation + - sorted_first_last + - toggle_bool + - unused_declaration + - unused_import + - unused_private_declaration + - yoda_condition + +vertical_whitespace: + max_empty_lines: 2 + diff --git a/.travis.yml b/.travis.yml index c87f1fece..fb7fdf576 100644 --- a/.travis.yml +++ b/.travis.yml @@ -146,8 +146,16 @@ jobs: gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode10.2 env: - - TID=CocoaPods GRDB - script: make test_install_GRDB_CocoaPods + - TID=CocoaPods GRDB (framework) + script: make test_install_GRDB_CocoaPods_framework + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 10.2 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.2 + env: + - TID=CocoaPods GRDB (static) + script: make test_install_GRDB_CocoaPods_static # SPM Install - stage: Test Installation Xcode 10.2 @@ -297,10 +305,10 @@ jobs: # env: # - TID=SQLCipher 4 # script: make test_framework_SQLCipher4 - # - # ########################################### - # ## Test Installation Xcode 10 - # + + ########################################### + ## Test Installation Xcode 10 + # # Manual Install # - stage: Test Installation Xcode 10 # gemfile: .ci/gemfiles/Gemfile.travis @@ -316,15 +324,23 @@ jobs: # env: # - TID=CocoaPods Lint # script: make test_CocoaPodsLint_GRDB - # - # # CocoaPods Install GRDB - # - stage: Test Installation Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=CocoaPods GRDB - # script: make test_install_GRDB_CocoaPods - # + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 10 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10 + env: + - TID=CocoaPods GRDB (framework) + script: make test_install_GRDB_CocoaPods_framework + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 10 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10 + env: + - TID=CocoaPods GRDB (static) + script: make test_install_GRDB_CocoaPods_static + # # SPM Install # - stage: Test Installation Xcode 10 # gemfile: .ci/gemfiles/Gemfile.travis diff --git a/CHANGELOG.md b/CHANGELOG.md index 05df3dc0e..1ab0c698d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,12 +5,15 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. + + #### 4.x Releases +- `4.2.x` Releases - [4.2.0](#420) - `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411) - `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401) @@ -51,10 +54,105 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [0.110.0](#01100), ... + +## 4.2.0 + +Released August 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.1.1...v4.2.0) + +**New** + +- [#570](https://github.com/groue/GRDB.swift/pull/570) by [@chrisballinger](https://github.com/chrisballinger): Allow Swift static library integration via CocoaPods +- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest +- [#586](https://github.com/groue/GRDB.swift/pull/586): Automatic region tracking for ValueObservation + +**Fixed** + +- [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix +- [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation +- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)` +- [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers + +**Other** + +- [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations +- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint + + +### Documentation Diff + +The [ValueObservation](README.md#valueobservation) chapter has been updated so that it fosters the new `ValueObservation.tracking(value:)` method. Other ways to define observations are now described as optimizations. + + +### API Diff + +```diff +-protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest { } ++protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } + +-extension QueryInterfaceRequest { +- func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest +-} +-extension QueryInterfaceRequest { +- func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest +-} ++extension TableRequest where Self: FilteredRequest { ++ func matching(_ pattern: FTS3Pattern?) -> Self ++} ++extension TableRequest where Self: FilteredRequest { ++ func matching(_ pattern: FTS5Pattern?) -> Self ++} + + protocol Association: DerivableRequest { +- associatedtype OriginRowDecoder ++ associatedtype OriginRowDecoder: TableRecord + } + +-struct BelongsToAssociation: AssociationToOne { } +-struct HasManyAssociation: AssociationToMany { } +-struct HasManyThroughAssociation: AssociationToMany { } +-struct HasOneAssociation: AssociationToOne { } +-struct HasOneThroughAssociation: AssociationToOne { } ++struct BelongsToAssociation: AssociationToOne { } ++struct HasManyAssociation: AssociationToMany { } ++struct HasManyThroughAssociation: AssociationToMany { } ++struct HasOneAssociation: AssociationToOne { } ++struct HasOneThroughAssociation: AssociationToOne { } + +-struct QueryInterfaceRequest: DerivableRequest { } ++struct QueryInterfaceRequest: FilteredRequest, OrderedRequest, SelectionRequest, TableRequuest { } ++extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { } ++extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { } + + extension AssociationAggregate { ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ name: String) -> AssociationAggregate ++ func forKey(_ name: String) -> AssociationAggregate + ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ key: CodingKey) -> AssociationAggregate ++ func forKey(_ key: CodingKey) -> AssociationAggregate + } + + extension SQLSpecificExpressible { ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ name: String) -> SQLSelectable ++ func forKey(_ name: String) -> SQLSelectable + ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ key: CodingKey) -> SQLSelectable ++ func forKey(_ key: CodingKey) -> SQLSelectable + } + + extension ValueObservation where Reducer == Void { ++ static func tracking(fetch: @escaping (Database) throws -> Value) -> ValueObservation> + } +``` + + ## 4.1.1 Released June 22, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.1.0...v4.1.1) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 65b6b22c8..833b6245e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,7 +88,6 @@ The ideas, in alphabetical order: - [Reactive Database Observation] - [SQL Console in the Debugger] - [SQLCipher in a Shared App Container] -- [Static Library] - [Typed Expressions] @@ -292,14 +291,16 @@ There are several SQLite features that GRDB could natively support: - [Windows Functions](https://www.sqlite.org/windowfunctions.html) - [More ideas](https://www.sqlite.org/lang.html) +See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations. + ### Reactive Database Observation :baby: Starter Task -We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings. +We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries. -We need more choices of reactive engines. +More choices of reactive engines would help more developers enjoy GRDB. ### SQL Console in the Debugger @@ -316,13 +317,6 @@ Sometimes one needs, in lldb, a console similar to the [Command Line Shell For S See issue [#302](https://github.com/groue/GRDB.swift/issues/302). -### Static Library - -:question: Unknown Difficulty :hammer: Tooling - -It would be nice to be able to integrate GRDB as a static library. - - ### Typed Expressions :bowtie: Public API Challenge :muscle: Hard :fire: Experimental @@ -376,12 +370,12 @@ Features that blur this focus are non-goals: [JSON]: #json [Linux]: #linux [More SQL Generation]: #more-sql-generation +[Reactive Database Observation]: #reactive-database-observation [Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database [Non-Goals]: #non-goals [Report Bugs]: #report-bugs [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Concurrency]: #concurrency -[Static Library]: #static-library [Sponsoring and Professional Support]: #sponsoring-and-professional-support [SQL Console in the Debugger]: #sql-console-in-the-debugger [SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index e7450b0c6..7c6bbd3a9 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -1,6 +1,6 @@ QueryInterfaceRequest { - let numberOfBooks = Author.books.count.aliased(CodingKey.numberOfBooks) // <-- + let numberOfBooks = Author.books.count.forKey(CodingKey.numberOfBooks) // <-- return Author .annotated(with: numberOfBooks) .asRequest(of: AuthorInfo.self) @@ -2041,7 +2028,7 @@ Aggregates can be modified and combined with Swift operators: ```swift let workCount = Author.books.count + Author.paintings.count) - let request = Author.annotated(with: workCount.aliased("workCount")) + let request = Author.annotated(with: workCount.forKey("workCount")) ``` - IFNULL operator `??` @@ -2133,7 +2120,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin let aggregate = Author.books.count + // association key "books" Author.paintings.count // association key "paintings" - let request = Author.annotated(with: aggregate.aliased("workCount")) + let request = Author.annotated(with: aggregate.forKey("workCount")) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` @@ -2201,11 +2188,11 @@ But in the following example, we use the same association `Author.books` twice, let novelCount = Author.books // association key "books" .filter(Column("kind") == "novel") .count - .aliased("novelCount") + .forKey("novelCount") let theatrePlayCount = Author.books // association key "books" .filter(Column("kind") == "theatrePlay") .count - .aliased("theatrePlayCount") + .forKey("theatrePlayCount") let request = Author.annotated(with: novelCount, theatrePlayCount) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 1daf7e909..dabcadaa0 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```sh cd [GRDB directory] - git checkout v4.1.1 + git checkout v4.2.0 git submodule update --init SQLiteCustom/src ```` diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 1cb1a41da..44cf88639 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '4.1.1' + s.version = '4.2.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' @@ -9,21 +9,20 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } s.module_name = 'GRDB' - s.swift_versions = ['4.2', '5'] + s.swift_versions = ['4.2', '5.0'] s.ios.deployment_target = '9.0' s.osx.deployment_target = '10.9' s.watchos.deployment_target = '2.0' - s.module_map = 'Support/module.modulemap' s.default_subspec = 'standard' s.subspec 'standard' do |ss| - ss.source_files = 'GRDB/**/*.swift', 'Support/*.h' + ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h' ss.framework = 'Foundation' ss.library = 'sqlite3' end s.subspec 'SQLCipher' do |ss| - ss.source_files = 'GRDB/**/*.swift', 'Support/*.h' + ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h' ss.framework = 'Foundation' ss.dependency 'SQLCipher', '>= 3.4.0' ss.xcconfig = { diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 2e51e1755..8e93a465e 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -461,6 +461,8 @@ 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -1129,6 +1131,7 @@ 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; + 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -1233,8 +1236,8 @@ 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = ""; }; - 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.2.1/Realm.framework"; sourceTree = ""; }; - 56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.2.1/RealmSwift.framework"; sourceTree = ""; }; + 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.3/Realm.framework"; sourceTree = ""; }; + 56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.3/RealmSwift.framework"; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; 56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = ""; }; 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = ""; }; @@ -1628,6 +1631,7 @@ 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, + 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */, 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */, ); @@ -2313,6 +2317,7 @@ 56E5D7C61B4D3FED00430942 /* Frameworks */, 56E5D7C71B4D3FED00430942 /* Headers */, 56E5D7C81B4D3FED00430942 /* Resources */, + 56EB54FA22C9115E00850069 /* Swiftlint */, ); buildRules = ( ); @@ -2367,6 +2372,7 @@ DC3773EF19C8CBB3004FCF85 /* Frameworks */, DC3773F019C8CBB3004FCF85 /* Headers */, DC3773F119C8CBB3004FCF85 /* Resources */, + 56EB54F322C8ED5100850069 /* Swiftlint */, ); buildRules = ( ); @@ -2559,6 +2565,45 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 56EB54F322C8ED5100850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; + 56EB54FA22C9115E00850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 560C97D41C0E22D300BF8471 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -3051,6 +3096,7 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, @@ -3250,6 +3296,7 @@ 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, 569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, @@ -3497,7 +3544,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1", + "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3", ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -3520,7 +3567,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1", + "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3", ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; diff --git a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme index 7ebe66f64..0c36958af 100644 --- a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme +++ b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme @@ -1,6 +1,6 @@ ())? - var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())? - var SQLiteConnectionDidClose: (() -> ())? + var SQLiteConnectionDidOpen: (() -> Void)? + var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? + var SQLiteConnectionDidClose: (() -> Void)? var SQLiteOpenFlags: Int32 { let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) return threadingMode.SQLiteOpenFlags | readWriteFlags diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 51ef3b303..95705d5a2 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -29,7 +29,10 @@ extension Sequence { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + public func flatMap( + _ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) + -> FlattenCursor, SegmentOfResult>> + { return AnyCursor(self).flatMap(transform) } } @@ -76,7 +79,7 @@ extension Set { /// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, /// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, /// `suffix`. -public protocol Cursor : class { +public protocol Cursor: AnyObject { /// The type of element traversed by the cursor. associatedtype Element @@ -141,7 +144,9 @@ extension Cursor { /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. - public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { + public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) + -> MapCursor>, ElementOfResult> + { return map(transform).filter { $0 != nil }.map { $0! } } @@ -190,7 +195,7 @@ extension Cursor { public func dropFirst() -> DropFirstCursor { return dropFirst(1) } - + /// Returns an array containing all but the given number of final /// elements. /// @@ -243,13 +248,19 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) + -> FlattenCursor>> + where SegmentOfResult: Sequence + { return flatMap { try AnyCursor(transform($0)) } } /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor> { + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) + -> FlattenCursor> + where SegmentOfResult: Cursor + { return map(transform).joined() } @@ -503,7 +514,7 @@ extension Cursor where Element: StringProtocol { /// This cursor forwards its next() method to an arbitrary underlying cursor /// having the same Element type, hiding the specifics of the underlying /// cursor. -public final class AnyCursor : Cursor { +public final class AnyCursor: Cursor { private let element: () throws -> Element? /// Creates a cursor that wraps a base cursor but whose type depends only on @@ -539,11 +550,11 @@ public final class AnyCursor : Cursor { } /// :nodoc: -public final class DropFirstCursor : Cursor { +public final class DropFirstCursor: Cursor { private let base: Base private let limit: Int private var dropped: Int = 0 - + init(_ base: Base, limit: Int) { GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor") self.base = base @@ -566,7 +577,7 @@ public final class DropFirstCursor : Cursor { /// consecutive elements of some base cursor that satisfy a given predicate. /// /// :nodoc: -public final class DropWhileCursor : Cursor { +public final class DropWhileCursor: Cursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false @@ -605,7 +616,7 @@ public final class DropWhileCursor : Cursor { /// // Prints: "1: bar" /// /// :nodoc: -public final class EnumeratedCursor : Cursor { +public final class EnumeratedCursor: Cursor { private let base: Base private var index: Int @@ -628,7 +639,7 @@ public final class EnumeratedCursor : Cursor { /// also satisfy a given predicate. /// /// :nodoc: -public final class FilterCursor : Cursor { +public final class FilterCursor: Cursor { private let base: Base private let isIncluded: (Base.Element) throws -> Bool @@ -656,7 +667,7 @@ public final class FilterCursor : Cursor { /// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:) /// /// :nodoc: -public final class FlattenCursor : Cursor where Base.Element: Cursor { +public final class FlattenCursor: Cursor where Base.Element: Cursor { private let base: Base private var inner: Base.Element? @@ -686,7 +697,7 @@ public final class FlattenCursor : Cursor where Base.Element: Curs /// See Cursor.map(_:) /// /// :nodoc: -public final class MapCursor : Cursor { +public final class MapCursor: Cursor { private let base: Base private let transform: (Base.Element) throws -> Element @@ -708,7 +719,7 @@ public final class MapCursor : Cursor { /// `Base` cursor. /// /// :nodoc: -public final class PrefixCursor : Cursor { +public final class PrefixCursor: Cursor { private let base: Base private let maxLength: Int private var taken = 0 @@ -735,7 +746,7 @@ public final class PrefixCursor : Cursor { /// some base cursor that satisfy a given predicate. /// /// :nodoc: -public final class PrefixWhileCursor : Cursor { +public final class PrefixWhileCursor: Cursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 0155a214e..71e0b773a 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,15 +1,15 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { - + // MARK: - Database Schema - + /// Clears the database schema cache. /// /// You may need to clear the cache manually if the database schema is @@ -71,7 +71,7 @@ extension Database { .names(ofType: type) .contains { $0.lowercased() == name } } - + /// The primary key for table named `tableName`. /// /// All tables have a primary key, even when it is not explicit. When a @@ -203,7 +203,12 @@ extension Database { /// True if a sequence of columns uniquely identifies a row, that is to say /// if the columns are the primary key, or if there is a unique index on them. - public func table(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String { + public func table( + _ tableName: String, + hasUniqueKey columns: T) + throws -> Bool + where T.Iterator.Element == String + { return try columnsForUniqueKey(Array(columns), in: tableName) != nil } @@ -213,7 +218,9 @@ extension Database { return foreignKeys } - var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] + var rawForeignKeys: [( + destinationTable: String, + mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") { // row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."] @@ -224,9 +231,13 @@ extension Database { let destination: String? = row[4] if previousId == id { - rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq)) + rawForeignKeys[rawForeignKeys.count - 1] + .mapping + .append((origin: origin, destination: destination, seq: seq)) } else { - rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)])) + rawForeignKeys.append(( + destinationTable: table, + mapping: [(origin: origin, destination: destination, seq: seq)])) previousId = id } } @@ -281,7 +292,7 @@ extension Database { } extension Database { - + /// The columns in the table named `tableName` /// /// - throws: A DatabaseError if table does not exist. @@ -313,7 +324,7 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | name | TEXT | 0 | NULL | 0 | // 2 | score | INTEGER | 0 | NULL | 0 | - + if sqlite3_libversion_number() < 3008005 { // Work around a bug in SQLite where PRAGMA table_info would // return a result even after the table was deleted. @@ -324,7 +335,7 @@ extension Database { let columns = try ColumnInfo .fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") .sorted(by: { $0.cid < $1.cid }) - guard columns.count > 0 else { + if columns.isEmpty { throw DatabaseError(message: "no such table: \(tableName)") } @@ -335,14 +346,25 @@ extension Database { /// If there exists a unique key on columns, return the columns /// ordered as the matching index (or primay key). Case of returned columns /// is not guaranteed. - func columnsForUniqueKey(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String { - let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist + func columnsForUniqueKey( + _ columns: T, + in tableName: String) + throws -> [String]? + where T.Iterator.Element == String + { + // Check primaryKey first, so that we fail early if the table does not exist + let primaryKey = try self.primaryKey(tableName) let lowercasedColumns = Set(columns.map { $0.lowercased() }) if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns { return primaryKey.columns } - if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) { - // There is an explicit unique index on the columns + + // Is there is an explicit unique index on the columns? + let indexes = try self.indexes(on: tableName) + let matchingIndex = indexes.first { index in + index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns + } + if let index = matchingIndex { return index.columns } return nil @@ -366,7 +388,7 @@ extension Database { /// 2 score INTEGER 0 NULL 0 /// /// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info -public struct ColumnInfo : FetchableRecord { +public struct ColumnInfo: FetchableRecord { let cid: Int /// The column name diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 1553dbf62..859882b91 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { @@ -36,7 +36,7 @@ extension Database { /// - returns: A SelectStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement { - return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self) + return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags) } /// Returns a prepared statement that can be reused. @@ -85,7 +85,7 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement { - return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self) + return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags) } /// Returns a prepared statement that can be reused. @@ -180,16 +180,15 @@ extension Database { // Compile do { - let statementCompilationAuthorizer = StatementCompilationAuthorizer() - authorizer = statementCompilationAuthorizer - defer { authorizer = nil } - - nextStatement = try UpdateStatement( - database: self, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: 0, - authorizer: statementCompilationAuthorizer) + let authorizer = StatementCompilationAuthorizer() + nextStatement = try withAuthorizer(authorizer) { + try UpdateStatement( + database: self, + statementStart: statementStart, + statementEnd: &statementEnd, + prepFlags: 0, + authorizer: authorizer) + } } guard let statement = nextStatement else { @@ -213,18 +212,63 @@ extension Database { // Check that all arguments were consumed: it is a programmer error to // provide arguments that do not match the statement. if arguments.values.isEmpty == false { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)") + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)") } } } extension Database { - - func updateStatementWillExecute(_ statement: UpdateStatement) { - observationBroker.updateStatementWillExecute(statement) + + func executeUpdateStatement(_ statement: UpdateStatement) throws { + let authorizer = observationBroker.updateStatementWillExecute(statement) + let sqliteStatement = statement.sqliteStatement + var code: Int32 = SQLITE_OK + withAuthorizer(authorizer) { + while true { + code = sqlite3_step(sqliteStatement) + if code == SQLITE_ROW { + // Statement returns a row, but the user ignores the + // content of this row: + // + // try db.execute(sql: "SELECT ...") + // + // That's OK: maybe the selected rows perform side effects. + // For example: + // + // try db.execute(sql: "SELECT sqlcipher_export(...)") + // + // Or maybe the user doesn't know that the executed statement + // return rows (https://github.com/groue/GRDB.swift/issues/15); + // + // try db.execute(sql: "PRAGMA journal_mode=WAL") + // + // It is thus important that we consume *all* rows. + continue + } else { + break + } + } + } + + // Statement has been fully executed, and authorizer has been reset. + // We can now move on further tasks. + + if code == SQLITE_DONE { + try updateStatementDidExecute(statement) + } else { + assert(code != SQLITE_ROW) + try updateStatementDidFail(statement) + throw DatabaseError( + resultCode: code, + message: lastErrorMessage, + sql: statement.sql, + arguments: statement.arguments) + } } - func updateStatementDidExecute(_ statement: UpdateStatement) throws { + private func updateStatementDidExecute(_ statement: UpdateStatement) throws { if statement.invalidatesDatabaseSchemaCache { clearSchemaCache() } @@ -232,7 +276,7 @@ extension Database { try observationBroker.updateStatementDidExecute(statement) } - func updateStatementDidFail(_ statement: UpdateStatement) throws { + private func updateStatementDidFail(_ statement: UpdateStatement) throws { // Failed statements can not be reused, because sqlite3_reset won't // be able to restore the statement to its initial state: // https://www.sqlite.org/c3ref/reset.html @@ -244,6 +288,28 @@ extension Database { try observationBroker.updateStatementDidFail(statement) } + @inline(__always) + func selectStatementWillExecute(_ statement: SelectStatement) { + if _isRecordingSelectedRegion { + // Don't record schema introspection queries, which may be + // run, or not, depending on the state of the schema cache. + // + // This gives us a quick way to make sure that the observation + // below, which runs schema introspection queries as a side effect, + // only tracks the "player" table: + // + // let observation = ValueObservation.tracking { db in + // try Player.fetchOne(db, key: 1) + // } + // + // Strictly speaking, this prevents the recording of all schema + // queries. But we assume, until proven wrong, that such recording + // isn't needed by anyone. + let region = statement.databaseRegion.ignoringInternalSQLiteTables() + _selectedRegion.formUnion(region) + } + } + func selectStatementDidFail(_ statement: SelectStatement) { // Failed statements can not be reused, because sqlite3_reset won't // be able to restore the statement to its initial state: @@ -294,7 +360,7 @@ struct StatementCache { selectStatements[sql] = statement return statement } - + mutating func updateStatement(_ sql: String) throws -> UpdateStatement { if let statement = updateStatements[sql] { return statement diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ee308af24..f6e29f84c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A raw SQLite connection, suitable for the SQLite C API. @@ -36,7 +36,7 @@ public final class Database { public let sqliteConnection: SQLiteConnection // MARK: - Configuration - + /// The error logging function. /// /// Quoting https://www.sqlite.org/errlog.html: @@ -53,7 +53,7 @@ public final class Database { if logError != nil { registerErrorLogCallback { (_, code, message) in guard let logError = Database.logError else { return } - guard let message = message.map({ String(cString: $0) }) else { return } + guard let message = message.map(String.init) else { return } let resultCode = ResultCode(rawValue: code) logError(resultCode, message) } @@ -129,24 +129,8 @@ public final class Database { var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) } var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) } - // Statement authorizer - var authorizer: StatementAuthorizer? { - didSet { - switch (oldValue, authorizer) { - case (.some, nil): - sqlite3_set_authorizer(sqliteConnection, nil, nil) - case (nil, .some): - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in - guard let dbPointer = dbPointer else { return SQLITE_OK } - let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() - return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4) - }, dbPointer) - default: - break - } - } - } + /// Statement authorizer. Use withAuthorizer(_:_:). + fileprivate var _authorizer: StatementAuthorizer? // Transaction observers management lazy var observationBroker = DatabaseObservationBroker(self) @@ -156,6 +140,11 @@ public final class Database { try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS")) } + /// If true, select statement execution is recorded. + /// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)` + var _isRecordingSelectedRegion: Bool = false + var _selectedRegion = DatabaseRegion() + // MARK: - Private properties private var busyCallback: BusyCallback? @@ -164,9 +153,9 @@ public final class Database { private var collations = Set() private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly private var isClosed: Bool = false - + // MARK: - Initializer - + init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws { self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.configuration = configuration @@ -179,7 +168,7 @@ public final class Database { } extension Database { - + // MARK: - Database Opening private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection { @@ -207,7 +196,7 @@ extension Database { } extension Database { - + // MARK: - Database Setup /// This method must be called after database initialization @@ -218,16 +207,17 @@ extension Database { setupBusyMode() setupDefaultFunctions() setupDefaultCollations() + setupAuthorizer() observationBroker.installCommitAndRollbackHooks() try activateExtendedCodes() - + #if SQLITE_HAS_CODEC try validateSQLCipher() if let passphrase = configuration.passphrase { try setCipherPassphrase(passphrase) } #endif - + // Last step before we can start accessing the database. // This is the opportunity to run SQLCipher configuration // pragmas such as cipher_page_size, for example. @@ -240,24 +230,34 @@ extension Database { guard configuration.trace != nil else { return } - // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14 - // It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 + // http://www.sqlite.org/changes.html#version_3_14 + // It is available from iOS 10.0 and OS X 10.12 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in - return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) - }, dbPointer) + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2( + sqliteConnection, + UInt32(SQLITE_TRACE_STMT), + { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in + Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) + }, + dbPointer) #elseif os(Linux) - setupTrace_v1() + setupTrace_v1() #else - if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in - return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) - }, dbPointer) - } else { - setupTrace_v1() - } + if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2( + sqliteConnection, + UInt32(SQLITE_TRACE_STMT), + { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in + Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) + }, + dbPointer) + } else { + setupTrace_v1() + } #endif } @@ -265,7 +265,7 @@ extension Database { private func setupTrace_v1() { let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace(sqliteConnection, { (dbPointer, sql) in - guard let sql = sql.map({ String(cString: $0) }) else { return } + guard let sql = sql.map(String.init) else { return } let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.configuration.trace!(sql) }, dbPointer) @@ -339,6 +339,29 @@ extension Database { add(collation: .localizedStandardCompare) } + private func setupAuthorizer() { + // SQLite authorizer is set only once per database connection. + // + // This is because authorizer changes have SQLite invalidate statements, + // with undesired side effects. See: + // + // - DatabaseCursorTests.testIssue583() + // - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html + // swiftlint:disable:previous line_length + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_set_authorizer( + sqliteConnection, + { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in + let db = Unmanaged.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue() + guard let authorizer = db._authorizer else { + return SQLITE_OK + } + return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4) + }, + dbPointer) + } + + private func activateExtendedCodes() throws { let code = sqlite3_extended_result_codes(sqliteConnection, 1) guard code == SQLITE_OK else { @@ -391,7 +414,7 @@ extension Database { } extension Database { - + // MARK: - Database Closing /// This method must be called before database deallocation @@ -409,18 +432,19 @@ extension 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) + // 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) + 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) - } + 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 @@ -466,7 +490,7 @@ extension Database { } extension Database { - + // MARK: - Functions /// Add or redefine an SQL function. @@ -492,7 +516,7 @@ extension Database { } extension Database { - + // MARK: - Collations /// Add or redefine a collation. @@ -539,7 +563,8 @@ extension Database { _readOnlyDepth += 1 if _readOnlyDepth == 1 && configuration.readonly == false { // 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) + // 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() } } @@ -548,7 +573,8 @@ extension Database { _readOnlyDepth -= 1 if _readOnlyDepth == 0 && configuration.readonly == false { // 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) + // 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() } } @@ -583,7 +609,42 @@ extension Database { } extension Database { + + // MARK: - Authorizer + + func withAuthorizer(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T { + SchedulingWatchdog.preconditionValidQueue(self) + let old = self._authorizer + self._authorizer = authorizer + defer { self._authorizer = old } + return try block() + } +} +extension Database { + + // MARK: - Recording of the selected region + + func recordingSelectedRegion(_ block: () throws -> T) rethrows -> (T, DatabaseRegion) { + SchedulingWatchdog.preconditionValidQueue(self) + let oldFlag = self._isRecordingSelectedRegion + let oldRegion = self._selectedRegion + self._isRecordingSelectedRegion = true + self._selectedRegion = DatabaseRegion() + defer { + self._isRecordingSelectedRegion = oldFlag + if self._isRecordingSelectedRegion { + self._selectedRegion = oldRegion.union(self._selectedRegion) + } else { + self._selectedRegion = oldRegion + } + } + return try (block(), _selectedRegion) + } +} + +extension Database { + // MARK: - Transactions & Savepoint /// Executes a block inside a database transaction. @@ -640,7 +701,7 @@ extension Database { } } } - + if let firstError = firstError { throw firstError } @@ -674,7 +735,7 @@ extension Database { if !isInsideTransaction && configuration.defaultTransactionKind != .deferred { return try inTransaction(configuration.defaultTransactionKind, block) } - + // If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in // order to perform the special error handling of rollbacks (see // the rollback method). @@ -849,7 +910,7 @@ extension Database { } extension Database { - + // MARK: - Memory Management func releaseMemory() { @@ -864,12 +925,18 @@ extension Database { // MARK: - Backup - static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws { + static func backup( + from dbFrom: Database, + to dbDest: Database, + afterBackupInit: (() -> Void)? = nil, + afterBackupStep: (() -> Void)? = nil) + throws + { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { - throw DatabaseError(resultCode: .SQLITE_ERROR) + throw DatabaseError() } afterBackupInit?() @@ -904,35 +971,36 @@ extension Database { } #if SQLITE_HAS_CODEC - extension Database { - - // MARK: - Encryption - - func change(passphrase: String) throws { - // FIXME: sqlite3_rekey is discouraged. - // - // https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320 - // - // > We (Zetetic) have been discouraging the use of sqlite3_rekey in - // > favor of attaching a new database with the desired encryption - // > options and using sqlcipher_export() to migrate the contents and - // > schema of the original db into the new one: - // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ - let data = passphrase.data(using: .utf8)! - #if swift(>=5.0) - let code = data.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) - } - #else - let code = data.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0, Int32(data.count)) - } - #endif - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: lastErrorMessage) - } +extension Database { + + // MARK: - Encryption + + func change(passphrase: String) throws { + // FIXME: sqlite3_rekey is discouraged. + // + // https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320 + // + // > We (Zetetic) have been discouraging the use of sqlite3_rekey in + // > favor of attaching a new database with the desired encryption + // > options and using sqlcipher_export() to migrate the contents and + // > schema of the original db into the new one: + // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ + // swiftlint:disable:previous line_length + let data = passphrase.data(using: .utf8)! + #if swift(>=5.0) + let code = data.withUnsafeBytes { + sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) + } + #else + let code = data.withUnsafeBytes { + sqlite3_rekey(sqliteConnection, $0, Int32(data.count)) + } + #endif + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: lastErrorMessage) } } +} #endif extension Database { @@ -991,7 +1059,7 @@ extension Database { /// A built-in SQLite collation. /// /// See https://www.sqlite.org/datatype3.html#collation - public struct CollationName : RawRepresentable, Hashable { + public struct CollationName: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1022,7 +1090,7 @@ extension Database { /// } /// /// See https://www.sqlite.org/datatype3.html - public struct ColumnType : RawRepresentable, Hashable { + public struct ColumnType: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1063,7 +1131,7 @@ extension Database { /// An SQLite conflict resolution. /// /// See https://www.sqlite.org/lang_conflict.html. - public enum ConflictResolution : String { + public enum ConflictResolution: String { case rollback = "ROLLBACK" case abort = "ABORT" case fail = "FAIL" @@ -1074,7 +1142,7 @@ extension Database { /// A foreign key action. /// /// See https://www.sqlite.org/foreignkeys.html - public enum ForeignKeyAction : String { + public enum ForeignKeyAction: String { case cascade = "CASCADE" case restrict = "RESTRICT" case setNull = "SET NULL" @@ -1091,7 +1159,7 @@ extension Database { } /// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html - public enum TransactionKind : String { + public enum TransactionKind: String { case deferred = "DEFERRED" case immediate = "IMMEDIATE" case exclusive = "EXCLUSIVE" diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 530992caa..0b182fd94 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A Collation is a string comparison function used by SQLite. @@ -27,8 +27,16 @@ public final class DatabaseCollation { self.name = name self.function = { (length1, buffer1, length2, buffer2) in // Buffers are not C strings: they do not end with \0. - let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)! - let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)! + let string1 = String( + bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), + length: Int(length1), + encoding: .utf8, + freeWhenDone: false)! + let string2 = String( + bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), + length: Int(length2), + encoding: .utf8, + freeWhenDone: false)! return function(string1, string2) } } @@ -50,6 +58,6 @@ extension DatabaseCollation: Hashable { /// :nodoc: public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { // See https://www.sqlite.org/c3ref/create_collation.html - return sqlite3_stricmp(lhs.name, lhs.name) == 0 + return sqlite3_stricmp(lhs.name, rhs.name) == 0 } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 2ed6eab62..308f2d28b 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -1,13 +1,13 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif -public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible { +public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public let rawValue: Int32 public init(rawValue: Int32) { @@ -48,6 +48,7 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible // Primary Result codes // https://www.sqlite.org/rescode.html#primary_result_code_list + // swiftlint:disable operator_usage_whitespace public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite @@ -79,10 +80,12 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log() public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing + // swiftlint:enable operator_usage_whitespace // Extended Result Code // https://www.sqlite.org/rescode.html#extended_result_code_list + // swiftlint:disable operator_usage_whitespace public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8))) public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8))) public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8))) @@ -139,21 +142,23 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) + // swiftlint:enable operator_usage_whitespace } // 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) + // 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)) + 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 - } + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { + return String(cString: sqlite3_errstr(rawValue)) + } else { + return nil + } #endif } @@ -168,7 +173,7 @@ extension ResultCode { } /// DatabaseError wraps an SQLite error. -public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { +public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// The SQLite error code (see /// https://www.sqlite.org/rescode.html#primary_result_code_list). @@ -207,7 +212,12 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { public let sql: String? /// Creates a Database Error - public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) { + public init( + resultCode: ResultCode = .SQLITE_ERROR, + message: String? = nil, + sql: String? = nil, + arguments: StatementArguments? = nil) + { self.extendedResultCode = resultCode self.message = message ?? resultCode.errorString self.sql = sql @@ -264,7 +274,7 @@ extension DatabaseError { /// NSError bridging: the user-info dictionary. /// :nodoc: - public var errorUserInfo: [String : Any] { + public var errorUserInfo: [String: Any] { return [NSLocalizedDescriptionKey: description] } } diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 0a9f4e036..6827ca0ae 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// An SQL function or aggregate. @@ -44,7 +44,12 @@ public final class DatabaseFunction: Hashable { /// as Int, String, NSDate, etc. The array is guaranteed to have /// exactly *argumentCount* elements, provided *argumentCount* is /// not nil. - public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) { + public init( + _ name: String, + argumentCount: Int32? = nil, + pure: Bool = false, + function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) + { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .function{ (argc, argv) in @@ -94,10 +99,15 @@ public final class DatabaseFunction: Hashable { /// an array of DatabaseValue arguments. The array is guaranteed to /// have exactly *argumentCount* elements, provided *argumentCount* is /// not nil. - public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) { + public init( + _ name: String, + argumentCount: Int32? = nil, + pure: Bool = false, + aggregate: Aggregate.Type) + { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure - self.kind = .aggregate { return Aggregate() } + self.kind = .aggregate { Aggregate() } } /// Calls sqlite3_create_function_v2 @@ -197,7 +207,9 @@ public final class DatabaseFunction: Hashable { var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { guard case .function = self else { return nil } return { (sqliteContext, argc, argv) in - let definition = Unmanaged.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue() + let definition = Unmanaged + .fromOpaque(sqlite3_user_data(sqliteContext)) + .takeUnretainedValue() do { try DatabaseFunction.report( result: definition.compute(argc, argv), @@ -262,11 +274,15 @@ public final class DatabaseFunction: Hashable { private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged { // The current aggregate buffer let stride = MemoryLayout>.stride - let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride) + let aggregateContextBufferP = UnsafeMutableRawBufferPointer( + start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, + count: stride) if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review. // Buffer contains non-null pointer: load aggregate context - let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged.self) + let aggregateContextP = aggregateContextBufferP + .baseAddress! + .assumingMemoryBound(to: Unmanaged.self) return aggregateContextP.pointee } else { // Buffer contains null pointer: create aggregate context... diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5d9eb114d..2cc913f07 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -1,14 +1,14 @@ import Foundation import Dispatch #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if os(iOS) - import UIKit +import UIKit #endif /// A DatabasePool grants concurrent accesses to an SQLite database. @@ -79,7 +79,10 @@ public final class DatabasePool: DatabaseWriter { // opens a pool to an existing non-WAL database, and // attempts to read from it. // See https://github.com/groue/GRDB.swift/issues/102 - try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;") + try db.execute(sql: """ + CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); + DROP TABLE grdb_issue_102; + """) } } } @@ -87,8 +90,13 @@ public final class DatabasePool: DatabaseWriter { // Readers readerConfig = configuration readerConfig.readonly = true - readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections. - readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction. + // Readers use deferred transactions by default. + // Other transaction kinds are forbidden by SQLite in read-only connections. + readerConfig.defaultTransactionKind = .deferred + // Readers can't allow dangling transactions because there's no + // guarantee that one can get the same reader later in order to close + // an opened transaction. + readerConfig.allowsUnsafeTransactions = false var readerCount = 0 readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection) @@ -134,9 +142,9 @@ public final class DatabasePool: DatabaseWriter { } extension DatabasePool { - + // MARK: - WAL Checkpoints - + /// Runs a WAL checkpoint /// /// See https://www.sqlite.org/wal.html and @@ -151,16 +159,16 @@ extension DatabasePool { // when kind is not .Passive. let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil) guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil) + throw DatabaseError(resultCode: code, message: db.lastErrorMessage) } } } } extension DatabasePool { - + // MARK: - Memory management - + /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. @@ -195,7 +203,8 @@ extension DatabasePool { object: nil) } - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { + @objc + private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return } @@ -213,7 +222,8 @@ extension DatabasePool { } } - @objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { + @objc + private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { DispatchQueue.global().async { self.releaseMemory() } @@ -222,24 +232,24 @@ extension DatabasePool { } #if SQLITE_HAS_CODEC - extension DatabasePool { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - public func change(passphrase: String) throws { - try readerPool.clear(andThen: { - try writer.sync { try $0.change(passphrase: passphrase) } - readerConfig.passphrase = passphrase - }) - } +extension DatabasePool { + + // MARK: - Encryption + + /// Changes the passphrase of an encrypted database + public func change(passphrase: String) throws { + try readerPool.clear(andThen: { + try writer.sync { try $0.change(passphrase: passphrase) } + readerConfig.passphrase = passphrase + }) } +} #endif -extension DatabasePool : DatabaseReader { +extension DatabasePool: DatabaseReader { // MARK: - Reading from Database - + /// Synchronously executes a read-only block in a protected dispatch queue, /// and returns its result. The block is wrapped in a deferred transaction. /// @@ -493,7 +503,7 @@ extension DatabasePool : DatabaseReader { asyncConcurrentRead(block) } #endif - + #if compiler(>=5.0) /// Asynchronously executes a read-only block in a protected dispatch queue. /// @@ -649,7 +659,11 @@ extension DatabasePool : DatabaseReader { /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the /// wrapping transaction. - public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { + public func writeInTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { try writer.sync { db in try db.inTransaction(kind) { try updates(db) @@ -811,7 +825,9 @@ extension DatabasePool { // Sanity check if writer.onValidQueue { writer.execute { db in - GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.") + GRDBPrecondition( + !db.isInsideTransaction, + "makeSnapshot() must not be called from inside a transaction.") } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index a4286bc20..791a2f132 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -71,9 +71,9 @@ public final class DatabaseQueue: DatabaseWriter { } extension DatabaseQueue { - + // MARK: - Memory management - + /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. @@ -106,7 +106,8 @@ extension DatabaseQueue { object: nil) } - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { + @objc + private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return } @@ -124,7 +125,8 @@ extension DatabaseQueue { } } - @objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { + @objc + private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { DispatchQueue.global().async { self.releaseMemory() } @@ -133,15 +135,15 @@ extension DatabaseQueue { } #if SQLITE_HAS_CODEC - extension DatabaseQueue { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - public func change(passphrase: String) throws { - try writer.sync { try $0.change(passphrase: passphrase) } - } +extension DatabaseQueue { + + // MARK: - Encryption + + /// Changes the passphrase of an encrypted database + public func change(passphrase: String) throws { + try writer.sync { try $0.change(passphrase: passphrase) } } +} #endif extension DatabaseQueue { @@ -202,7 +204,7 @@ extension DatabaseQueue { } } #endif - + /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// @@ -302,7 +304,11 @@ extension DatabaseQueue { /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the /// wrapping transaction. - public func inTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { + public func inTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { try writer.sync { db in try db.inTransaction(kind) { try updates(db) @@ -323,7 +329,7 @@ extension DatabaseQueue { public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { return try writer.sync(updates) } - + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index f9a9fd664..ffad142a8 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The protocol for all types that can fetch values from a database. @@ -21,7 +21,7 @@ /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseReader : class { +public protocol DatabaseReader: AnyObject { /// The database configuration var configuration: Configuration { get } @@ -220,10 +220,14 @@ extension DatabaseReader { try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil) } - func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws { + func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws { try read { dbFrom in try writer.writeWithoutTransaction { dbDest in - try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) + try Database.backup( + from: dbFrom, + to: dbDest, + afterBackupInit: afterBackupInit, + afterBackupStep: afterBackupStep) } } } @@ -233,7 +237,7 @@ extension DatabaseReader { /// /// Instances of AnyDatabaseReader forward their methods to an arbitrary /// underlying database reader. -public final class AnyDatabaseReader : DatabaseReader { +public final class AnyDatabaseReader: DatabaseReader { private let base: DatabaseReader /// Creates a database reader that wraps a base database reader. diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 7df10aa59..793c82f4b 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -31,6 +31,7 @@ /// let region = try request.databaseRegion(db) public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? + private init(tableRegions: [String: TableRegion]?) { self.tableRegions = tableRegions } @@ -125,9 +126,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { switch (tableRegion, otherTableRegion) { case (nil, nil): preconditionFailure() - case (nil, let tableRegion?), (let tableRegion?, nil): + case let (nil, tableRegion?), let (tableRegion?, nil): tableRegionUnion = tableRegion - case (let tableRegion?, let otherTableRegion?): + case let (tableRegion?, otherTableRegion?): tableRegionUnion = tableRegion.union(otherTableRegion) } tableRegionsUnion[table] = tableRegionUnion @@ -141,10 +142,23 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { self = union(other) } - func ignoring(_ tables: Set) -> DatabaseRegion { - guard tables.isEmpty == false else { return self } + /// Returns a region suitable for database observation by removing views. + /// + /// We can do it because modifications only happen in actual tables. And we + /// want to do it because we have a fast path for regions that span a + /// single table. + func ignoringViews(_ db: Database) throws -> DatabaseRegion { guard let tableRegions = tableRegions else { return .fullDatabase } - let filteredRegions = tableRegions.filter { tables.contains($0.key) == false } + let viewNames = try db.schema().names(ofType: .view) + guard viewNames.isEmpty == false else { return self } + let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false } + return DatabaseRegion(tableRegions: filteredRegions) + } + + /// Returns a region which doesn't contain any SQLite internal table. + func ignoringInternalSQLiteTables() -> DatabaseRegion { + guard let tableRegions = tableRegions else { return .fullDatabase } + let filteredRegions = tableRegions.filter { !$0.key.starts(with: "sqlite_") } return DatabaseRegion(tableRegions: filteredRegions) } } @@ -184,7 +198,10 @@ extension DatabaseRegion { // Slow path when several tables are observed. guard let tableRegion = tableRegions[event.tableName] else { // Shouldn't happen if the precondition is met. - fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)") + fatalError(""" + precondition failure: event was not filtered out in observes(eventsOfKind:) \ + by region.isModified(byEventsOfKind:) + """) } return tableRegion.contains(rowID: event.rowID) } @@ -198,16 +215,14 @@ extension DatabaseRegion { switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): return true - case (let ltableRegions?, let rtableRegions?): + case let (ltableRegions?, rtableRegions?): let ltableNames = Set(ltableRegions.keys) let rtableNames = Set(rtableRegions.keys) guard ltableNames == rtableNames else { return false } - for tableName in ltableNames { - if ltableRegions[tableName]! != rtableRegions[tableName]! { - return false - } + for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! { + return false } return true default: @@ -257,17 +272,17 @@ private struct TableRegion: Equatable { func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set? switch (self.columns, other.columns) { - case (nil, let columns), (let columns, nil): + case let (nil, columns), let (columns, nil): columnsIntersection = columns - case (let columns?, let other?): + case let (columns?, other?): columnsIntersection = columns.intersection(other) } let rowIdsIntersection: Set? switch (self.rowIds, other.rowIds) { - case (nil, let rowIds), (let rowIds, nil): + case let (nil, rowIds), let (rowIds, nil): rowIdsIntersection = rowIds - case (let rowIds?, let other?): + case let (rowIds?, other?): rowIdsIntersection = rowIds.intersection(other) } @@ -279,7 +294,7 @@ private struct TableRegion: Equatable { switch (self.columns, other.columns) { case (nil, _), (_, nil): columnsUnion = nil - case (let columns?, let other?): + case let (columns?, other?): columnsUnion = columns.union(other) } @@ -287,7 +302,7 @@ private struct TableRegion: Equatable { switch (self.rowIds, other.rowIds) { case (nil, _), (_, nil): rowIdsUnion = nil - case (let rowIds?, let other?): + case let (rowIds?, other?): rowIdsUnion = rowIds.union(other) } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index a55fd2b3f..b7985bae7 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -13,25 +13,14 @@ public struct DatabaseRegionObservation { /// `.observerLifetime`: the observation lasts until the /// observer returned by the `start(in:onChange:)` method /// is deallocated. - public var extent = Database.TransactionObservationExtent.observerLifetime + public var extent: Database.TransactionObservationExtent /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion +} - // Not public because we foster DatabaseRegionConvertible. - init(tracking region: @escaping (Database) throws -> DatabaseRegion) { - self.observedRegion = { db in - // Remove views from the observed region. - // - // We can do it because we are only interested in modifications in - // actual tables. And we want to do it because we have a fast path - // for simple regions that span a single table. - let views = try db.schema().names(ofType: .view) - return try region(db).ignoring(views) - } - } - +extension DatabaseRegionObservation { /// Creates a DatabaseRegionObservation which observes *regions*, and /// notifies whenever one of the observed regions is modified by a /// database transaction. @@ -75,7 +64,9 @@ public struct DatabaseRegionObservation { /// /// - parameter regions: A list of observed regions. public init(tracking regions: [DatabaseRegionConvertible]) { - self.init(tracking: DatabaseRegion.union(regions)) + self.init( + extent: .observerLifetime, + observedRegion: DatabaseRegion.union(regions)) } } @@ -87,11 +78,15 @@ extension DatabaseRegionObservation { /// - parameter onChange: A closure that is provided a database connection /// with write access each time the observed region has been modified. /// - returns: a TransactionObserver - public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + public func start( + in dbWriter: DatabaseWriter, + onChange: @escaping (Database) -> Void) + throws -> TransactionObserver + { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in - let region = try observedRegion(db) + let region = try observedRegion(db).ignoringViews(db) let observer = DatabaseRegionObserver(region: region, onChange: onChange) db.add(transactionObserver: observer, extent: extent) return observer @@ -123,7 +118,7 @@ private class DatabaseRegionObserver: TransactionObserver { func databaseDidCommit(_ db: Database) { guard isChanged else { return } isChanged = false - + onChange(db) } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 6cef0ca48..094423cf2 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -6,7 +6,7 @@ import Dispatch /// See DatabasePool.makeSnapshot() /// /// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html -public class DatabaseSnapshot : DatabaseReader { +public class DatabaseSnapshot: DatabaseReader { private var serializedDatabase: SerializedDatabase /// The database configuration diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index b4b84dfc2..aee43d0f6 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - DatabaseValue @@ -20,7 +20,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon public static let null = DatabaseValue(storage: .null) /// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB). - public enum Storage : Equatable { + public enum Storage: Equatable { /// The NULL storage class. case null @@ -60,10 +60,10 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool { switch (lhs, rhs) { case (.null, .null): return true - case (.int64(let lhs), .int64(let rhs)): return lhs == rhs - case (.double(let lhs), .double(let rhs)): return lhs == rhs - case (.string(let lhs), .string(let rhs)): return lhs == rhs - case (.blob(let lhs), .blob(let rhs)): return lhs == rhs + case let (.int64(lhs), .int64(rhs)): return lhs == rhs + case let (.double(lhs), .double(rhs)): return lhs == rhs + case let (.string(lhs), .string(rhs)): return lhs == rhs + case let (.blob(lhs), .blob(rhs)): return lhs == rhs default: return false } } @@ -120,7 +120,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon fatalError("Unexpected SQLite value type: \(type)") } } - + /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. init(sqliteStatement: SQLiteStatement, index: Int32) { switch sqlite3_column_type(sqliteStatement, index) { @@ -187,17 +187,17 @@ extension DatabaseValue { switch (lhs.storage, rhs.storage) { case (.null, .null): return true - case (.int64(let lhs), .int64(let rhs)): + case let (.int64(lhs), .int64(rhs)): return lhs == rhs - case (.double(let lhs), .double(let rhs)): + case let (.double(lhs), .double(rhs)): return lhs == rhs - case (.int64(let lhs), .double(let rhs)): + case let (.int64(lhs), .double(rhs)): return Int64(exactly: rhs) == lhs - case (.double(let lhs), .int64(let rhs)): + case let (.double(lhs), .int64(rhs)): return rhs == Int64(exactly: lhs) - case (.string(let lhs), .string(let rhs)): + case let (.string(lhs), .string(rhs)): return lhs == rhs - case (.blob(let lhs), .blob(let rhs)): + case let (.blob(lhs), .blob(rhs)): return lhs == rhs default: return false @@ -266,8 +266,10 @@ extension DatabaseValue { case .blob: // We can't assume all blobs are true, and return false: // - // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0) - // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1) + // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', + // then into integer 1, which is negated into 0) + // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', + // then into integer 0, which is negated into 1) return SQLExpressionNot(self) } } @@ -309,17 +311,17 @@ extension DatabaseValue { /// easier testing. func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool { switch (lhs.storage, rhs.storage) { - case (.int64(let lhs), .int64(let rhs)): + case let (.int64(lhs), .int64(rhs)): return lhs < rhs - case (.double(let lhs), .double(let rhs)): + case let (.double(lhs), .double(rhs)): return lhs < rhs - case (.int64(let lhs), .double(let rhs)): + case let (.int64(lhs), .double(rhs)): return Double(lhs) < rhs - case (.double(let lhs), .int64(let rhs)): + case let (.double(lhs), .int64(rhs)): return lhs < Double(rhs) - case (.string(let lhs), .string(let rhs)): + case let (.string(lhs), .string(rhs)): return lhs.utf8.lexicographicallyPrecedes(rhs.utf8) - case (.blob(let lhs), .blob(let rhs)): + case let (.blob(lhs), .blob(rhs)): return lhs.lexicographicallyPrecedes(rhs, by: <) case (.blob, _): return false diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift index a752e34e5..ca59df531 100644 --- a/GRDB/Core/DatabaseValueConversion.swift +++ b/GRDB/Core/DatabaseValueConversion.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - Conversion Context and Errors @@ -14,6 +14,7 @@ struct ValueConversionContext { case columnIndex(Int) case columnName(String) } + var row: Row? var sql: String? var arguments: StatementArguments? @@ -89,7 +90,12 @@ extension ValueConversionContext { /// The canonical conversion error message /// /// - parameter dbValue: nil means "missing column" -func conversionErrorMessage(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) -> String { +func conversionErrorMessage( + to: T.Type, + from dbValue: DatabaseValue?, + conversionContext: ValueConversionContext?) + -> String +{ var message: String var extras: [String] = [] @@ -128,12 +134,33 @@ func conversionErrorMessage(to: T.Type, from dbValue: DatabaseValue?, convers /// The canonical conversion fatal error /// /// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil) -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) -> Never { - fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line) +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + conversionContext: ValueConversionContext?, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ + fatalError( + conversionErrorMessage( + to: T.self, + from: dbValue, + conversionContext: conversionContext), + file: file, + line: line) } @usableFromInline -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, in row: Row, atColumn columnName: String, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + in row: Row, + atColumn columnName: String, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ fatalConversionError( to: T.self, from: dbValue, @@ -141,7 +168,14 @@ func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, in row: R } @usableFromInline -func fatalConversionError(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + sqliteStatement: SQLiteStatement, + index: Int32, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( to: T.self, @@ -150,7 +184,15 @@ func fatalConversionError(to: T.Type, sqliteStatement: SQLiteStatement, index } @usableFromInline -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + sqliteStatement: SQLiteStatement, + index: Int32, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( to: T.self, @@ -172,7 +214,11 @@ extension DatabaseValueConvertible { } } - static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self { + static func decode( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Self + { if let value = fromDatabaseValue(dbValue) { return value } else { @@ -198,8 +244,12 @@ extension DatabaseValueConvertible { fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index) } } - - static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? { + + static func decodeIfPresent( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Self? + { // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. if let value = fromDatabaseValue(dbValue) { return value @@ -258,12 +308,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { // Support for @inlinable decoding extension Row { @usableFromInline - func fastDecode(_ type: Value.Type, atUncheckedIndex index: Int) -> Value { + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value + { return impl.fastDecode(type, atUncheckedIndex: index) } @usableFromInline - func fastDecodeIfPresent(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? { + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value? + { return impl.fastDecodeIfPresent(type, atUncheckedIndex: index) } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 30cc1753f..6836906f6 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - DatabaseValueConvertible @@ -24,7 +24,7 @@ /// try String.fetchOne(statement, arguments:...) // String? /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. -public protocol DatabaseValueConvertible : SQLExpressible { +public protocol DatabaseValueConvertible: SQLExpressible { /// Returns a value that can be stored in the database. var databaseValue: DatabaseValue { get } @@ -49,7 +49,7 @@ extension DatabaseValueConvertible { /// print(url) /// } /// } -public final class DatabaseValueCursor : Cursor { +public final class DatabaseValueCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 @@ -65,6 +65,9 @@ public final class DatabaseValueCursor : Cursor _columnIndex = 0 } _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { @@ -102,12 +105,12 @@ public final class DatabaseValueCursor : Cursor /// print(url) /// } /// } -public final class NullableDatabaseValueCursor : Cursor { +public final class NullableDatabaseValueCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 @usableFromInline var _done = false - + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement @@ -118,6 +121,9 @@ public final class NullableDatabaseValueCursor _columnIndex = 0 } _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { @@ -182,7 +188,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -197,7 +208,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -215,7 +231,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { // fetchOne returns nil if there is no row, or if there is a row with a null value let cursor = try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) return try cursor.next() ?? nil @@ -223,7 +244,7 @@ extension DatabaseValueConvertible { } extension DatabaseValueConvertible { - + // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. @@ -245,7 +266,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -260,7 +287,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -278,7 +311,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -430,7 +469,12 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -445,7 +489,12 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } @@ -473,7 +522,13 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -488,7 +543,13 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -515,7 +576,9 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - request: A FetchRequest. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> NullableDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -572,4 +635,3 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: return try Optional.fetchAll(db, self) } } - diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 1dbc6c740..ec6d88065 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -15,10 +15,10 @@ import Dispatch /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseWriter : DatabaseReader { +public protocol DatabaseWriter: DatabaseReader { // MARK: - Writing in Database - + /// Synchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction, and returns the result. /// @@ -76,16 +76,18 @@ public protocol DatabaseWriter : DatabaseReader { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) + func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) #endif - + /// Asynchronously executes database updates in a protected dispatch queue, /// outside of any transaction. /// /// Eventual concurrent reads may see partial updates unless you wrap them /// in a transaction. func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) - + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// @@ -98,7 +100,7 @@ public protocol DatabaseWriter : DatabaseReader { /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T - + // MARK: - Reading from Database /// Concurrently executes a read-only block in a protected dispatch queue. @@ -175,7 +177,7 @@ public protocol DatabaseWriter : DatabaseReader { } extension DatabaseWriter { - + /// Synchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction, and returns the result. /// @@ -228,7 +230,10 @@ extension DatabaseWriter { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + public func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) + { asyncWriteWithoutTransaction { db in do { var result: T? @@ -255,7 +260,10 @@ extension DatabaseWriter { /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). - public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { + public func add( + transactionObserver: TransactionObserver, + extent: Database.TransactionObservationExtent = .observerLifetime) + { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } @@ -273,7 +281,8 @@ extension DatabaseWriter { /// execution of this method. public func erase() throws { #if SQLITE_HAS_CODEC - // SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 + // SQLCipher does not support the backup API: + // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 // So we'll drop all database objects one after the other. try writeWithoutTransaction { db in // Prevent foreign keys from messing with drop table statements @@ -285,7 +294,8 @@ extension DatabaseWriter { // Remove all database objects, one after the other do { try db.inTransaction { - while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") { + let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" + while let row = try Row.fetchOne(db, sql: sql) { let type: String = row["type"] let name: String = row["name"] try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") @@ -333,6 +343,7 @@ extension DatabaseWriter { let requiresWriteAccess = observation.requiresWriteAccess let observer = ValueObserver( requiresWriteAccess: requiresWriteAccess, + observesSelectedRegion: observation.observesSelectedRegion, writer: self, reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), onError: onError, @@ -353,18 +364,23 @@ extension DatabaseWriter { do { try unsafeReentrantWrite { db in - let region = try observation.observedRegion(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = DispatchQueue.main + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) { + // Initial value & selected region + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { startValue = value } - - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = DispatchQueue.main + db.add(transactionObserver: observer, extent: .observerLifetime) } } catch { @@ -375,20 +391,25 @@ extension DatabaseWriter { // has the default scheduling .mainQueue asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = DispatchQueue.main + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) { + // Initial value & selected region + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { DispatchQueue.main.async { onChange(value) } } - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = DispatchQueue.main db.add(transactionObserver: observer, extent: .observerLifetime) } catch { DispatchQueue.main.async { @@ -402,22 +423,31 @@ extension DatabaseWriter { // Use case: observation must not block the target queue asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = queue + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if startImmediately, - let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) - { - queue.async { - onChange(value) + // Initial value & selected region + if startImmediately { + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { + queue.async { + onChange(value) + } + } + } else if observation.observesSelectedRegion { + (_, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) } } - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = queue db.add(transactionObserver: observer, extent: .observerLifetime) } catch { queue.async { @@ -448,20 +478,29 @@ extension DatabaseWriter { do { try unsafeReentrantWrite { db in - let region = try observation.observedRegion(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = nil + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if startImmediately, - let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) - { - startValue = value + // Initial value & selected region + if startImmediately { + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { + startValue = value + } + } else if observation.observesSelectedRegion { + (_, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } } - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = nil db.add(transactionObserver: observer, extent: .observerLifetime) } } catch { @@ -474,13 +513,17 @@ extension DatabaseWriter { // queue on which the onChange and onError callbacks are called. asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db) - let reducer = try observation.makeReducer(db) - - // Start observing the database - observer.region = region - observer.reducer = reducer observer.notificationQueue = nil + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) + + // Selected region + if observation.observesSelectedRegion { + (_, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } + db.add(transactionObserver: observer, extent: .observerLifetime) } catch { onError(error) @@ -545,7 +588,7 @@ public class DatabaseFuture { /// /// Instances of AnyDatabaseWriter forward their methods to an arbitrary /// underlying database writer. -public final class AnyDatabaseWriter : DatabaseWriter { +public final class AnyDatabaseWriter: DatabaseWriter { private let base: DatabaseWriter /// Creates a database writer that wraps a base database writer. @@ -608,7 +651,10 @@ public final class AnyDatabaseWriter : DatabaseWriter { #if compiler(>=5.0) /// :nodoc: - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + public func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) + { base.asyncWrite(updates, completion: completion) } #endif @@ -617,12 +663,12 @@ public final class AnyDatabaseWriter : DatabaseWriter { public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { base.asyncWriteWithoutTransaction(updates) } - + /// :nodoc: public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { return try base.unsafeReentrantWrite(updates) } - + // MARK: - Functions /// :nodoc: diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index d0abb0e6a..02a7925d2 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -23,7 +23,7 @@ public struct PreparedRequest { { self.init(statement: statement, adapter: adapter, supplementaryFetch: nil) } - + init( statement: SelectStatement, adapter: RowAdapter?, @@ -62,7 +62,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// 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. @@ -86,7 +86,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { } extension FetchRequest { - + /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { return AdaptedFetchRequest(self, adapter) @@ -134,7 +134,7 @@ extension FetchRequest { // MARK: - AdaptedFetchRequest /// An adapted request. -public struct AdaptedFetchRequest : FetchRequest { +public struct AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder private let base: Base @@ -175,7 +175,7 @@ public struct AdaptedFetchRequest : FetchRequest { /// /// An AnyFetchRequest forwards its operations to an underlying request, /// hiding its specifics. -public struct AnyFetchRequest : FetchRequest { +public struct AnyFetchRequest: FetchRequest { public typealias RowDecoder = T private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 28734b9e9..d0328e5af 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,14 +1,17 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A database row. -public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible { +public final class Row: Equatable, Hashable, RandomAccessCollection, + ExpressibleByDictionaryLiteral, CustomStringConvertible, + CustomDebugStringConvertible +{ // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. let impl: RowImpl @@ -45,7 +48,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// let bookRows = row.prefetchedRows["books"] /// print(bookRows[0]) /// // Prints [id:42 title:"Moby-Dick"] - public internal(set) var prefetchedRows: PrefetchedRowsView = PrefetchedRowsView() + public internal(set) var prefetchedRows = PrefetchedRowsView() // MARK: - Building rows @@ -126,8 +129,13 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// The row is implemented on top of StatementCopyRowImpl, which *copies* /// the values from the SQLite statement so that further iteration of the /// statement does not modify the row. - convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, statementRef: Unmanaged) { - self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames)) + convenience init( + copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, + statementRef: Unmanaged) + { + self.init(impl: StatementCopyRowImpl( + sqliteStatement: sqliteStatement, + columnNames: statementRef.takeUnretainedValue().columnNames)) } init(impl: RowImpl) { @@ -139,7 +147,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl } extension Row { - + // MARK: - Columns /// The names of columns in the row. @@ -416,7 +424,12 @@ extension Row { /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). @inlinable - public subscript(_ column: Column) -> Value? { + public subscript(_ column: Column) + -> Value? + where + Value: DatabaseValueConvertible & StatementColumnConvertible, + Column: ColumnExpression + { return self[column.name] } @@ -448,7 +461,12 @@ extension Row { /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). @inlinable - public subscript(_ column: Column) -> Value { + public subscript(_ column: Column) + -> Value + where + Value: DatabaseValueConvertible & StatementColumnConvertible, + Column: ColumnExpression + { return self[column.name] } @@ -565,7 +583,7 @@ extension Row { } return Record(row: scopedRow) } - + /// Returns the eventual record associated with the given scope. /// /// For example: @@ -761,7 +779,7 @@ extension Row { /// try dbQueue.read { db in /// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RowCursor : Cursor { +public final class RowCursor: Cursor { public let statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _row: Row // Reused for performance @@ -772,6 +790,9 @@ public final class RowCursor : Cursor { self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) self._sqliteStatement = statement.sqliteStatement statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { @@ -833,7 +854,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RowCursor + { return try RowCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -848,7 +874,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Row] + { // The cursor reuses a single mutable row. Return immutable copies. return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() }) } @@ -864,7 +895,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Row? + { let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) // Keep cursor alive until we can copy the fetched row return try withExtendedLifetime(cursor) { @@ -905,7 +941,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> RowCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -924,7 +966,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Row] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -943,7 +991,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Row? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -1079,7 +1133,7 @@ extension FetchRequest where RowDecoder == Row { return try Row.fetchOne(db, self) } } - + // ExpressibleByDictionaryLiteral extension Row { @@ -1198,7 +1252,7 @@ extension Row { if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty { return description } - let prefix = repeatElement(" ", count: level + 1).joined(separator: "") + let prefix = repeatElement(" ", count: level + 1).joined() var str = "" if level == 0 { str = "▿ " + description @@ -1234,7 +1288,7 @@ extension Row { // MARK: - RowIndex /// Indexes to (ColumnName, DatabaseValue) pairs in a database row. -public struct RowIndex : Comparable, Strideable { +public struct RowIndex: Comparable, Strideable { let index: Int init(_ index: Int) { self.index = index } } @@ -1386,7 +1440,7 @@ extension Row { } return names } - + /// Returns the row associated with the given scope. /// /// For example: @@ -1461,7 +1515,7 @@ extension Row { public var isEmpty: Bool { return prefetches.isEmpty } - + /// The keys for available prefetched rows /// /// For example: @@ -1483,7 +1537,7 @@ extension Row { } return result } - + /// Returns the prefetched rows associated with the given key. /// /// For example: @@ -1538,13 +1592,20 @@ extension OrderedDictionary where Key == String, Value == Row.Prefetch { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } + func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView func columnName(atUncheckedIndex index: Int) -> String - func hasNull(atUncheckedIndex index:Int) -> Bool + func hasNull(atUncheckedIndex index: Int) -> Bool func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue - func fastDecode(_ type: Value.Type, atUncheckedIndex index: Int) -> Value - func fastDecodeIfPresent(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? - func dataNoCopy(atUncheckedIndex index:Int) -> Data? + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value? + func dataNoCopy(atUncheckedIndex index: Int) -> Data? /// Returns the index of the leftmost column that matches *name* (case-insensitive) func index(ofColumn name: String) -> Int? @@ -1558,7 +1619,7 @@ protocol RowImpl { extension RowImpl { func copiedRow(_ row: Row) -> Row { // unless customized, assume unsafe and unadapted row - return Row(impl: ArrayRowImpl(columns: row.map { $0 })) + return Row(impl: ArrayRowImpl(columns: Array(row))) } func unscopedRow(_ row: Row) -> Row { @@ -1576,7 +1637,7 @@ extension RowImpl { return Row.ScopesView() } - func hasNull(atUncheckedIndex index:Int) -> Bool { + func hasNull(atUncheckedIndex index: Int) -> Bool { // unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization) return databaseValue(atUncheckedIndex: index).isNull } @@ -1601,7 +1662,7 @@ extension RowImpl { conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index)) } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) return Data.decodeIfPresent( from: databaseValue(atUncheckedIndex: index), @@ -1611,7 +1672,7 @@ extension RowImpl { // TODO: merge with StatementCopyRowImpl eventually? /// See Row.init(dictionary:) -private struct ArrayRowImpl : RowImpl { +private struct ArrayRowImpl: RowImpl { let columns: [(String, DatabaseValue)] init(columns: [(String, DatabaseValue)]) { @@ -1647,13 +1708,16 @@ private struct ArrayRowImpl : RowImpl { // TODO: merge with ArrayRowImpl eventually? /// See Row.init(copiedFromStatementRef:sqliteStatement:) -private struct StatementCopyRowImpl : RowImpl { +private struct StatementCopyRowImpl: RowImpl { let dbValues: ContiguousArray let columnNames: [String] init(sqliteStatement: SQLiteStatement, columnNames: [String]) { let sqliteStatement = sqliteStatement - self.dbValues = ContiguousArray((0.. let sqliteStatement: SQLiteStatement let lowercaseColumnIndexes: [String: Int] @@ -1694,7 +1758,8 @@ private struct StatementRowImpl : RowImpl { self.statementRef = statementRef self.sqliteStatement = sqliteStatement // Optimize row[columnName] - let lowercaseColumnNames = (0.. Bool { + func hasNull(atUncheckedIndex index: Int) -> Bool { // Avoid extracting values, because this modifies the SQLite statement. return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { return nil } @@ -1761,7 +1826,7 @@ private struct StatementRowImpl : RowImpl { } // This one is not optimized at all, since it is only used in fatal conversion errors, so far -private struct SQLiteStatementRowImpl : RowImpl { +private struct SQLiteStatementRowImpl: RowImpl { let sqliteStatement: SQLiteStatement var count: Int { return Int(sqlite3_column_count(sqliteStatement)) } var isFetched: Bool { return true } @@ -1784,7 +1849,7 @@ private struct SQLiteStatementRowImpl : RowImpl { } /// See Row.init() -private struct EmptyRowImpl : RowImpl { +private struct EmptyRowImpl: RowImpl { var count: Int { return 0 } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index b9ab95c8c..87662cd31 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -100,7 +100,7 @@ public struct LayoutedColumnMapping { /// LayoutedColumnMapping adopts LayoutedRowAdapter /// /// :nodoc: -extension LayoutedColumnMapping : LayoutedRowAdapter { +extension LayoutedColumnMapping: LayoutedRowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns self. @@ -117,7 +117,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter { } /// :nodoc: -extension LayoutedColumnMapping : RowLayout { +extension LayoutedColumnMapping: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the index of the leftmost column named `name`, in a @@ -171,7 +171,7 @@ public protocol RowLayout { func layoutIndex(ofColumn name: String) -> Int? } -extension SelectStatement : RowLayout { +extension SelectStatement: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var layoutColumns: [(Int, String)] { @@ -270,7 +270,7 @@ public struct EmptyRowAdapter: RowAdapter { /// /// // [foo:"bar"] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct ColumnMapping : RowAdapter { +public struct ColumnMapping: RowAdapter { /// A dictionary from mapped column names to column names in a base row. let mapping: [String: String] @@ -287,7 +287,12 @@ public struct ColumnMapping : RowAdapter { .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout.layoutIndex(ofColumn: baseColumn) else { let columnNames = layout.layoutColumns.map { $0.1 } - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).") + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ + Mapping references missing column \(baseColumn). \ + Valid column names are: \(columnNames.joined(separator: ", ")). + """) } let baseIndex = layout.layoutColumns[index].0 return (baseIndex, mappedColumn) @@ -304,7 +309,7 @@ public struct ColumnMapping : RowAdapter { /// /// // [baz:3] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct SuffixRowAdapter : RowAdapter { +public struct SuffixRowAdapter: RowAdapter { /// The suffix index let index: Int @@ -331,7 +336,7 @@ public struct SuffixRowAdapter : RowAdapter { /// /// // [bar:2 baz:3] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct RangeRowAdapter : RowAdapter { +public struct RangeRowAdapter: RowAdapter { /// The range let range: CountableRange @@ -376,7 +381,7 @@ public struct RangeRowAdapter : RowAdapter { /// if let barRow = row.scopes["bar"] { /// barRow["value"] // "bar" /// } -public struct ScopeAdapter : RowAdapter { +public struct ScopeAdapter: RowAdapter { /// The base adapter let base: RowAdapter @@ -439,15 +444,15 @@ public struct ScopeAdapter : RowAdapter { } /// The LayoutedRowAdapter for ScopeAdapter -struct LayoutedScopeAdapter : LayoutedRowAdapter { +struct LayoutedScopeAdapter: LayoutedRowAdapter { let mapping: LayoutedColumnMapping let scopes: [String: LayoutedRowAdapter] } -struct ChainedAdapter : RowAdapter { +struct ChainedAdapter: RowAdapter { let first: RowAdapter let second: RowAdapter - + func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) } @@ -458,7 +463,7 @@ extension Row { convenience init(base: Row, adapter: LayoutedRowAdapter) { self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } - + /// Returns self if adapter is nil func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row { guard let adapter = adapter else { @@ -468,7 +473,7 @@ extension Row { } } -struct AdaptedRowImpl : RowImpl { +struct AdaptedRowImpl: RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping @@ -517,7 +522,7 @@ struct AdaptedRowImpl : RowImpl { return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex) } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex) } @@ -533,7 +538,7 @@ struct AdaptedRowImpl : RowImpl { func copiedRow(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } - + func unscopedRow(_ row: Row) -> Row { assert(adapter.mapping.scopes.isEmpty) return Row(base: base, adapter: adapter.mapping) diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index 49bc2b3b0..9253c01d8 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -7,23 +7,23 @@ public struct SQLInterpolation: StringInterpolationProtocol { get { return context.arguments! } set { context.arguments = newValue } } - + public init(literalCapacity: Int, interpolationCount: Int) { sql = "" sql.reserveCapacity(literalCapacity + interpolationCount) } - + /// "SELECT * FROM player" public mutating func appendLiteral(_ sql: String) { self.sql += sql } - + /// "SELECT * FROM \(sql: "player")" public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) { self.sql += sql self.arguments += arguments } - + /// "SELECT * FROM player WHERE \(literal: condition)" public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) { sql += sqlLiteral.sql diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index e95e58b88..161cc24f3 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -1,4 +1,5 @@ -/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). +/// SQLLiteral is a type which support [SQL +/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). /// /// For example: /// @@ -9,8 +10,8 @@ /// try db.execute(literal: query) /// } public struct SQLLiteral { - private(set) public var sql: String - private(set) public var arguments: StatementArguments + public private(set) var sql: String + public private(set) var arguments: StatementArguments /// Creates an SQLLiteral from a plain SQL string, and eventual arguments. /// @@ -63,7 +64,7 @@ extension SQLLiteral { public mutating func append(literal sqlLiteral: SQLLiteral) { self += sqlLiteral } - + /// Appends a plain SQL string to the receiver, and eventual arguments. /// /// let name = "O'Brien" diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 60ccd4360..5dd439fb0 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -1,5 +1,5 @@ /// A FetchRequest built from raw SQL. -public struct SQLRequest : FetchRequest { +public struct SQLRequest: FetchRequest { /// There are two statement caches: one "public" for statements generated by /// the user, and one "internal" for the statements generated by GRDB. Those /// are separated so that GRDB has no opportunity to inadvertently modify @@ -30,10 +30,10 @@ public struct SQLRequest : FetchRequest { /// The request adapter public var adapter: RowAdapter? - + private var sqlLiteral: SQLLiteral private let cache: Cache? - + /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// @@ -51,8 +51,16 @@ public struct SQLRequest : FetchRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) { - self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil) + public init( + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil, + cached: Bool = false) + { + self.init( + literal: SQLLiteral(sql: sql, arguments: arguments), + adapter: adapter, + fromCache: cached ? .public : nil) } /// Creates a request from an SQLLiteral, and optional row adapter. @@ -80,7 +88,7 @@ public struct SQLRequest : FetchRequest { public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) { self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil) } - + /// Creates an SQL request from any other fetch request. /// /// - parameters: @@ -89,7 +97,13 @@ public struct SQLRequest : FetchRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: An SQLRequest - public init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder { + public init( + _ db: Database, + request: Request, + cached: Bool = false) + throws + where Request: FetchRequest, Request.RowDecoder == RowDecoder + { let request = try request.makePreparedRequest(db, forSingleResult: false) self.init( literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments), diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 93318631b..087926c45 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -43,7 +43,12 @@ final class SchedulingWatchdog { return try body() } - static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + static func preconditionValidQueue( + _ db: Database, + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 7fabe2ee2..c08b1445a 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -16,7 +16,14 @@ final class SerializedDatabase { /// The dispatch queue private let queue: DispatchQueue - init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws { + init( + path: String, + configuration: Configuration = Configuration(), + schemaCache: DatabaseSchemaCache, + defaultLabel: String, + purpose: String? = nil) + throws + { // According to https://www.sqlite.org/threadsafe.html // // > SQLite support three different threading modes: @@ -193,12 +200,25 @@ final class SerializedDatabase { } /// Fatal error if current dispatch queue is not valid. - func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + func preconditionValidQueue( + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line) } /// Fatal error if a transaction has been left opened. - private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { - GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line) + private func preconditionNoUnsafeTransactionLeft( + _ db: Database, + _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", + file: StaticString = #file, + line: UInt = #line) + { + GRDBPrecondition( + configuration.allowsUnsafeTransactions || !db.isInsideTransaction, + message(), + file: file, + line: line) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 73a76d472..19aa651b0 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A raw SQLite statement, suitable for the SQLite C API. @@ -43,6 +43,7 @@ public class Statement { /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) + /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( database: Database, @@ -56,18 +57,25 @@ public class Statement { var sqliteStatement: SQLiteStatement? = nil // sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 #if GRDBCUSTOMSQLITE || GRDBCIPHER - let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd) + let code = sqlite3_prepare_v3( + database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + &sqliteStatement, statementEnd) #else let code: Int32 if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { - code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd) + code = sqlite3_prepare_v3( + database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + &sqliteStatement, statementEnd) } else { code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd) } #endif guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart)) + throw DatabaseError( + resultCode: code, + message: database.lastErrorMessage, + sql: String(cString: statementStart)) } guard let statement = sqliteStatement else { @@ -102,7 +110,7 @@ public class Statement { // Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)" fileprivate lazy var sqliteArgumentNames: [String?] = { - return (0.. Self { + static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self { let authorizer = StatementCompilationAuthorizer() - database.authorizer = authorizer - defer { database.authorizer = nil } - - return try sql.utf8CString.withUnsafeBufferPointer { buffer in - let statementStart = buffer.baseAddress! - var statementEnd: UnsafePointer? = nil - guard let statement = try self.init( - database: database, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: prepFlags, - authorizer: authorizer) else - { - throw DatabaseError( - resultCode: .SQLITE_ERROR, - message: "empty statement", - sql: sql, - arguments: nil) + return try db.withAuthorizer(authorizer) { + try sql.utf8CString.withUnsafeBufferPointer { buffer in + let statementStart = buffer.baseAddress! + var statementEnd: UnsafePointer? = nil + guard let statement = try self.init( + database: db, + statementStart: statementStart, + statementEnd: &statementEnd, + prepFlags: prepFlags, + authorizer: authorizer) else + { + throw DatabaseError( + resultCode: .SQLITE_ERROR, + message: "empty statement", + sql: sql) + } + + let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators) + guard remainingSQL.isEmpty else { + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ + Multiple statements found. To execute multiple statements, \ + use Database.execute(sql:) instead. + """, + sql: sql) + } + + return statement } - - let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators) - guard remainingSQL.isEmpty else { - throw DatabaseError( - resultCode: .SQLITE_MISUSE, - message: "Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead.", - sql: sql, - arguments: nil) - } - - return statement } } } @@ -271,9 +275,13 @@ extension StatementProtocol where Self: Statement { /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// } -public final class SelectStatement : Statement { +public final class SelectStatement: Statement { + // Database region is computed during statement compilation, and maybe + // optimized when statement is compiled for a QueryInterfaceRequest, in + // order to perform focused database observation. See + // SQLQueryGenerator.optimizedDatabaseRegion(_:_:) /// The database region that the statement looks into. - public private(set) var databaseRegion = DatabaseRegion() + public internal(set) var databaseRegion = DatabaseRegion() /// Creates a prepared statement. Returns nil if the compiled string is /// blank or empty. @@ -285,7 +293,7 @@ public final class SelectStatement : Statement { /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - authorizer: A StatementCompilationAuthorizer + /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( database: Database, @@ -301,8 +309,12 @@ public final class SelectStatement : Statement { prepFlags: prepFlags, authorizer: authorizer) - GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") - GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") + GRDBPrecondition( + authorizer.invalidatesDatabaseSchemaCache == false, + "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") + GRDBPrecondition( + authorizer.transactionEffect == nil, + "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") self.databaseRegion = authorizer.databaseRegion } @@ -320,7 +332,7 @@ public final class SelectStatement : Statement { /// Cache for index(ofColumn:). Keys are lowercase. private lazy var columnIndexes: [String: Int] = { - return Dictionary( + Dictionary( self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) }, uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes }() @@ -353,7 +365,6 @@ public final class SelectStatement : Statement { message: database.lastErrorMessage, sql: sql, arguments: arguments) - } } @@ -377,6 +388,9 @@ final class StatementCursor: Cursor { _statement = statement _sqliteStatement = statement.sqliteStatement _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { @@ -418,7 +432,7 @@ final class StatementCursor: Cursor { /// try statement.execute(arguments: ["Barbara"]) /// return .commit /// } -public final class UpdateStatement : Statement { +public final class UpdateStatement: Statement { enum TransactionEffect { case beginTransaction case commitTransaction @@ -445,7 +459,7 @@ public final class UpdateStatement : Statement { /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - authorizer: A StatementCompilationAuthorizer + /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( database: Database, @@ -473,38 +487,11 @@ public final class UpdateStatement : Statement { SchedulingWatchdog.preconditionValidQueue(database) prepare(withArguments: arguments) try reset() - database.updateStatementWillExecute(self) - while true { - switch sqlite3_step(sqliteStatement) { - case SQLITE_ROW: - // The statement did return a row, and the user ignores the - // content of this row: - // - // try db.execute(sql: "SELECT ...") - // - // That's OK: maybe the selected rows perform side effects. - // For example: - // - // try db.execute(sql: "SELECT sqlcipher_export(...)") - // - // Or maybe the user doesn't know that the executed statement - // return rows (https://github.com/groue/GRDB.swift/issues/15); - // - // try db.execute(sql: "PRAGMA journal_mode=WAL") - // - // It is thus important that we consume *all* rows. - continue - - case SQLITE_DONE: - try database.updateStatementDidExecute(self) - return - - case let code: - try database.updateStatementDidFail(self) - throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter. - } - } + // Statement does not know how to execute itself, because it does not + // know how to handle its errors, or if truncate optimisation should be + // prevented or not. Database knows. + try database.executeUpdateStatement(self) } } @@ -589,7 +576,9 @@ public final class UpdateStatement : Statement { /// .filter(sql: "team = :team", arguments: ["team": "Blue"]) /// .filter(sql: "score > ?", arguments: [1000]) /// .fetchAll(db) -public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { +public struct StatementArguments: CustomStringConvertible, Equatable, + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral +{ private(set) var values: [DatabaseValue] = [] private(set) var namedValues: [String: DatabaseValue] = [:] @@ -667,7 +656,9 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) { + public init(_ sequence: Sequence) + where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) + { namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) }) } @@ -843,33 +834,48 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl /// append(contentsOf:) method. public static func += (lhs: inout StatementArguments, rhs: StatementArguments) { let replacedValues = lhs.append(contentsOf: rhs) - GRDBPrecondition(replacedValues.isEmpty, "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))") + GRDBPrecondition( + replacedValues.isEmpty, + "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))") } // MARK: Not Public - mutating func extractBindings(forStatement statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] { + mutating func extractBindings( + forStatement statement: Statement, + allowingRemainingValues: Bool) + throws -> [DatabaseValue] + { let initialValuesCount = values.count let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in if let argumentName = argumentName { if let dbValue = namedValues[argumentName] { return dbValue } else if values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "missing statement argument: \(argumentName)", + sql: statement.sql) } else { return values.removeFirst() } } else { if values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)", + sql: statement.sql) } else { return values.removeFirst() } } } if !allowingRemainingValues && !values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)", + sql: statement.sql) } return bindings } @@ -907,7 +913,7 @@ extension StatementArguments { public var description: String { let valuesDescriptions = values.map { $0.description } let namedValuesDescriptions = namedValues.map { (key, value) -> String in - return "\(String(reflecting: key)): \(value)" + "\(String(reflecting: key)): \(value)" } return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]" } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index e94bfa4a5..ec72fb117 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,16 +1,16 @@ #if os(Linux) - import Glibc +import Glibc #endif #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A protocol around sqlite3_set_authorizer -protocol StatementAuthorizer : class { +protocol StatementAuthorizer: AnyObject { func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, @@ -21,7 +21,7 @@ protocol StatementAuthorizer : class { } /// A class that gathers information about one statement during its compilation. -final class StatementCompilationAuthorizer : StatementAuthorizer { +final class StatementCompilationAuthorizer: StatementAuthorizer { /// What this statements reads var databaseRegion = DatabaseRegion() @@ -47,7 +47,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })") + // print(""" + // StatementCompilationAuthorizer: \ + // \(actionCode) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) + // """) switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, @@ -67,8 +71,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_OK case SQLITE_READ: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } - guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } + guard let columnName = cString2.map(String.init) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table databaseRegion.formUnion(DatabaseRegion(table: tableName)) @@ -79,7 +83,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_OK case SQLITE_INSERT: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } databaseEventKinds.append(.insert(tableName: tableName)) return SQLITE_OK @@ -100,8 +104,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_IGNORE case SQLITE_UPDATE: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } - guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } + guard let columnName = cString2.map(String.init) else { return SQLITE_OK } insertUpdateEventKind(tableName: tableName, columnName: columnName) return SQLITE_OK @@ -118,7 +122,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { case SQLITE_SAVEPOINT: guard let cString1 = cString1 else { return SQLITE_OK } - guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let name = cString2.map(String.init) else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginSavepoint(name) } else if strcmp(cString1, "RELEASE") == 0 { @@ -168,7 +172,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { // /// Warning: to perform well, this authorizer must be used during statement /// execution, not during statement compilation. -final class TruncateOptimizationBlocker : StatementAuthorizer { +final class TruncateOptimizationBlocker: StatementAuthorizer { func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, @@ -177,8 +181,11 @@ final class TruncateOptimizationBlocker : StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })") + // print(""" + // TruncateOptimizationBlocker: \ + // \(actionCode) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) + // """) return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK } } - diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 2ae6f87ba..dd0077f59 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The StatementColumnConvertible protocol grants access to the low-level C @@ -77,6 +77,9 @@ public final class FastDatabaseValueCursor = try Optional.fetchCursor(db, sql: "SELECT email FROM player") +/// let emails: FastNullableDatabaseValueCursor = +/// try Optional.fetchCursor(db, sql: "SELECT email FROM player") /// while let email = emails.next() { // String? /// print(email ?? "") /// } /// } -public final class FastNullableDatabaseValueCursor : Cursor { +public final class FastNullableDatabaseValueCursor: Cursor + where Value: DatabaseValueConvertible & StatementColumnConvertible +{ @usableFromInline let _statement: SelectStatement @usableFromInline let _columnIndex: Int32 @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline var _done = false - + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement @@ -130,6 +136,9 @@ public final class FastNullableDatabaseValueCursor FastDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -202,7 +216,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -217,15 +236,23 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { // fetchOne returns nil if there is no row, or if there is a row with a null value - let cursor = try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) + let cursor = try FastNullableDatabaseValueCursor( + statement: statement, + arguments: arguments, + adapter: adapter) return try cursor.next() ?? nil } } extension DatabaseValueConvertible where Self: StatementColumnConvertible { - + // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. @@ -247,7 +274,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -262,7 +295,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -277,7 +316,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -304,7 +349,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A FetchRequest. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> FastDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -426,7 +473,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -441,7 +493,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } @@ -469,7 +526,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -484,7 +547,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -511,7 +580,9 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - request: A FetchRequest. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> FastNullableDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -532,7 +603,11 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } } -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { +extension FetchRequest + where + RowDecoder: _OptionalProtocol, + RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible +{ // MARK: Fetching Optional values diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index 444dc0c40..a7f7c6bc4 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -2,8 +2,8 @@ import CoreGraphics /// CGFloat adopts DatabaseValueConvertible -extension CGFloat : DatabaseValueConvertible { - +extension CGFloat: DatabaseValueConvertible { + /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return Double(self).databaseValue diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 8c4202bdc..281fdd920 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -1,14 +1,14 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Data is convertible to and from DatabaseValue. -extension Data : DatabaseValueConvertible, StatementColumnConvertible { +extension Data: DatabaseValueConvertible, StatementColumnConvertible { @inlinable public init(sqliteStatement: SQLiteStatement, index: Int32) { if let bytes = sqlite3_column_blob(sqliteStatement, index) { diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index f84be4909..0057f4a6f 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,17 +1,17 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// DatabaseDateComponents reads and stores DateComponents in the database. -public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible { - +public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible { + /// The available formats for reading and storing date components. - public enum Format : String { + public enum Format: String { /// The format "yyyy-MM-dd". case YMD = "yyyy-MM-dd" @@ -81,8 +81,10 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen - let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in - SQLiteDateParser().components(cString: cString, length: length) + let optionalComponents = cString.withMemoryRebound( + to: Int8.self, + capacity: length + 1 /* trailing \0 */) { cString in + SQLiteDateParser().components(cString: cString, length: length) } guard let components = optionalComponents else { fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) @@ -122,7 +124,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 let nanosecond = dateComponents.nanosecond ?? 0 - timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) + timeString = String( + format: "%02d:%02d:%02d.%03d", + hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) default: timeString = nil } diff --git a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift index d5fedd5ad..4a3e3c53b 100644 --- a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift +++ b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift @@ -26,14 +26,22 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere } } -extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { +extension DatabaseValueConvertible + where + Self: Decodable & ReferenceConvertible, + Self.ReferenceType: DatabaseValueConvertible +{ public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { // Preserve custom database decoding return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) } } } -extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { +extension DatabaseValueConvertible + where + Self: Encodable & ReferenceConvertible, + Self.ReferenceType: DatabaseValueConvertible +{ public var databaseValue: DatabaseValue { // Preserve custom database encoding return (self as! ReferenceType).databaseValue diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 4742c84ed..c51b103fd 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,16 +1,16 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if !os(Linux) /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. -extension NSDate : DatabaseValueConvertible { +extension NSDate: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { @@ -38,7 +38,7 @@ extension NSDate : DatabaseValueConvertible { /// Date is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. -extension Date : DatabaseValueConvertible { +extension Date: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { @@ -149,7 +149,7 @@ private let storageDateFormatter: DateFormatter = { formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter - }() +}() // The NSCalendar for stored dates. private let UTCCalendar: Calendar = { @@ -157,4 +157,4 @@ private let UTCCalendar: Calendar = { calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! return calendar - }() +}() diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 8bd9d2ecf..5a29bc4a4 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -2,7 +2,7 @@ import Foundation /// NSData is convertible to and from DatabaseValue. -extension NSData : DatabaseValueConvertible { +extension NSData: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNull.swift b/GRDB/Core/Support/Foundation/NSNull.swift index e954befe4..af531bab5 100644 --- a/GRDB/Core/Support/Foundation/NSNull.swift +++ b/GRDB/Core/Support/Foundation/NSNull.swift @@ -1,7 +1,7 @@ import Foundation /// NSNull adopts DatabaseValueConvertible -extension NSNull : DatabaseValueConvertible { +extension NSNull: DatabaseValueConvertible { /// Returns DatabaseValue.null. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 2caf60868..7c33a68fb 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -1,10 +1,16 @@ #if !os(Linux) import Foundation -private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) +private let integerRoundingBehavior = NSDecimalNumberHandler( + roundingMode: .plain, + scale: 0, + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false) /// NSNumber adopts DatabaseValueConvertible -extension NSNumber : DatabaseValueConvertible { +extension NSNumber: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { @@ -34,13 +40,17 @@ extension NSNumber : DatabaseValueConvertible { return Int64(intValue).databaseValue case "L": let uint = uintValue - GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database") + GRDBPrecondition( + UInt64(uint) <= UInt64(Int64.max), + "could not convert \(uint) to an Int64 that can be stored in the database") return Int64(uint).databaseValue case "q": return Int64(int64Value).databaseValue case "Q": let uint64 = uint64Value - GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database") + GRDBPrecondition( + uint64 <= UInt64(Int64.max), + "could not convert \(uint64) to an Int64 that can be stored in the database") return Int64(uint64).databaseValue case "f": return Double(floatValue).databaseValue diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index d5455bed4..ba9941012 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -2,7 +2,7 @@ import Foundation /// NSString adopts DatabaseValueConvertible -extension NSString : DatabaseValueConvertible { +extension NSString: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index cd42663c0..b6630fe39 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -58,6 +58,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + // swiftlint:disable:next line_length withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer) } diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 4cc95b1b4..6990562e1 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -2,7 +2,7 @@ import Foundation #if !os(Linux) /// NSURL stores its absoluteString in the database. -extension NSURL : DatabaseValueConvertible { +extension NSURL: DatabaseValueConvertible { /// Returns a value that can be stored in the database. /// (the URL's absoluteString). @@ -21,4 +21,4 @@ extension NSURL : DatabaseValueConvertible { #endif /// URL stores its absoluteString in the database. -extension URL : DatabaseValueConvertible { } +extension URL: DatabaseValueConvertible { } diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 8ed8d68b0..92447987c 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if !os(Linux) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index f04cfd071..b37fb8d80 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -13,7 +13,8 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. - /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Bool.Type) throws -> Bool { if let result = Bool.fromDatabaseValue(dbValue) { @@ -131,9 +132,10 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. - /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { if let type = T.self as? DatabaseValueConvertible.Type { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows custom database decoding, such as decoding Date from @@ -159,7 +161,7 @@ private struct DatabaseValueDecoder: Decoder { // Decoder let codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey : Any] { return [:] } + var userInfo: [CodingUserInfoKey: Any] { return [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { throw DecodingError.typeMismatch( diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 8aa705b32..bd37c0bde 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -1,4 +1,4 @@ -private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { +private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void var codingPath: [CodingKey] { return [] } @@ -34,7 +34,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. - mutating func encode(_ value: T) throws where T : Encodable { + mutating func encode(_ value: T) throws where T: Encodable { if let dbValueConvertible = value as? DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. // This allows us to encode Date as String, for example. @@ -45,7 +45,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { } } -private struct DatabaseValueEncoder : Encoder { +private struct DatabaseValueEncoder: Encoder { let encode: (DatabaseValue) -> Void /// The path of coding keys taken to get to this point in encoding. @@ -53,7 +53,7 @@ private struct DatabaseValueEncoder : Encoder { var codingPath: [CodingKey] { return [] } /// Any contextual information set by the user for encoding. - var userInfo: [CodingUserInfoKey : Any] = [:] + var userInfo: [CodingUserInfoKey: Any] = [:] init(encode: @escaping (DatabaseValue) -> Void) { self.encode = encode @@ -64,7 +64,8 @@ private struct DatabaseValueEncoder : Encoder { /// - parameter type: The key type to use for the container. /// - returns: A new keyed encoding container. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { fatalError("keyed encoding is not supported") } @@ -73,7 +74,8 @@ private struct DatabaseValueEncoder : Encoder { /// /// - returns: A new empty unkeyed container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("unkeyed encoding is not supported") } @@ -83,7 +85,8 @@ private struct DatabaseValueEncoder : Encoder { /// - returns: A new empty single value container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer { return DatabaseValueEncodingContainer(encode: encode) } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 099b742fe..0914b0dcf 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - Value Types @@ -500,11 +500,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.capitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.capitalized + public static let capitalize = + DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.capitalized } /// An SQL function that returns the Swift built-in lowercased @@ -519,11 +520,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.lowercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.lowercased() + public static let lowercase = + DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.lowercased() } /// An SQL function that returns the Swift built-in uppercased @@ -538,11 +540,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.uppercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.uppercased() + public static let uppercase = + DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.uppercased() } } @@ -560,11 +563,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedCapitalized + public static let localizedCapitalize = + DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedCapitalized } /// An SQL function that returns the Swift built-in @@ -580,11 +584,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedLowercase + public static let localizedLowercase = + DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedLowercase } /// An SQL function that returns the Swift built-in @@ -600,11 +605,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedUppercase + public static let localizedUppercase = + DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedUppercase } } @@ -637,8 +643,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in - return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) + public static let unicodeCompare = + DatabaseCollation("swiftCompare") { (lhs, rhs) in + (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) } /// A collation, or SQL string comparison function, that compares strings @@ -655,8 +662,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in - return lhs.caseInsensitiveCompare(rhs) + public static let caseInsensitiveCompare = + DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in + lhs.caseInsensitiveCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -673,8 +681,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in - return lhs.localizedCaseInsensitiveCompare(rhs) + public static let localizedCaseInsensitiveCompare = + DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in + return lhs.localizedCaseInsensitiveCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -691,8 +700,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in - return lhs.localizedCompare(rhs) + public static let localizedCompare = + DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in + lhs.localizedCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -709,7 +719,8 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in - return lhs.localizedStandardCompare(rhs) + public static let localizedStandardCompare = + DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in + lhs.localizedStandardCompare(rhs) } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 096a246e8..13cd61a2e 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1,13 +1,13 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { - + // MARK: - Database Observation /// Add a transaction observer, so that it gets notified of @@ -17,7 +17,10 @@ extension Database { /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). - public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) { + public func add( + transactionObserver: TransactionObserver, + extent: TransactionObservationExtent = .observerLifetime) + { SchedulingWatchdog.preconditionValidQueue(self) observationBroker.add(transactionObserver: transactionObserver, extent: extent) } @@ -42,11 +45,11 @@ extension Database { /// /// If the transaction is committed, the closure is executed in a protected /// dispatch queue, serialized will all database updates. - public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ()) { - class CommitHandler : TransactionObserver { - let closure: (Database) -> () + public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { + class CommitHandler: TransactionObserver { + let closure: (Database) -> Void - init(_ closure: @escaping (Database) -> ()) { + init(_ closure: @escaping (Database) -> Void) { self.closure = closure } @@ -195,7 +198,7 @@ class DatabaseObservationBroker { } func disableUntilNextTransaction(transactionObserver: TransactionObserver) { - if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) { + if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { observation.isDisabled = true statementObservations.removeFirst { $0.0 === observation } } @@ -203,7 +206,10 @@ class DatabaseObservationBroker { // MARK: - Statement execution - func updateStatementWillExecute(_ statement: UpdateStatement) { + /// Setups observation of changes that are about to be performed by the + /// statement, and returns the authorizer that should be used during + /// statement execution. + func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? { // As statement executes, it may trigger database changes that will // be notified to transaction observers. As a consequence, observers // may disable themselves with stopObservingDatabaseChangesUntilNextTransaction() @@ -282,18 +288,17 @@ class DatabaseObservationBroker { } if observesRowDeletion { - database.authorizer = TruncateOptimizationBlocker() + return TruncateOptimizationBlocker() } else { - database.authorizer = nil + return nil } } func updateStatementDidFail(_ statement: UpdateStatement) throws { // Undo updateStatementWillExecute statementObservations = [] - database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil - + // Reset transactionState before databaseDidRollback eventually // executes other statements. let transactionState = self.transactionState @@ -316,9 +321,8 @@ class DatabaseObservationBroker { func updateStatementDidExecute(_ statement: UpdateStatement) throws { // Undo updateStatementWillExecute statementObservations = [] - database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil - + // Has statement any effect on transaction/savepoints? if let transactionEffect = statement.transactionEffect { switch transactionEffect { @@ -379,7 +383,7 @@ class DatabaseObservationBroker { } } -#if SQLITE_ENABLE_PREUPDATE_HOOK + #if SQLITE_ENABLE_PREUPDATE_HOOK // Called from sqlite3_preupdate_hook private func databaseWillChange(with event: DatabasePreUpdateEvent) { if savepointStack.isEmpty { @@ -392,7 +396,7 @@ class DatabaseObservationBroker { savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations)) } } -#endif + #endif // Called from sqlite3_update_hook private func databaseDidChange(with event: DatabaseEvent) { @@ -597,17 +601,23 @@ class DatabaseObservationBroker { private func installUpdateHook() { let brokerPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in - let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() - broker.databaseDidChange(with: DatabaseEvent( - kind: DatabaseEvent.Kind(rawValue: updateKind)!, - rowID: rowID, - databaseNameCString: databaseNameCString, - tableNameCString: tableNameCString)) - }, brokerPointer) + sqlite3_update_hook( + database.sqliteConnection, + { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in + let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() + broker.databaseDidChange(with: DatabaseEvent( + kind: DatabaseEvent.Kind(rawValue: updateKind)!, + rowID: rowID, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + }, + brokerPointer) #if SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(database.sqliteConnection, { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in + sqlite3_preupdate_hook( + database.sqliteConnection, + // swiftlint:disable:next line_length + { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() broker.databaseWillChange(with: DatabasePreUpdateEvent( connection: databaseConnection!, @@ -616,14 +626,15 @@ class DatabaseObservationBroker { finalRowID: finalRowID, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) - }, brokerPointer) + }, + brokerPointer) #endif } private func uninstallUpdateHook() { sqlite3_update_hook(database.sqliteConnection, nil, nil) #if SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) + sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) #endif } @@ -642,7 +653,7 @@ class DatabaseObservationBroker { /// or rollbacked on a database. /// /// Adopting types must be a class. -public protocol TransactionObserver : class { +public protocol TransactionObserver: AnyObject { /// Filters database changes that should be notified the the /// databaseDidChange(with:) method. @@ -713,7 +724,8 @@ public protocol TransactionObserver : class { /// /// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library /// does not have this enabled, so you'll need to compile your own - /// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md + /// copy using GRDBCustomSQLite. + /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md /// /// The databaseDidChangeWithEvent callback is always available, /// and may provide most/all of what you need. @@ -726,13 +738,13 @@ extension TransactionObserver { /// Default implementation does nothing public func databaseWillCommit() throws { } - + #if SQLITE_ENABLE_PREUPDATE_HOOK /// Default implementation does nothing public func databaseWillChange(with event: DatabasePreUpdateEvent) { } #endif - + /// After this method has been called, the `databaseDidChange(with:)` /// method won't be called until the next transaction. /// @@ -756,7 +768,10 @@ extension TransactionObserver { /// - precondition: This method must be called from `databaseDidChange(with:)`. public func stopObservingDatabaseChangesUntilNextTransaction() { guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else { - fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method") + fatalError(""" + stopObservingDatabaseChangesUntilNextTransaction must be called \ + from the databaseDidChange method + """) } broker.disableUntilNextTransaction(transactionObserver: self) } @@ -801,23 +816,23 @@ final class TransactionObservation { if isDisabled { return false } return observer?.observes(eventsOfKind: eventKind) ?? false } - + #if SQLITE_ENABLE_PREUPDATE_HOOK func databaseWillChange(with event: DatabasePreUpdateEvent) { if isDisabled { return } observer?.databaseWillChange(with: event) } #endif - + func databaseDidChange(with event: DatabaseEvent) { if isDisabled { return } observer?.databaseDidChange(with: event) } - + func databaseWillCommit() throws { try observer?.databaseWillCommit() } - + func databaseDidCommit(_ db: Database) { switch extent { case .observerLifetime, .databaseLifetime: @@ -867,11 +882,11 @@ public enum DatabaseEventKind { var modifiedRegion: DatabaseRegion { switch self { - case .delete(let tableName): + case let .delete(tableName): return DatabaseRegion(table: tableName) - case .insert(let tableName): + case let .insert(tableName): return DatabaseRegion(table: tableName) - case .update(let tableName, let updatedColumnNames): + case let .update(tableName, updatedColumnNames): return DatabaseRegion(table: tableName, columns: updatedColumnNames) } } @@ -881,9 +896,9 @@ extension DatabaseEventKind { /// The impacted database table public var tableName: String { switch self { - case .insert(tableName: let tableName): return tableName - case .delete(tableName: let tableName): return tableName - case .update(tableName: let tableName, columnNames: _): return tableName + case let .insert(tableName: tableName): return tableName + case let .delete(tableName: tableName): return tableName + case let .update(tableName: tableName, columnNames: _): return tableName } } } @@ -915,7 +930,7 @@ public struct DatabaseEvent { /// The database name public var databaseName: String { return impl.databaseName } - + /// The table name public var tableName: String { return impl.tableName } @@ -941,11 +956,16 @@ public struct DatabaseEvent { } init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { - self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) + self.init( + kind: kind, + rowID: rowID, + impl: MetalDatabaseEventImpl( + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) } } -extension DatabaseEvent : DatabaseEventProtocol { +extension DatabaseEvent: DatabaseEventProtocol { func send(to observer: TransactionObservation) { observer.databaseDidChange(with: self) } @@ -970,19 +990,25 @@ private protocol DatabaseEventImpl { /// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw /// SQLite char* until actually asked for databaseName or tableName. -private struct MetalDatabaseEventImpl : DatabaseEventImpl { +private struct MetalDatabaseEventImpl: DatabaseEventImpl { let databaseNameCString: UnsafePointer? let tableNameCString: UnsafePointer? - + var databaseName: String { return String(cString: databaseNameCString!) } var tableName: String { return String(cString: tableNameCString!) } + func copy(_ event: DatabaseEvent) -> DatabaseEvent { - return DatabaseEvent(kind: event.kind, rowID: event.rowID, impl: CopiedDatabaseEventImpl(databaseName: databaseName, tableName: tableName)) + return DatabaseEvent( + kind: event.kind, + rowID: event.rowID, + impl: CopiedDatabaseEventImpl( + databaseName: databaseName, + tableName: tableName)) } } /// Impl for DatabaseEvent that contains copies of event strings. -private struct CopiedDatabaseEventImpl : DatabaseEventImpl { +private struct CopiedDatabaseEventImpl: DatabaseEventImpl { let databaseName: String let tableName: String func copy(_ event: DatabaseEvent) -> DatabaseEvent { @@ -992,258 +1018,293 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl { #if SQLITE_ENABLE_PREUPDATE_HOOK - public struct DatabasePreUpdateEvent { +public struct DatabasePreUpdateEvent { + + /// An event kind + public enum Kind: Int32 { + /// SQLITE_INSERT + case insert = 18 - /// An event kind - public enum Kind: Int32 { - /// SQLITE_INSERT - case insert = 18 - - /// SQLITE_DELETE - case delete = 9 - - /// SQLITE_UPDATE - case update = 23 - } + /// SQLITE_DELETE + case delete = 9 - /// The event kind - public let kind: Kind - - /// The database name - public var databaseName: String { return impl.databaseName } - - /// The table name - public var tableName: String { return impl.tableName } - - /// The number of columns in the row that is being inserted, updated, or deleted. - public var count: Int { return Int(impl.columnsCount) } - - /// The triggering depth of the row update - /// Returns: - /// 0 if the preupdate callback was invoked as a result of a direct insert, - // update, or delete operation; - /// 1 for inserts, updates, or deletes invoked by top-level triggers; - /// 2 for changes resulting from triggers called by top-level triggers; - /// ... and so forth - public var depth: CInt { return impl.depth } - - /// The initial rowID of the row being changed for .Update and .Delete changes, - /// and nil for .Insert changes. - public let initialRowID: Int64? - - /// The final rowID of the row being changed for .Update and .Insert changes, - /// and nil for .Delete changes. - public let finalRowID: Int64? - - /// The initial database values in the row. - /// - /// Values appear in the same order as the columns in the table. - /// - /// The result is nil if the event is an .Insert event. - public var initialDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .delete) else { return nil } - return impl.initialDatabaseValues - } - - /// Returns the initial `DatabaseValue` at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// The result is nil if the event is an .Insert event. - public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - GRDBPrecondition(index >= 0 && index < count, "row index out of range") - guard (kind == .update || kind == .delete) else { return nil } - return impl.initialDatabaseValue(atIndex: index) - } - - /// The final database values in the row. - /// - /// Values appear in the same order as the columns in the table. - /// - /// The result is nil if the event is a .Delete event. - public var finalDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .insert) else { return nil } - return impl.finalDatabaseValues - } - - /// Returns the final `DatabaseValue` at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// The result is nil if the event is a .Delete event. - public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - GRDBPrecondition(index >= 0 && index < count, "row index out of range") - guard (kind == .update || kind == .insert) else { return nil } - return impl.finalDatabaseValue(atIndex: index) - } - - /// Returns an event that can be stored: - /// - /// class MyObserver: TransactionObserver { - /// var events: [DatabasePreUpdateEvent] - /// func databaseWillChange(with event: DatabasePreUpdateEvent) { - /// events.append(event.copy()) - /// } - /// } - public func copy() -> DatabasePreUpdateEvent { - return impl.copy(self) - } - - fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { - self.kind = kind - self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil - self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil - self.impl = impl - } - - init(connection: SQLiteConnection, kind: Kind, initialRowID: Int64, finalRowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { - self.init(kind: kind, - initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil, - finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil, - impl: MetalDatabasePreUpdateEventImpl(connection: connection, kind: kind, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) - } - - private let impl: DatabasePreUpdateEventImpl + /// SQLITE_UPDATE + case update = 23 } - extension DatabasePreUpdateEvent : DatabaseEventProtocol { - func send(to observer: TransactionObservation) { - observer.databaseWillChange(with: self) - } - - func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool { - switch (kind, databaseEventKind) { - case (.insert, .insert(let tableName)): return self.tableName == tableName - case (.delete, .delete(let tableName)): return self.tableName == tableName - case (.update, .update(let tableName, _)): return self.tableName == tableName - default: - return false - } - } + /// The event kind + public let kind: Kind + + /// The database name + public var databaseName: String { return impl.databaseName } + + /// The table name + public var tableName: String { return impl.tableName } + + /// The number of columns in the row that is being inserted, updated, or deleted. + public var count: Int { return Int(impl.columnsCount) } + + /// The triggering depth of the row update + /// Returns: + /// 0 if the preupdate callback was invoked as a result of a direct insert, + // update, or delete operation; + /// 1 for inserts, updates, or deletes invoked by top-level triggers; + /// 2 for changes resulting from triggers called by top-level triggers; + /// ... and so forth + public var depth: CInt { return impl.depth } + + /// The initial rowID of the row being changed for .Update and .Delete changes, + /// and nil for .Insert changes. + public let initialRowID: Int64? + + /// The final rowID of the row being changed for .Update and .Insert changes, + /// and nil for .Delete changes. + public let finalRowID: Int64? + + /// The initial database values in the row. + /// + /// Values appear in the same order as the columns in the table. + /// + /// The result is nil if the event is an .Insert event. + public var initialDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .delete else { return nil } + return impl.initialDatabaseValues } - /// Protocol for internal implementation of DatabaseEvent - private protocol DatabasePreUpdateEventImpl { - var databaseName: String { get } - var tableName: String { get } - - var columnsCount: CInt { get } - var depth: CInt { get } - var initialDatabaseValues: [DatabaseValue]? { get } - var finalDatabaseValues: [DatabaseValue]? { get } - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent + /// Returns the initial `DatabaseValue` at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// The result is nil if the event is an .Insert event. + public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { + GRDBPrecondition(index >= 0 && index < count, "row index out of range") + guard kind == .update || kind == .delete else { return nil } + return impl.initialDatabaseValue(atIndex: index) } - /// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw - /// SQLite char* until actually asked for databaseName or tableName, - /// nor does it request other data via the sqlite3_preupdate_* APIs - /// until asked. - private struct MetalDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl { - let connection: SQLiteConnection - let kind: DatabasePreUpdateEvent.Kind - - let databaseNameCString: UnsafePointer? - let tableNameCString: UnsafePointer? - - var databaseName: String { return String(cString: databaseNameCString!) } - var tableName: String { return String(cString: tableNameCString!) } - - var columnsCount: CInt { return sqlite3_preupdate_count(connection) } - var depth: CInt { return sqlite3_preupdate_depth(connection) } - var initialDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .delete) else { return nil } - return preupdate_getValues_old(connection) - } - - var finalDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .insert) else { return nil } - return preupdate_getValues_new(connection) - } - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount - precondition(index >= 0 && index < Int(columnCount), "row index out of range") - return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_old(connection, column, &value) - }) - } - - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount - precondition(index >= 0 && index < Int(columnCount), "row index out of range") - return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_new(connection, column, &value) - }) - } - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return DatabasePreUpdateEvent(kind: event.kind, initialRowID: event.initialRowID, finalRowID: event.finalRowID, impl: CopiedDatabasePreUpdateEventImpl( - databaseName: databaseName, - tableName: tableName, - columnsCount: columnsCount, - depth: depth, - initialDatabaseValues: initialDatabaseValues, - finalDatabaseValues: finalDatabaseValues)) - } - - private func preupdate_getValues(_ connection: SQLiteConnection, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> [DatabaseValue]? { - let columnCount = sqlite3_preupdate_count(connection) - guard columnCount > 0 else { return nil } - - var columnValues = [DatabaseValue]() - - for i in 0.. CInt ) -> DatabaseValue? { - var value : SQLiteValue? = nil - guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } - if let value = value { - return DatabaseValue(sqliteValue: value) - } - return nil - } - - private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_old(connection, column, &value) - }) - } - - private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_new(connection, column, &value) - }) - } + /// The final database values in the row. + /// + /// Values appear in the same order as the columns in the table. + /// + /// The result is nil if the event is a .Delete event. + public var finalDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .insert else { return nil } + return impl.finalDatabaseValues } - /// Impl for DatabasePreUpdateEvent that contains copies of all event data. - private struct CopiedDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl { - let databaseName: String - let tableName: String - let columnsCount: CInt - let depth: CInt - let initialDatabaseValues: [DatabaseValue]? - let finalDatabaseValues: [DatabaseValue]? - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return event + /// Returns the final `DatabaseValue` at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// The result is nil if the event is a .Delete event. + public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { + GRDBPrecondition(index >= 0 && index < count, "row index out of range") + guard kind == .update || kind == .insert else { return nil } + return impl.finalDatabaseValue(atIndex: index) + } + + /// Returns an event that can be stored: + /// + /// class MyObserver: TransactionObserver { + /// var events: [DatabasePreUpdateEvent] + /// func databaseWillChange(with event: DatabasePreUpdateEvent) { + /// events.append(event.copy()) + /// } + /// } + public func copy() -> DatabasePreUpdateEvent { + return impl.copy(self) + } + + fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { + self.kind = kind + self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil + self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil + self.impl = impl + } + + init( + connection: SQLiteConnection, + kind: Kind, + initialRowID: Int64, + finalRowID: Int64, + databaseNameCString: UnsafePointer?, + tableNameCString: UnsafePointer?) + { + self.init( + kind: kind, + initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil, + finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil, + impl: MetalDatabasePreUpdateEventImpl( + connection: connection, + kind: kind, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + } + + private let impl: DatabasePreUpdateEventImpl +} + +extension DatabasePreUpdateEvent: DatabaseEventProtocol { + func send(to observer: TransactionObservation) { + observer.databaseWillChange(with: self) + } + + func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool { + switch (kind, databaseEventKind) { + case (.insert, .insert(let tableName)): return self.tableName == tableName + case (.delete, .delete(let tableName)): return self.tableName == tableName + case (.update, .update(let tableName, _)): return self.tableName == tableName + default: + return false } } +} + +/// Protocol for internal implementation of DatabaseEvent +private protocol DatabasePreUpdateEventImpl { + var databaseName: String { get } + var tableName: String { get } + + var columnsCount: CInt { get } + var depth: CInt { get } + var initialDatabaseValues: [DatabaseValue]? { get } + var finalDatabaseValues: [DatabaseValue]? { get } + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent +} + +/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw +/// SQLite char* until actually asked for databaseName or tableName, +/// nor does it request other data via the sqlite3_preupdate_* APIs +/// until asked. +private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { + let connection: SQLiteConnection + let kind: DatabasePreUpdateEvent.Kind + + let databaseNameCString: UnsafePointer? + let tableNameCString: UnsafePointer? + + var databaseName: String { return String(cString: databaseNameCString!) } + var tableName: String { return String(cString: tableNameCString!) } + + var columnsCount: CInt { return sqlite3_preupdate_count(connection) } + var depth: CInt { return sqlite3_preupdate_depth(connection) } + var initialDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .delete else { return nil } + return preupdate_getValues_old(connection) + } + + var finalDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .insert else { return nil } + return preupdate_getValues_new(connection) + } + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { + let columnCount = columnsCount + precondition(index >= 0 && index < Int(columnCount), "row index out of range") + return getValue( + connection, + column: CInt(index), + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_old(connection, column, &value) + }) + } + + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { + let columnCount = columnsCount + precondition(index >= 0 && index < Int(columnCount), "row index out of range") + return getValue( + connection, + column: CInt(index), + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_new(connection, column, &value) + }) + } + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { + return DatabasePreUpdateEvent( + kind: event.kind, + initialRowID: event.initialRowID, + finalRowID: event.finalRowID, + impl: CopiedDatabasePreUpdateEventImpl( + databaseName: databaseName, + tableName: tableName, + columnsCount: columnsCount, + depth: depth, + initialDatabaseValues: initialDatabaseValues, + finalDatabaseValues: finalDatabaseValues)) + } + + private func preupdate_getValues( + _ connection: SQLiteConnection, + sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) + -> [DatabaseValue]? + { + let columnCount = sqlite3_preupdate_count(connection) + guard columnCount > 0 else { return nil } + + var columnValues = [DatabaseValue]() + + for i in 0.. CInt) + -> DatabaseValue? + { + var value: SQLiteValue? = nil + guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } + if let value = value { + return DatabaseValue(sqliteValue: value) + } + return nil + } + + private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { + return preupdate_getValues( + connection, + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_old(connection, column, &value) + }) + } + + private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { + return preupdate_getValues( + connection, + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_new(connection, column, &value) + }) + } +} + +/// Impl for DatabasePreUpdateEvent that contains copies of all event data. +private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { + let databaseName: String + let tableName: String + let columnsCount: CInt + let depth: CInt + let initialDatabaseValues: [DatabaseValue]? + let finalDatabaseValues: [DatabaseValue]? + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { + return event + } +} #endif @@ -1330,4 +1391,3 @@ class SavepointStack { } } } - diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 4bf3abfca..edc39bac3 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -4,7 +4,7 @@ /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } -public struct FTS3 : VirtualTableModule { +public struct FTS3: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// @@ -55,7 +55,10 @@ public struct FTS3 : VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " ")) + arguments.append( + "tokenize=\(tokenizer.name) " + tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } return arguments diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 69c43d0e1..4859285ee 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -24,7 +24,7 @@ public struct FTS3Pattern { } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message) } // Pattern is valid @@ -115,7 +115,7 @@ public struct FTS3Pattern { #endif } -extension FTS3Pattern : DatabaseValueConvertible { +extension FTS3Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 44f667d0f..8f4f6a401 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -48,7 +48,12 @@ public struct FTS3TokenizerDescriptor { /// these characters as token characters. /// /// See https://www.sqlite.org/fts3.html#tokenizer - public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + public static func unicode61( + diacritics: FTS3.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } #else @@ -68,14 +73,25 @@ public struct FTS3TokenizerDescriptor { /// /// 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 { + 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) + // 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, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + private static func _unicode61( + diacritics: FTS3.Diacritics, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { var arguments: [String] = [] switch diacritics { case .removeLegacy: @@ -88,12 +104,16 @@ public struct FTS3TokenizerDescriptor { #endif } if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - arguments.append("separators=" + separators.sorted().map { String($0) }.joined(separator: "")) + // TODO: test "=" and "\"", "(" and ")" as separators, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) + arguments.append("separators=" + separators.sorted().map { String($0) }.joined()) } if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined(separator: "")) + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) + arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined()) } return FTS3TokenizerDescriptor("unicode61", arguments: arguments) } @@ -108,13 +128,14 @@ public struct FTS3TokenizerDescriptor { 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) + // 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) @@ -124,7 +145,9 @@ public struct FTS3TokenizerDescriptor { let tokenizerSQL = tokenizerChunks.joined(separator: ", ") // Assume fts3tokenize virtual table in an in-memory database always succeeds try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))") - return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string]) + return try! String.fetchAll(db, sql: """ + SELECT token FROM tokens WHERE input = ? ORDER BY position + """, arguments: [string]) } } } diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 56dc6e0f8..29cfc4b85 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -6,7 +6,7 @@ /// } /// /// See https://www.sqlite.org/fts3.html -public struct FTS4 : VirtualTableModule { +public struct FTS4: VirtualTableModule { /// Creates a FTS4 module suitable for the Database /// `create(virtualTable:using:)` method. @@ -53,7 +53,10 @@ public struct FTS4 : VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " ")) + arguments.append( + "tokenize=\(tokenizer.name) " + tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } @@ -273,7 +276,8 @@ public final class FTS4ColumnDefinition { @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) + // 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 } @@ -292,7 +296,8 @@ public final class FTS4ColumnDefinition { @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) + // 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 } diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index d7346948f..381d0bb4c 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,10 +1,11 @@ #if SQLITE_ENABLE_FTS5 +import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// FTS5 lets you define "fts5" virtual tables. @@ -15,7 +16,7 @@ /// } /// /// See https://www.sqlite.org/fts5.html -public struct FTS5 : VirtualTableModule { +public struct FTS5: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// @@ -34,7 +35,7 @@ public struct FTS5 : VirtualTableModule { case remove #endif } - + /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// @@ -75,30 +76,41 @@ public struct FTS5 : VirtualTableModule { } if let tokenizer = definition.tokenizer { - arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))") + let tokenizerSQL = tokenizer + .components + .joined(separator: " ") + .sqlExpression + .quotedSQL() + arguments.append("tokenize=\(tokenizerSQL)") } switch definition.contentMode { - case .raw(let content, let contentRowID): + case let .raw(content, contentRowID): if let content = content { - let quotedContent = content.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedContent = content.sqlExpression.quotedSQL() arguments.append("content=\(quotedContent)") } if let contentRowID = contentRowID { - let quotedContentRowID = contentRowID.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedContentRowID = contentRowID.sqlExpression.quotedSQL() arguments.append("content_rowid=\(quotedContentRowID)") } - case .synchronized(let contentTable): - arguments.append("content=\(contentTable.sqlExpression.quotedSQL(wrappedInParenthesis: false))") + case let .synchronized(contentTable): + arguments.append("content=\(contentTable.sqlExpression.quotedSQL())") if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { - let quotedRowID = rowIDColumn.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedRowID = rowIDColumn.sqlExpression.quotedSQL() arguments.append("content_rowid=\(quotedRowID)") } } if let prefixes = definition.prefixes { - arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))") + let prefix = prefixes + .sorted() + .map { "\($0)" } + .joined(separator: " ") + .sqlExpression + .quotedSQL() + arguments.append("prefix=\(prefix)") } if let columnSize = definition.columnSize { @@ -141,14 +153,14 @@ public struct FTS5 : VirtualTableModule { try db.execute(sql: """ CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); END; CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; """) @@ -190,7 +202,7 @@ public struct FTS5 : VirtualTableModule { } #if swift(>=5.0) return data.withUnsafeBytes { - $0.bindMemory(to: UnsafePointer.self).first! + $0.bindMemory(to: UnsafePointer.self).first! } #else return data.withUnsafeBytes { @@ -203,7 +215,9 @@ public struct FTS5 : VirtualTableModule { // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 private static func api_v2( _ db: Database, + // swiftlint:disable:next line_length _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, Int32, UInt32, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Int32, + // swiftlint:disable:next line_length _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32) -> UnsafePointer { diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 9d3a54570..ebfc24d5c 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,14 +1,14 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The protocol for custom FTS5 tokenizers. -public protocol FTS5CustomTokenizer : FTS5Tokenizer { +public protocol FTS5CustomTokenizer: FTS5Tokenizer { /// The name of the tokenizer; should uniquely identify your custom /// tokenizer. static var name: String { get } @@ -41,7 +41,6 @@ extension FTS5CustomTokenizer { public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor { return FTS5TokenizerDescriptor(components: [name] + arguments) } - } extension Database { @@ -52,7 +51,10 @@ extension Database { let db: Database let constructor: (Database, [String], UnsafeMutablePointer?) -> Int32 - init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) { + init( + db: Database, + constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) + { self.db = db self.constructor = constructor } @@ -101,7 +103,13 @@ extension Database { Unmanaged.fromOpaque(constructorPointer).release() } - func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer?) -> Int32 { + func xCreateTokenizer( + constructorPointer: UnsafeMutableRawPointer?, + azArg: UnsafeMutablePointer?>?, + nArg: Int32, + tokenizerHandle: UnsafeMutablePointer?) + -> Int32 + { guard let constructorPointer = constructorPointer else { return SQLITE_ERROR } @@ -122,20 +130,41 @@ extension Database { Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() } - func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) -> Int32 { + func xTokenize( + tokenizerPointer: OpaquePointer?, + context: UnsafeMutableRawPointer?, + flags: Int32, + pText: UnsafePointer?, + nText: Int32, + // swiftlint:disable:next line_length + tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) + -> Int32 + { guard let tokenizerPointer = tokenizerPointer else { return SQLITE_ERROR } - let object = Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue() + let object = Unmanaged + .fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)) + .takeUnretainedValue() guard let tokenizer = object as? FTS5Tokenizer else { return SQLITE_ERROR } - return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!) + return tokenizer.tokenize( + context: context, + tokenization: FTS5Tokenization(rawValue: flags), + pText: pText, + nText: nText, + tokenCallback: tokenCallback!) } var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize) let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in - api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor) + api.pointee.xCreateTokenizer( + UnsafeMutablePointer(mutating: api), + Tokenizer.name, + constructorPointer, + xTokenizerPointer, + deleteConstructor) } guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index c67558f10..72632c932 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -13,7 +13,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingAnyTokenIn string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) } @@ -26,7 +33,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingAllTokensIn string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) } @@ -39,7 +53,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } @@ -52,7 +73,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPrefixPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") } @@ -80,7 +108,7 @@ public struct FTS5Pattern { } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message) } // Pattern is valid @@ -104,7 +132,7 @@ extension Database { } } -extension FTS5Pattern : DatabaseValueConvertible { +extension FTS5Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index d5dd44de2..b5fbea527 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,21 +1,29 @@ #if SQLITE_ENABLE_FTS5 +import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A low-level SQLite function that lets FTS5Tokenizer notify tokens. /// /// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) -public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32 +public typealias FTS5TokenCallback = @convention(c) ( + _ context: UnsafeMutableRawPointer?, + _ flags: Int32, + _ pToken: UnsafePointer?, + _ nToken: Int32, + _ iStart: Int32, + _ iEnd: Int32) + -> Int32 /// The reason why FTS5 is requesting tokenization. /// /// See https://www.sqlite.org/fts5.html#custom_tokenizers -public struct FTS5Tokenization : OptionSet { +public struct FTS5Tokenization: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { @@ -36,7 +44,7 @@ public struct FTS5Tokenization : OptionSet { } /// The protocol for FTS5 tokenizers -public protocol FTS5Tokenizer : class { +public protocol FTS5Tokenizer: AnyObject { /// Tokenizes the text described by `pText` and `nText`, and /// notifies found tokens to the `tokenCallback` function. /// @@ -51,7 +59,13 @@ public protocol FTS5Tokenizer : class { /// - nText: The number of bytes in the tokenized text. /// - tokenCallback: The function to call for each found token. /// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 + func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 } private class TokenizeContext { @@ -81,20 +95,34 @@ extension FTS5Tokenizer { var context = TokenizeContext() try withUnsafeMutablePointer(to: &context) { contextPointer in - let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in - guard let contextPointer = contextPointer else { return SQLITE_ERROR } - - // Extract token - guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { + let code = tokenize( + context: UnsafeMutableRawPointer(contextPointer), + tokenization: tokenization, + pText: pText, + nText: nText, + tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in + guard let contextPointer = contextPointer else { + return SQLITE_ERROR + } + + // Extract token + guard + let token = pToken.flatMap({ + String( + data: Data( + bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), + count: Int(nToken), + deallocator: .none), + encoding: .utf8) }) + else { + return SQLITE_OK + } + + let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee + context.tokens.append((token, FTS5TokenFlags(rawValue: flags))) return SQLITE_OK - } - - let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee - context.tokens.append((token, FTS5TokenFlags(rawValue: flags))) - - return SQLITE_OK }) - if (code != SQLITE_OK) { + if code != SQLITE_OK { throw DatabaseError(resultCode: code) } } @@ -119,13 +147,13 @@ extension Database { /// Private type that makes a pre-registered FTS5 tokenizer available /// through the FTS5Tokenizer protocol. - private final class FTS5RegisteredTokenizer : FTS5Tokenizer { + private final class FTS5RegisteredTokenizer: FTS5Tokenizer { let xTokenizer: fts5_tokenizer let tokenizerPointer: OpaquePointer init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws { guard let xCreate = xTokenizer.xCreate else { - throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate") + throw DatabaseError(message: "nil fts5_tokenizer.xCreate") } self.xTokenizer = xTokenizer @@ -135,7 +163,13 @@ extension Database { if let argument = arguments.first { // Turn [String] into ContiguousArray> // (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/) - func convertArguments(_ array: inout ContiguousArray>, _ car: String, _ cdr: [String], _ body: (ContiguousArray>) -> Result) -> Result { + func convertArguments( + _ array: inout ContiguousArray>, + _ car: String, + _ cdr: [String], + _ body: (ContiguousArray>) -> Result) + -> Result + { return car.withCString { cString in if let car = cdr.first { array.append(cString) @@ -148,7 +182,11 @@ extension Database { var cStrings = ContiguousArray>() code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in cStrings.withUnsafeBufferPointer { azArg in - xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer) + xCreate( + contextPointer, + UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), + Int32(cStrings.count), + &tokenizerPointer) } } } else { @@ -172,7 +210,14 @@ extension Database { } } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 + { guard let xTokenize = xTokenizer.xTokenize else { return SQLITE_ERROR } @@ -216,7 +261,10 @@ extension Database { } let contextPointer = contextHandle.pointee - return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments) + return try FTS5RegisteredTokenizer( + xTokenizer: xTokenizerPointer.pointee, + contextPointer: contextPointer, + arguments: descriptor.arguments) } } #endif diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index dab8ec8a4..7ef83c9ff 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -57,11 +57,20 @@ public struct FTS5TokenizerDescriptor { /// /// See https://www.sqlite.org/fts5.html#ascii_tokenizer public static func ascii(separators: Set = []) -> FTS5TokenizerDescriptor { + let components: [String] if separators.isEmpty { - return FTS5TokenizerDescriptor(components: ["ascii"]) + components = ["ascii"] } else { - return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL(wrappedInParenthesis: false)]) + components = [ + "ascii", + "separators", + separators + .map { String($0) } + .joined() + .sqlExpression + .quotedSQL()] } + return FTS5TokenizerDescriptor(components: components) } /// The "porter" tokenizer @@ -98,7 +107,12 @@ public struct FTS5TokenizerDescriptor { /// consider these characters as token characters. /// /// See https://www.sqlite.org/fts5.html#unicode61_tokenizer - public static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { + public static func unicode61( + diacritics: FTS5.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS5TokenizerDescriptor + { var components: [String] = ["unicode61"] switch diacritics { case .removeLegacy: @@ -111,26 +125,32 @@ public struct FTS5TokenizerDescriptor { #endif } if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + // TODO: test "=" and "\"", "(" and ")" as separators, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) components.append(contentsOf: [ "separators", separators .sorted() .map { String($0) } - .joined(separator: "") + .joined() .sqlExpression - .quotedSQL(wrappedInParenthesis: false)]) + .quotedSQL() + ]) } if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) components.append(contentsOf: [ "tokenchars", tokenCharacters .sorted() .map { String($0) } - .joined(separator: "") + .joined() .sqlExpression - .quotedSQL(wrappedInParenthesis: false)]) + .quotedSQL() + ]) } return FTS5TokenizerDescriptor(components: components) } diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index a217176cb..f3318f8ad 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,16 +1,17 @@ #if SQLITE_ENABLE_FTS5 +import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Flags that tell SQLite how to register a token. /// /// See https://www.sqlite.org/fts5.html#custom_tokenizers -public struct FTS5TokenFlags : OptionSet { +public struct FTS5TokenFlags: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { @@ -24,7 +25,7 @@ public struct FTS5TokenFlags : OptionSet { /// A function that lets FTS5WrapperTokenizer notify tokens. /// /// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:) -public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> () +public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void /// The protocol for custom FTS5 tokenizers that wrap another tokenizer. /// @@ -44,11 +45,17 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token /// wrappedTokenizer = try db.makeTokenizer(.ascii()) /// } /// -/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { +/// func accept( +/// token: String, +/// flags: FTS5TokenFlags, +/// for tokenization: FTS5Tokenization, +/// tokenCallback: FTS5WrapperTokenCallback) +/// throws +/// { /// try tokenCallback(token, flags) /// } /// } -public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { +public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// The wrapped tokenizer var wrappedTokenizer: FTS5Tokenizer { get } @@ -57,7 +64,13 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { /// /// For example: /// - /// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { + /// func accept( + /// token: String, + /// flags: FTS5TokenFlags, + /// for tokenization: FTS5Tokenization, + /// tokenCallback: FTS5WrapperTokenCallback) + /// throws + /// { /// // pass through: /// try tokenCallback(token, flags) /// } @@ -77,7 +90,12 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { /// - flags: Flags that tell SQLite how to register a token. /// - tokenization: The reason why FTS5 is requesting tokenization. /// - tokenCallback: The function to call for each customized token. - func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws + func accept( + token: String, + flags: FTS5TokenFlags, + for tokenization: FTS5Tokenization, + tokenCallback: FTS5WrapperTokenCallback) + throws } private struct FTS5WrapperContext { @@ -89,7 +107,14 @@ private struct FTS5WrapperContext { extension FTS5WrapperTokenizer { /// Default implementation - public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + public func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 + { // `tokenCallback` is @convention(c). This requires a little setup // in order to transfer context. var customContext = FTS5WrapperContext( @@ -99,49 +124,62 @@ extension FTS5WrapperTokenizer { tokenCallback: tokenCallback) return withUnsafeMutablePointer(to: &customContext) { customContextPointer in // Invoke wrappedTokenizer - return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in - - // Extract token produced by wrapped tokenizer - guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { - return 0 // SQLITE_OK - } - - // Extract context - let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee - let tokenizer = customContext.tokenizer - let context = customContext.context - let tokenization = customContext.tokenization - let tokenCallback = customContext.tokenCallback - - // Process token produced by wrapped tokenizer - do { - try tokenizer.accept( - token: token, - flags: FTS5TokenFlags(rawValue: tokenFlags), - for: tokenization, - tokenCallback: { (token, flags) in - // Turn token into bytes - return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in - guard let addr = buffer.baseAddress else { - return - } - let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) - let nToken = Int32(buffer.count) - - // Inject token bytes into SQLite - let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: "token callback failed") - } - } - }) + return wrappedTokenizer.tokenize( + context: customContextPointer, + tokenization: tokenization, + pText: pText, + nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in - return SQLITE_OK - } catch let error as DatabaseError { - return error.extendedResultCode.rawValue - } catch { - return SQLITE_ERROR - } + // Extract token produced by wrapped tokenizer + guard + let token = pToken.flatMap({ + String( + data: Data( + bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), + count: Int(nToken), + deallocator: .none), + encoding: .utf8) }) + else { + return SQLITE_OK // 0 // SQLITE_OK + } + + // Extract context + let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee + let tokenizer = customContext.tokenizer + let context = customContext.context + let tokenization = customContext.tokenization + let tokenCallback = customContext.tokenCallback + + // Process token produced by wrapped tokenizer + do { + try tokenizer.accept( + token: token, + flags: FTS5TokenFlags(rawValue: tokenFlags), + for: tokenization, + tokenCallback: { (token, flags) in + // Turn token into bytes + return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in + guard let addr = buffer.baseAddress else { + return + } + let pToken = UnsafeMutableRawPointer(mutating: addr) + .assumingMemoryBound(to: Int8.self) + let nToken = Int32(buffer.count) + + // Inject token bytes into SQLite + let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: "token callback failed") + } + } + }) + + return SQLITE_OK + } catch let error as DatabaseError { + return error.extendedResultCode.rawValue + } catch { + return SQLITE_ERROR + } } } } diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift index f468c0604..1c6c41220 100644 --- a/GRDB/Fixit/GRDB-4.0.swift +++ b/GRDB/Fixit/GRDB-4.0.swift @@ -4,7 +4,10 @@ import Dispatch extension Cursor { @available(*, unavailable, renamed: "compactMap") - public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { preconditionFailure() } + public func flatMap( + _ transform: @escaping (Element) throws -> ElementOfResult?) + -> MapCursor>, ElementOfResult> + { preconditionFailure() } } extension DatabaseWriter { @@ -14,17 +17,26 @@ extension DatabaseWriter { extension ValueObservation { @available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure") - public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation { preconditionFailure() } + 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() } + 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 +public typealias ColumnCursor = FastDatabaseValueCursor + where Value: DatabaseValueConvertible & StatementColumnConvertible @available(*, unavailable, renamed: "FastNullableDatabaseValueCursor") -public typealias NullableColumnCursor = FastNullableDatabaseValueCursor +public typealias NullableColumnCursor = FastNullableDatabaseValueCursor + where Value: DatabaseValueConvertible & StatementColumnConvertible extension Database { @available(*, unavailable, renamed: "execute(sql:arguments:)") @@ -45,58 +57,141 @@ extension Database { 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + 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() } + public init( + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil, + cached: Bool = false) + { preconditionFailure() } } extension SQLExpressionLiteral { @@ -111,30 +206,49 @@ extension SQLExpression { extension FTS3TokenizerDescriptor { @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61(removeDiacritics: Bool, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { preconditionFailure() } + 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() } + 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() } + 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() } + 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() } + 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() } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b8d18d176..70520ce1b 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -68,7 +68,7 @@ public struct DatabaseMigrator { /// for some downloaded data. public var eraseDatabaseOnSchemaChange = false private var migrations: [Migration] = [] - + /// A new migrator. public init() { } @@ -92,58 +92,64 @@ public struct DatabaseMigrator { } #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter - /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text).notNull() - /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") - /// } - /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - /// - /// :nodoc: - public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } + /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter + /// + /// // Add a NOT NULL constraint on players.name: + /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") + /// } + /// + /// While your migration code runs with disabled foreign key checks, those + /// are re-enabled and checked at the end of the migration, regardless of + /// eventual errors. + /// + /// - parameters: + /// - identifier: The migration identifier. + /// - block: The migration block that performs SQL statements. + /// - precondition: No migration with the same same as already been registered. + /// + /// :nodoc: + public mutating func registerMigrationWithDeferredForeignKeyCheck( + _ identifier: String, + migrate: @escaping (Database) throws -> Void) + { + registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) + } #else - @available(OSX 10.10, *) - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter - /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text).notNull() - /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") - /// } - /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } + @available(OSX 10.10, *) + /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter + /// + /// // Add a NOT NULL constraint on players.name: + /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") + /// } + /// + /// While your migration code runs with disabled foreign key checks, those + /// are re-enabled and checked at the end of the migration, regardless of + /// eventual errors. + /// + /// - parameters: + /// - identifier: The migration identifier. + /// - block: The migration block that performs SQL statements. + /// - precondition: No migration with the same same as already been registered. + public mutating func registerMigrationWithDeferredForeignKeyCheck( + _ identifier: String, + migrate: @escaping (Database) throws -> Void) + { + registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) + } #endif /// Iterate migrations in the same order as they were registered. If a @@ -232,7 +238,9 @@ public struct DatabaseMigrator { // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { - GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))") + GRDBPrecondition( + !migrations.map({ $0.identifier }).contains(migration.identifier), + "already registered migration: \(String(reflecting: migration.identifier))") migrations.append(migration) } @@ -254,13 +262,17 @@ public struct DatabaseMigrator { } // targetIdentifier must refer to a registered migration - GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") + GRDBPrecondition( + prefixMigrations.last?.identifier == targetIdentifier, + "undefined migration: \(String(reflecting: targetIdentifier))") // Subsequent migration must not be applied let appliedIdentifiers = try self.appliedIdentifiers(db) if prefixMigrations.count < migrations.count { let nextIdentifier = migrations[prefixMigrations.count].identifier - GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") + GRDBPrecondition( + !appliedIdentifiers.contains(nextIdentifier), + "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 17d60de28..098667d76 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -5,26 +5,27 @@ struct Migration { let migrate: (Database) throws -> Void #if GRDBCUSTOMSQLITE || GRDBCIPHER - init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } + init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { + self.identifier = identifier + self.disabledForeignKeyChecks = disabledForeignKeyChecks + self.migrate = migrate + } #else - init(identifier: String, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = false - self.migrate = migrate - } + init(identifier: String, migrate: @escaping (Database) throws -> Void) { + self.identifier = identifier + self.disabledForeignKeyChecks = false + self.migrate = migrate + } - @available(OSX 10.10, *) - // PRAGMA foreign_key_check was introduced 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) - init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } + @available(OSX 10.10, *) + // PRAGMA foreign_key_check was introduced 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) + init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { + self.identifier = identifier + self.disabledForeignKeyChecks = disabledForeignKeyChecks + self.migrate = migrate + } #endif func run(_ db: Database) throws { @@ -75,6 +76,7 @@ struct Migration { return .commit } + // TODO: we should restore foreign_keys in case of error as well // > 12. If foreign keys constraints were originally enabled, reenable them now. try db.execute(sql: "PRAGMA foreign_keys = ON") } diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 7bdfaade4..9faee9094 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -1,4 +1,4 @@ -extension QueryInterfaceRequest { +extension TableRequest where Self: FilteredRequest { // MARK: Full Text Search @@ -11,7 +11,7 @@ extension QueryInterfaceRequest { /// /// If the search pattern is nil, the request does not match any /// database row. - public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { + public func matching(_ pattern: FTS3Pattern?) -> Self { guard let pattern = pattern else { return none() } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index ab3bb55e0..e8d74aa79 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -1,44 +1,44 @@ #if SQLITE_ENABLE_FTS5 - extension QueryInterfaceRequest { - - // MARK: Full Text Search - - /// Creates a request with a full-text predicate added to the eventual - /// set of already applied predicates. - /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.all() - /// request = request.matching(pattern) - /// - /// If the search pattern is nil, the request does not match any - /// database row. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - guard let pattern = pattern else { - return none() - } - let alias = TableAlias() - let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return self.aliased(alias).filter(matchExpression) - } - } +extension TableRequest where Self: FilteredRequest { - extension TableRecord { - - // MARK: Full Text Search - - /// Returns a QueryInterfaceRequest with a matching predicate. - /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.matching(pattern) - /// - /// If the search pattern is nil, the request does not match any - /// database row. - public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - return all().matching(pattern) + // MARK: Full Text Search + + /// Creates a request with a full-text predicate added to the eventual + /// set of already applied predicates. + /// + /// // SELECT * FROM book WHERE book MATCH '...' + /// var request = Book.all() + /// request = request.matching(pattern) + /// + /// If the search pattern is nil, the request does not match any + /// database row. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. + public func matching(_ pattern: FTS5Pattern?) -> Self { + guard let pattern = pattern else { + return none() } + let alias = TableAlias() + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return self.aliased(alias).filter(matchExpression) } +} + +extension TableRecord { + + // MARK: Full Text Search + + /// Returns a QueryInterfaceRequest with a matching predicate. + /// + /// // SELECT * FROM book WHERE book MATCH '...' + /// var request = Book.matching(pattern) + /// + /// If the search pattern is nil, the request does not match any + /// database row. + public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { + return all().matching(pattern) + } +} #endif diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 27cc272fd..b4ae535b2 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -18,7 +18,7 @@ public protocol Association: DerivableRequest { /// // BelongsToAssociation /// static let author = belongsTo(Author.self) /// } - associatedtype OriginRowDecoder + associatedtype OriginRowDecoder: TableRecord /// :nodoc: var sqlAssociation: SQLAssociation { get } @@ -72,12 +72,12 @@ extension Association { extension Association { private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) + return .init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) } } extension Association { - + /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -290,8 +290,8 @@ extension Association { } } -// Allow association.filter(key: ...) -extension Association where Self: TableRequest, RowDecoder: TableRecord { +// TableRequest +extension Association { /// :nodoc: public var databaseTableName: String { return RowDecoder.databaseTableName } } @@ -306,7 +306,7 @@ public protocol AssociationToOne: Association { } extension AssociationToOne { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedSingular(key) - return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } @@ -320,11 +320,11 @@ public protocol AssociationToMany: Association { } extension AssociationToMany { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedPlural(key) - return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } -extension AssociationToMany where OriginRowDecoder: TableRecord { +extension AssociationToMany { private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { return AssociationAggregate { request in let tableAlias = TableAlias() @@ -353,7 +353,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { return makeAggregate(SQLExpressionCountDistinct(Column.rowID)) - .aliased("\(key.singularizedName)Count") + .forKey("\(key.singularizedName)Count") } /// Creates an aggregate that is true if there exists no associated records. @@ -373,7 +373,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) - .aliased("hasNo\(key.singularizedName.uppercasingFirstCharacter)") + .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } /// Creates an aggregate which evaluate to the average value of the given @@ -397,7 +397,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -424,7 +424,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -451,7 +451,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -478,7 +478,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("\(name)\(column.name.uppercasingFirstCharacter)Sum") + return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") } else { return aggregate } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index cf67dd5bb..37990fa3b 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,5 +1,9 @@ import Foundation +typealias AssociationAggregatePreparation = + (QueryInterfaceRequest) + -> (request: QueryInterfaceRequest, expression: SQLExpression) + /// An AssociationAggregate is able to compute aggregated values from a /// population of associated records. /// @@ -56,12 +60,12 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated value will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - let prepare: (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) + let prepare: AssociationAggregatePreparation - /// The SQL alias for the value of this aggregate. See aliased(_:). - var alias: String? + /// The SQL name for the value of this aggregate. See forKey(_:). + var key: String? - init(_ prepare: @escaping (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression)) { + init(_ prepare: @escaping AssociationAggregatePreparation) { self.prepare = prepare } } @@ -71,14 +75,28 @@ extension AssociationAggregate { /// /// For example: /// - /// let aggregate = Author.books.count.aliased("foo") + /// let aggregate = Author.books.count.aliased("numberOfBooks") /// let request = Author.annotated(with: aggregate) /// if let row = try Row.fetchOne(db, request) { - /// let bookCount: Int = row["foo"] + /// 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: + /// + /// let aggregate = Author.books.count.forKey("numberOfBooks") + /// let request = Author.annotated(with: aggregate) + /// if let row = try Row.fetchOne(db, request) { + /// let numberOfBooks: Int = row["numberOfBooks"] + /// } + public func forKey(_ key: String) -> AssociationAggregate { var aggregate = self - aggregate.alias = name + aggregate.key = key return aggregate } @@ -89,16 +107,36 @@ extension AssociationAggregate { /// /// struct AuthorInfo: Decodable, FetchableRecord { /// var author: Author - /// var bookCount: Int + /// var numberOfBooks: Int /// /// static func fetchAll(_ db: Database) throws -> [AuthorInfo] { - /// let aggregate = Author.books.count.aliased(CodingKeys.bookCount) + /// 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 aliased(key.stringValue) + return forKey(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.forKey(CodingKeys.numberOfBooks) + /// let request = Author.annotated(with: aggregate) + /// return try AuthorInfo.fetchAll(db, request) + /// } + /// } + public func forKey(_ key: CodingKey) -> AssociationAggregate { + return forKey(key.stringValue) } } @@ -121,7 +159,11 @@ public prefix func ! (aggregate: AssociationAggregate) - /// For example: /// /// Author.having(Author.books.isEmpty && Author.paintings.isEmpty) -public func && (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func && ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -131,7 +173,11 @@ public func && (lhs: AssociationAggregate, rhs: Associat // TODO: test /// :nodoc: -public func && (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func && ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression && rhs) @@ -140,7 +186,11 @@ public func && (lhs: AssociationAggregate, rhs: SQLExpre // TODO: test /// :nodoc: -public func && (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func && ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs && expression) @@ -153,7 +203,11 @@ public func && (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func || ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -163,7 +217,11 @@ public func || (lhs: AssociationAggregate, rhs: Associat // TODO: test /// :nodoc: -public func || (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func || ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression || rhs) @@ -172,7 +230,11 @@ public func || (lhs: AssociationAggregate, rhs: SQLExpre // TODO: test /// :nodoc: -public func || (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func || ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs || expression) @@ -186,7 +248,11 @@ public func || (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func == ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -199,7 +265,11 @@ public func == (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count == 3) -public func == (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func == ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression == rhs) @@ -211,7 +281,11 @@ public func == (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 == Author.books.count) -public func == (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func == ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs == expression) @@ -247,7 +321,11 @@ public func == (lhs: Bool, rhs: AssociationAggregate) -> /// For example: /// /// Author.having(Author.books.count != Author.paintings.count) -public func != (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func != ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -260,7 +338,11 @@ public func != (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count != 3) -public func != (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func != ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression != rhs) @@ -272,7 +354,11 @@ public func != (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 != Author.books.count) -public func != (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func != ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs != expression) @@ -308,7 +394,11 @@ public func != (lhs: Bool, rhs: AssociationAggregate) -> /// For example: /// /// Author.having(Author.books.count === Author.paintings.count) -public func === (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func === ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -321,7 +411,11 @@ public func === (lhs: AssociationAggregate, rhs: Associa /// For example: /// /// Author.having(Author.books.count === 3) -public func === (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func === ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression === rhs) @@ -333,7 +427,11 @@ public func === (lhs: AssociationAggregate, rhs: SQLExpr /// For example: /// /// Author.having(3 === Author.books.count) -public func === (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func === ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs === expression) @@ -345,7 +443,11 @@ public func === (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func !== ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -358,7 +460,11 @@ public func !== (lhs: AssociationAggregate, rhs: Associa /// For example: /// /// Author.having(Author.books.count !== 3) -public func !== (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func !== ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression !== rhs) @@ -370,7 +476,11 @@ public func !== (lhs: AssociationAggregate, rhs: SQLExpr /// For example: /// /// Author.having(3 !== Author.books.count) -public func !== (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func !== ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs !== expression) @@ -384,7 +494,11 @@ public func !== (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func <= ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -397,7 +511,11 @@ public func <= (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count <= 3) -public func <= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func <= ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression <= rhs) @@ -409,7 +527,11 @@ public func <= (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 <= Author.books.count) -public func <= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func <= ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs <= expression) @@ -421,7 +543,11 @@ public func <= (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func < ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -434,7 +560,11 @@ public func < (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.having(Author.books.count < 3) -public func < (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func < ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression < rhs) @@ -446,7 +576,11 @@ public func < (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.having(3 < Author.books.count) -public func < (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func < ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs < expression) @@ -458,7 +592,11 @@ public func < (lhs: SQLExpressible, rhs: AssociationAggregate Author.paintings.count) -public func > (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func > ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -471,7 +609,11 @@ public func > (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.having(Author.books.count > 3) -public func > (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func > ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression > rhs) @@ -483,7 +625,11 @@ public func > (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.having(3 > Author.books.count) -public func > (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func > ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs > expression) @@ -495,7 +641,11 @@ public func > (lhs: SQLExpressible, rhs: AssociationAggregate= Author.paintings.count) -public func >= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func >= ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -508,7 +658,11 @@ public func >= (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count >= 3) -public func >= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func >= ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression >= rhs) @@ -520,7 +674,11 @@ public func >= (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 >= Author.books.count) -public func >= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func >= ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs >= expression) @@ -546,7 +704,11 @@ public prefix func - (aggregate: AssociationAggregate) - /// For example: /// /// Author.annotated(with: Author.books.count + Author.paintings.count) -public func + (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func + ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -559,7 +721,11 @@ public func + (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count + 1) -public func + (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func + ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression + rhs) @@ -571,7 +737,11 @@ public func + (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 1 + Author.books.count) -public func + (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func + ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs + expression) @@ -583,7 +753,11 @@ public func + (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func - ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -596,7 +770,11 @@ public func - (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count - 1) -public func - (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func - ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression - rhs) @@ -608,7 +786,11 @@ public func - (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 1 - Author.books.count) -public func - (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func - ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs - expression) @@ -620,7 +802,11 @@ public func - (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func * ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -633,7 +819,11 @@ public func * (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count * 2) -public func * (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func * ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression * rhs) @@ -645,7 +835,11 @@ public func * (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 2 * Author.books.count) -public func * (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func * ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs * expression) @@ -657,7 +851,11 @@ public func * (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func / ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -670,7 +868,11 @@ public func / (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count / 2) -public func / (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func / ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression / rhs) @@ -682,7 +884,11 @@ public func / (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 2 / Author.books.count) -public func / (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func / ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs / expression) @@ -694,14 +900,18 @@ public func / (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func ?? ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ var aggregate = AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression ?? rhs) } - // Preserve alias - aggregate.alias = lhs.alias + // Preserve key + aggregate.key = lhs.key return aggregate } diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 1f459622f..1643ba69e 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -58,7 +58,7 @@ /// } /// /// See ForeignKey for more information. -public struct BelongsToAssociation: AssociationToOne { +public struct BelongsToAssociation: AssociationToOne { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -73,6 +73,3 @@ public struct BelongsToAssociation: AssociationToOne { self.sqlAssociation = sqlAssociation } } - -// Allow BelongsToAssociation(...).filter(key: ...) -extension BelongsToAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index d02586fde..fb263da89 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -58,7 +58,7 @@ /// } /// /// See ForeignKey for more information. -public struct HasManyAssociation: AssociationToMany { +public struct HasManyAssociation: AssociationToMany { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -73,6 +73,3 @@ public struct HasManyAssociation: AssociationToMany { self.sqlAssociation = sqlAssociation } } - -// Allow HasManyAssociation(...).filter(key: ...) -extension HasManyAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index e4e5cb3cc..8b1aec3f5 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -41,7 +41,7 @@ /// two other associations: the `through:` and `using:` arguments. Those /// associations can be any other association (BelongsTo, HasMany, /// HasManyThrough, etc). -public struct HasManyThroughAssociation: AssociationToMany { +public struct HasManyThroughAssociation: AssociationToMany { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -56,6 +56,3 @@ public struct HasManyThroughAssociation: AssociationToMany self.sqlAssociation = sqlAssociation } } - -// Allow HasManyThroughAssociation(...).filter(key: ...) -extension HasManyThroughAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 6b1f49f7c..c0ad1e021 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -60,7 +60,7 @@ /// } /// /// See ForeignKey for more information. -public struct HasOneAssociation: AssociationToOne { +public struct HasOneAssociation: AssociationToOne { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -75,6 +75,3 @@ public struct HasOneAssociation: AssociationToOne { self.sqlAssociation = sqlAssociation } } - -// Allow HasOneAssociation(...).filter(key: ...) -extension HasOneAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index be25e3173..ccc8d5011 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -21,7 +21,7 @@ /// two other associations: the `through:` and `using:` arguments. Those /// associations can be any other association to one (BelongsTo, HasOne, /// HasOneThrough). -public struct HasOneThroughAssociation: AssociationToOne { +public struct HasOneThroughAssociation: AssociationToOne { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -36,6 +36,3 @@ public struct HasOneThroughAssociation: AssociationToOne { self.sqlAssociation = sqlAssociation } } - -// Allow HasOneThroughAssociation(...).filter(key: ...) -extension HasOneThroughAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index ccc080857..403376c33 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -4,8 +4,8 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = aggregate.prepare(self) - if let alias = aggregate.alias { - return request.annotated(with: [expression.aliased(alias)]) + if let key = aggregate.key { + return request.annotated(with: [expression.forKey(key)]) } else { return request.annotated(with: [expression]) } @@ -20,7 +20,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { return annotated(with: aggregates) } - + /// Creates a request which appends *aggregates* to the current selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index fcf8db63d..d9b715ce8 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -28,7 +28,7 @@ /// } /// /// See https://github.com/groue/GRDB.swift#the-query-interface -public struct QueryInterfaceRequest: DerivableRequest { +public struct QueryInterfaceRequest { var query: SQLQuery init(query: SQLQuery) { @@ -86,7 +86,7 @@ extension QueryInterfaceRequest: FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - var region = try SQLQueryGenerator(query).databaseRegion(db) + var region = try SQLQueryGenerator(query).makeSelectStatement(db).databaseRegion // Iterate all prefetched associations var fifo = query.relation.prefetchedAssociations @@ -101,11 +101,11 @@ extension QueryInterfaceRequest: FetchRequest { let prefetchedRelation = association .mapPivotRelation { $0.qualified(with: pivotAlias) } .destinationRelation(fromOriginRows: { _ in [] /* no origin row */ }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) let prefetchedQuery = SQLQuery(relation: prefetchedRelation) // Union region - try region.formUnion(SQLQueryGenerator(prefetchedQuery).databaseRegion(db)) + try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).databaseRegion) // Append nested prefetched associations (support for // A.including(all: A.bs.including(all: B.cs)) @@ -143,7 +143,9 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self) } @@ -155,7 +157,9 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(selection, as: type) } @@ -167,7 +171,12 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(sql: "max(score)", as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -198,7 +207,11 @@ extension QueryInterfaceRequest: SelectionRequest { /// as: String.self) /// let name: String? = try request.fetchOne(db) /// } - public func select(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select( + literal sqlLiteral: SQLLiteral, + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(SQLSelectionLiteral(literal: sqlLiteral), as: type) } @@ -225,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest { extension QueryInterfaceRequest: FilteredRequest { // MARK: Request Derivation - + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// @@ -235,7 +248,6 @@ extension QueryInterfaceRequest: FilteredRequest { public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { return mapQuery { $0.filter(predicate) } } - } extension QueryInterfaceRequest: OrderedRequest { @@ -298,7 +310,7 @@ extension QueryInterfaceRequest: AggregatingRequest { } } -extension QueryInterfaceRequest: JoinableRequest { +extension QueryInterfaceRequest: _JoinableRequest { /// :nodoc: public func _including(all association: SQLAssociation) -> QueryInterfaceRequest { return mapQuery { $0._including(all: association) } @@ -325,10 +337,12 @@ extension QueryInterfaceRequest: JoinableRequest { } } +extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { } + extension QueryInterfaceRequest { // MARK: Request Derivation - + /// Creates a request which returns distinct rows. /// /// // SELECT DISTINCT * FROM player @@ -460,6 +474,8 @@ extension QueryInterfaceRequest: TableRequest { } } +extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { } + extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: Deleting @@ -479,7 +495,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: - Eager loading of hasMany associations /// Append rows from prefetched associations into the argument rows. -fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { +private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { guard let firstRow = rows.first else { // No rows -> no prefetch return @@ -517,7 +533,7 @@ fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in row let prefetchedRelation = association .mapPivotRelation { $0.qualified(with: pivotAlias) } .destinationRelation(fromOriginRows: { _ in rows }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation) .fetchAll(db) .grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index c8c467d4f..9c6a8cbf1 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -176,7 +176,7 @@ extension FilteredRequest { // NOT TESTED return filter(SQLExpressionLiteral(literal: sqlLiteral)) } - + /// Creates a request that matches nothing. /// /// // SELECT * FROM player WHERE 0 @@ -230,7 +230,10 @@ extension TableRequest where Self: FilteredRequest { } /// Creates a request with the provided primary key *predicate*. - public func filter(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible { + public func filter(keys: Sequence) + -> Self + where Sequence.Element: DatabaseValueConvertible + { var request = self let keys = Array(keys) switch keys.count { @@ -241,7 +244,7 @@ extension TableRequest where Self: FilteredRequest { default: break } - + let databaseTableName = self.databaseTableName return request.filter { db in let primaryKey = try db.primaryKey(databaseTableName) @@ -286,7 +289,10 @@ extension TableRequest where Self: FilteredRequest { // ("foo", "bar") is not a unique key (primary key or columns of a // unique index) guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { - fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + fatalError(""" + table \(databaseTableName) has no unique index on column(s) \ + \(key.keys.sorted().joined(separator: ", ")) + """) } let lowercaseColumns = columns.map { $0.lowercased() } @@ -365,13 +371,13 @@ extension AggregatingRequest { // NOT TESTED return group(SQLExpressionLiteral(literal: sqlLiteral)) } - + /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { return having(literal: SQLLiteral(sql: sql, arguments: arguments)) } - + /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(literal sqlLiteral: SQLLiteral) -> Self { @@ -494,6 +500,8 @@ extension OrderedRequest { } } +// MARK: - JoinableRequest + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Type-unsafe support for the JoinableRequest protocol. @@ -542,7 +550,7 @@ public protocol JoinableRequest: _JoinableRequest { /// // BelongsToAssociation /// static let author = belongsTo(Author.self) /// } - associatedtype RowDecoder + associatedtype RowDecoder: TableRecord } extension JoinableRequest { @@ -587,4 +595,4 @@ extension JoinableRequest { /// The base protocol for all requests that can be refined. /// /// :nodoc: -public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest, JoinableRequest { } +public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 29582b5f2..f80d4de53 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -51,7 +51,7 @@ public struct SQLCollatedExpression { } /// :nodoc: -extension SQLCollatedExpression : SQLOrderingTerm { +extension SQLCollatedExpression: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index a070b8e9c..2ebcd6045 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -37,15 +37,17 @@ extension SQLCollection { /// SQLExpressionsArray wraps an array of expressions /// /// SQLExpressionsArray([1, 2, 3]) -struct SQLExpressionsArray : SQLCollection { +struct SQLExpressionsArray: SQLCollection { let expressions: [SQLExpression] - init(_ expressions: S) where S.Iterator.Element : SQLExpressible { + init(_ expressions: S) where S.Iterator.Element: SQLExpressible { self.expressions = expressions.map { $0.sqlExpression } } func collectionSQL(_ context: inout SQLGenerationContext) -> String { - return (expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", ") + return expressions + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") } func contains(_ value: SQLExpressible) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift index 366864aee..a0bb76240 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressible.swift @@ -31,7 +31,7 @@ public protocol SQLExpressible { /// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible). /// /// :nodoc: -public protocol SQLSpecificExpressible : SQLExpressible { +public protocol SQLSpecificExpressible: SQLExpressible { // SQLExpressible can be adopted by Swift standard types, and user // types, through the DatabaseValueConvertible protocol which inherits // from SQLExpressible. diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index b94bd973a..814dabf46 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -14,10 +14,10 @@ extension SQLExpression { /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// - /// "foo'bar".databaseValue.quotedSQL(wrappedInParenthesis: true) // "'foo''bar'"" - func quotedSQL(wrappedInParenthesis: Bool) -> String { + /// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'"" + func quotedSQL() -> String { var context = SQLGenerationContext.literalGenerationContext(withArguments: false) - return expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) + return expressionSQL(&context, wrappedInParenthesis: false) } } @@ -33,7 +33,7 @@ extension SQLExpression { /// /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) -public struct SQLExpressionLiteral : SQLExpression { +public struct SQLExpressionLiteral: SQLExpression { private let sqlLiteral: SQLLiteral public var sql: String { return sqlLiteral.sql } public var arguments: StatementArguments { return sqlLiteral.arguments } @@ -93,7 +93,7 @@ public struct SQLExpressionLiteral : SQLExpression { /// SQLUnaryOperator is a SQLite unary operator. /// /// :nodoc: -public struct SQLUnaryOperator : Hashable { +public struct SQLUnaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL operator @@ -121,7 +121,7 @@ public struct SQLUnaryOperator : Hashable { /// an operand expression. /// /// :nodoc: -public struct SQLExpressionUnary : SQLExpression { +public struct SQLExpressionUnary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The unary operator @@ -167,7 +167,7 @@ public struct SQLExpressionUnary : SQLExpression { /// SQLBinaryOperator is a SQLite binary operator. /// /// :nodoc: -public struct SQLBinaryOperator : Hashable { +public struct SQLBinaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL operator @@ -211,7 +211,7 @@ public struct SQLBinaryOperator : Hashable { /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) /// /// :nodoc: -public struct SQLExpressionBinary : SQLExpression { +public struct SQLExpressionBinary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The left operand @@ -252,17 +252,17 @@ public struct SQLExpressionBinary : SQLExpression { \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) """ } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var negated: SQLExpression { if let negatedOp = op.negated { - return SQLExpressionBinary(negatedOp, lhs, rhs) + return SQLExpressionBinary(negatedOp, lhs, rhs) } else { return SQLExpressionNot(self) } } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -272,7 +272,7 @@ public struct SQLExpressionBinary : SQLExpression { // MARK: - SQLExpressionAnd -struct SQLExpressionAnd : SQLExpression { +struct SQLExpressionAnd: SQLExpression { let expressions: [SQLExpression] init(_ expressions: [SQLExpression]) { @@ -312,7 +312,7 @@ struct SQLExpressionAnd : SQLExpression { // MARK: - SQLExpressionOr -struct SQLExpressionOr : SQLExpression { +struct SQLExpressionOr: SQLExpression { let expressions: [SQLExpression] init(_ expressions: [SQLExpression]) { @@ -422,9 +422,9 @@ struct SQLExpressionEqual: SQLExpression { } } switch (lhs, rhs) { - case (let column as ColumnExpression, let dbValue as DatabaseValue): + case let (column as ColumnExpression, dbValue as DatabaseValue): return matchedRowIds(column: column, dbValue: dbValue) - case (let dbValue as DatabaseValue, let column as ColumnExpression): + case let (dbValue as DatabaseValue, column as ColumnExpression): return matchedRowIds(column: column, dbValue: dbValue) default: return nil @@ -443,7 +443,7 @@ struct SQLExpressionEqual: SQLExpression { /// /// // id IN (1,2,3) /// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3])) -struct SQLExpressionContains : SQLExpression { +struct SQLExpressionContains: SQLExpression { let expression: SQLExpression let collection: SQLCollection let isNegated: Bool @@ -509,7 +509,7 @@ struct SQLExpressionContains : SQLExpression { /// /// // id BETWEEN 1 AND 3 /// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) -struct SQLExpressionBetween : SQLExpression { +struct SQLExpressionBetween: SQLExpression { let expression: SQLExpression let lowerBound: SQLExpression let upperBound: SQLExpression @@ -534,7 +534,7 @@ struct SQLExpressionBetween : SQLExpression { \(upperBound.expressionSQL(&context, wrappedInParenthesis: true)) """ } - + var negated: SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } @@ -553,7 +553,7 @@ struct SQLExpressionBetween : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// SQLFunctionName is an SQL function name. -public struct SQLFunctionName : Hashable { +public struct SQLFunctionName: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL function name @@ -581,7 +581,7 @@ public struct SQLFunctionName : Hashable { /// SQLExpressionFunction(.abs, [-1.databaseValue]) /// /// :nodoc: -public struct SQLExpressionFunction : SQLExpression { +public struct SQLExpressionFunction: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The function name @@ -616,11 +616,13 @@ public struct SQLExpressionFunction : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - return """ - \(functionName.sql)(\ - \((arguments.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", "))\ - ) - """ + var sql = functionName.sql + sql += "(" + sql += arguments + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") + sql += ")" + return sql } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -636,7 +638,7 @@ public struct SQLExpressionFunction : SQLExpression { /// /// // COUNT(name) /// SQLExpressionCount(Column("name")) -struct SQLExpressionCount : SQLExpression { +struct SQLExpressionCount: SQLExpression { /// The counted value let counted: SQLSelectable @@ -659,7 +661,7 @@ struct SQLExpressionCount : SQLExpression { /// /// // COUNT(DISTINCT name) /// SQLExpressionCountDistinct(Column("name")) -struct SQLExpressionCountDistinct : SQLExpression { +struct SQLExpressionCountDistinct: SQLExpression { let counted: SQLExpression init(_ counted: SQLExpression) { @@ -680,7 +682,7 @@ struct SQLExpressionCountDistinct : SQLExpression { /// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting /// the user using the not `!` logical operator, or comparisons with booleans /// such as `== true` or `== false`. -struct SQLExpressionIsEmpty : SQLExpression { +struct SQLExpressionIsEmpty: SQLExpression { var countExpression: SQLExpression var isEmpty: Bool @@ -739,7 +741,7 @@ struct TableMatchExpression: SQLExpression { /// /// // email = 'arthur@example.com' COLLATE NOCASE /// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") -struct SQLExpressionCollate : SQLExpression { +struct SQLExpressionCollate: SQLExpression { let expression: SQLExpression let collationName: Database.CollationName @@ -752,9 +754,8 @@ struct SQLExpressionCollate : SQLExpression { if wrappedInParenthesis { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } - let sql = expression.expressionSQL(&context, wrappedInParenthesis: false) return """ - \(sql) \ + \(expression.expressionSQL(&context, wrappedInParenthesis: false)) \ COLLATE \ \(collationName.rawValue) """ diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b2f5582ec..ac9fed167 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -5,20 +5,8 @@ /// SQLExpression is the protocol for types that represent an SQL expression, as /// described at https://www.sqlite.org/lang_expr.html /// -/// GRDB ships with a variety of types that already adopt this protocol, and -/// allow to represent many SQLite expressions: -/// -/// - Column -/// - DatabaseValue -/// - SQLExpressionLiteral -/// - SQLExpressionUnary -/// - SQLExpressionBinary -/// - SQLExpressionExists -/// - SQLExpressionFunction -/// - SQLExpressionCollate -/// /// :nodoc: -public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { +public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -131,7 +119,7 @@ extension SQLExpression { // MARK: - SQLExpressionNot -struct SQLExpressionNot : SQLExpression { +struct SQLExpressionNot: SQLExpression { let expression: SQLExpression init(_ expression: SQLExpression) { diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 8514256da..18ffe5187 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -67,7 +67,7 @@ struct SQLForeignKeyRequest: Equatable { // No matching foreign key found: use the destination primary key if let originColumns = originColumns { let destinationColumns = try db.primaryKey(destinationTable).columns - if (originColumns.count == destinationColumns.count) { + if originColumns.count == destinationColumns.count { let mapping = zip(originColumns, destinationColumns).map { (origin: $0, destination: $1) } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 8645fc737..06bd1d4a8 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -158,7 +158,7 @@ extension SQLSpecificExpressible { public var capitalized: SQLExpression { return DatabaseFunction.capitalize.apply(sqlExpression) } - + /// Returns an SQL expression that applies the Swift's built-in /// lowercased String property. It is NULL for non-String arguments. /// @@ -168,7 +168,7 @@ extension SQLSpecificExpressible { public var lowercased: SQLExpression { return DatabaseFunction.lowercase.apply(sqlExpression) } - + /// Returns an SQL expression that applies the Swift's built-in /// uppercased String property. It is NULL for non-String arguments. /// diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 8ff7c996f..ac0ee9c87 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -3,14 +3,14 @@ // Outputs "x = y" or "x IS NULL" private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression { switch (lhs, rhs) { - case (let lhs, let rhs as DatabaseValue): + case let (lhs, rhs as DatabaseValue): switch rhs.storage { case .null: return SQLExpressionEqual(.is, lhs, rhs) default: return SQLExpressionEqual(.equal, lhs, rhs) } - case (let lhs as DatabaseValue, let rhs): + case let (lhs as DatabaseValue, rhs): switch lhs.storage { case .null: return SQLExpressionEqual(.is, rhs, lhs) diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index f0ba0a1bf..25be3e43e 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -23,7 +23,7 @@ public protocol SQLOrderingTerm { // MARK: - SQLOrdering -enum SQLOrdering : SQLOrderingTerm { +enum SQLOrdering: SQLOrderingTerm { case asc(SQLExpression) case desc(SQLExpression) diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index ad3e1b2fb..87e3825e5 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -11,7 +11,7 @@ struct SQLQuery { // `(a AND b AND c)` instead of `((a AND b) AND c)`. var havingExpressions: [SQLExpression] var limit: SQLLimit? - + init( relation: SQLRelation, isDistinct: Bool = false, diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index ec5123fa2..ec7f167eb 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -1,4 +1,5 @@ -/// A "relation", as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), +/// A "relation", as defined by the [relational +/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), /// is "a set of tuples sharing the same attributes; a set of columns and rows." /// /// SQLRelation is defined with a selection, a source table of query, and an @@ -200,7 +201,7 @@ extension SQLRelation { relation.selection.append(contentsOf: selection) return relation } - + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { var relation = self relation.filtersPromise = relation.filtersPromise.flatMap { filters in @@ -277,10 +278,10 @@ extension SQLRelation { /// as HasManyThrough, which have any number of pivot relations between the /// origin and the destination. func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation { + // Preserve association cardinality in intermediate steps of + // including(all:), and force desired cardinality otherwize let childCardinality = (kind == .allNotPrefetched) - // preserve association cardinality in intermediate steps of including(all:) ? association.destination.cardinality - // force desired cardinality otherwize : kind.cardinality let childKey = association.destination.key.name(for: childCardinality) let child = SQLRelation.Child( @@ -347,7 +348,10 @@ extension SQLRelation { if let existingChild = relation.children.removeValue(forKey: key) { guard let mergedChild = existingChild.merged(with: child) else { // can't merge - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + fatalError(""" + The association key \"\(key)\" is ambiguous. \ + Use the Association.forKey(_:) method is order to disambiguate. + """) } relation.children.appendValue(mergedChild, forKey: key) } else { @@ -387,7 +391,7 @@ enum SQLSource { func qualified(with alias: TableAlias) -> SQLSource { switch self { - case .table(let tableName, let sourceAlias): + case let .table(tableName, sourceAlias): if let sourceAlias = sourceAlias { alias.becomeProxy(of: sourceAlias) return self @@ -395,7 +399,7 @@ enum SQLSource { alias.setTableName(tableName) return .table(tableName: tableName, alias: alias) } - case .query(let query): + case let .query(query): return .query(query.qualified(with: alias)) } } @@ -774,7 +778,7 @@ extension SQLRelation.Child.Kind { // .including(all: associationToDestinationThroughPivot) // .including(all: associationToPivot) fatalError("Not implemented: merging a direct association and an indirect one with including(all:)") - + case (.allNotPrefetched, .allNotPrefetched): // Equivalent to Record.including(all: association) // diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 08fbe4c48..311e87d16 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -18,7 +18,7 @@ public struct AllColumns { public init() { } } -extension AllColumns : SQLSelectable { +extension AllColumns: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { @@ -69,7 +69,7 @@ struct QualifiedAllColumns { } } -extension QualifiedAllColumns : SQLSelectable { +extension QualifiedAllColumns: SQLSelectable { func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { if let qualifier = context.qualifier(for: alias) { return qualifier.quotedDatabaseIdentifier + ".*" @@ -94,10 +94,10 @@ extension QualifiedAllColumns : SQLSelectable { // // So let's always return `*`, and fix this later. -// if context.qualifier(for: alias) != nil { -// // SELECT COUNT(t.*) is invalid SQL -// fatalError("Not implemented, or invalid query") -// } + // if context.qualifier(for: alias) != nil { + // // SELECT COUNT(t.*) is invalid SQL + // fatalError("Not implemented, or invalid query") + // } return "*" } @@ -118,7 +118,7 @@ extension QualifiedAllColumns : SQLSelectable { // MARK: - SQLAliasedExpression -struct SQLAliasedExpression : SQLSelectable { +struct SQLAliasedExpression: SQLSelectable { let expression: SQLExpression let name: String diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index cc492f4bb..a0497b7d1 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -25,7 +25,7 @@ public protocol SQLSelectable { // MARK: - SQLSelectionLiteral -struct SQLSelectionLiteral : SQLSelectable { +struct SQLSelectionLiteral: SQLSelectable { private let sqlLiteral: SQLLiteral init(literal sqlLiteral: SQLLiteral) { @@ -42,15 +42,24 @@ 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.") + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func count(distinct: Bool) -> SQLCount? { - fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } 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.") + fatalError(""" + Selection literals don't known how many columns they contain. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index 329f3b39e..25e8bfceb 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -24,18 +24,78 @@ extension SQLSpecificExpressible { /// :nodoc: extension SQLSpecificExpressible { - /// Returns a value that can be used as an argument to QueryInterfaceRequest.select() + /// Give the expression the given SQL name. /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// 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 SQLAliasedExpression(sqlExpression, name: name) + return forKey(name) } - /// Returns a value that can be used as an argument to QueryInterfaceRequest.select() + /// Give the expression the given SQL name. /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// For example: + /// + /// // SELECT (width * height) AS area FROM shape + /// let area = (Column("width") * Column("height")).forKey("area") + /// let request = Shape.select(area) + /// if let row = try Row.fetchOne(db, request) { + /// let area: Int = row["area"] + /// } + public func forKey(_ key: String) -> SQLSelectable { + 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 aliased(key.stringValue) + return forKey(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)).forKey(CodingKeys.area), + /// ] + /// } + /// + /// // SELECT width, height, (width * height) AS area FROM shape + /// let shapes: [Shape] = try Shape.fetchAll(db) + public func forKey(_ key: CodingKey) -> SQLSelectable { + return forKey(key.stringValue) } } @@ -63,4 +123,3 @@ extension SQLSpecificExpressible { return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name)) } } - diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 60d5f4a1b..525e32728 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -96,7 +96,6 @@ public struct SQLGenerationContext { /// /// A TableAlias identifies a table in a request. public class TableAlias: Hashable { - private var impl: Impl private enum Impl { /// A TableAlias is undefined when it is created by the GRDB user: /// @@ -144,6 +143,8 @@ public class TableAlias: Hashable { case proxy(TableAlias) } + private var impl: Impl + /// Resolve all proxies private var root: TableAlias { if case .proxy(let base) = impl { @@ -221,7 +222,8 @@ public class TableAlias: Hashable { let root = self.root let otherRoot = other.root switch (root.impl, otherRoot.impl) { - case let (.table(tableName: tableName, userName: userName), .table(tableName: otherTableName, userName: otherUserName)): + case let (.table(tableName: tableName, userName: userName), + .table(tableName: otherTableName, userName: otherUserName)): guard tableName == otherTableName else { // can't merge return nil diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 1ab3bf6c2..c3c5e1467 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -54,32 +54,43 @@ struct SQLQueryGenerator { GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - sql += try " FROM " + relation.source.sql(db, &context) + sql += " FROM " + sql += try relation.source.sql(db, &context) for (_, join) in relation.joins { - sql += try " " + join.sql(db, &context, leftAlias: relation.alias) + sql += " " + sql += try join.sql(db, &context, leftAlias: relation.alias) } let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + sql += SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) } if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - sql += " GROUP BY " + groupExpressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }.joined(separator: ", ") + sql += " GROUP BY " + sql += groupExpressions + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") } if havingExpressions.isEmpty == false { - sql += " HAVING " + SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) + sql += " HAVING " + sql += SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) } let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + sql += " ORDER BY " + sql += orderings + .map { $0.orderingTermSQL(&context) } + .joined(separator: ", ") } if let limit = limit { - sql += " LIMIT " + limit.sql + sql += " LIMIT " + sql += limit.sql } return sql @@ -89,10 +100,7 @@ struct SQLQueryGenerator { return try (makeSelectStatement(db), rowAdapter(db)) } - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try makeSelectStatement(db) - let databaseRegion = statement.databaseRegion - + private func optimizedDatabaseRegion(_ db: Database, _ databaseRegion: DatabaseRegion) throws -> DatabaseRegion { // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table @@ -167,7 +175,7 @@ struct SQLQueryGenerator { } /// Returns a select statement - private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + func makeSelectStatement(_ db: Database) throws -> SelectStatement { // Build an SQK generation context with all aliases found in the query, // so that we can disambiguate tables that are used several times with // SQL aliases. @@ -179,6 +187,9 @@ struct SQLQueryGenerator { // Compile & set arguments let statement = try db.makeSelectStatement(sql: sql) statement.arguments = context.arguments! // not nil for this kind of context + + // Optimize databaseRegion + statement.databaseRegion = try optimizedDatabaseRegion(db, statement.databaseRegion) return statement } @@ -409,23 +420,23 @@ private enum SQLQualifiedSource { init(_ source: SQLSource) { switch source { - case .table(let tableName, let alias): + case let .table(tableName, alias): let alias = alias ?? TableAlias(tableName: tableName) self = .table(tableName: tableName, alias: alias) - case .query(let query): + case let .query(query): self = .query(SQLQueryGenerator(query)) } } func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { switch self { - case .table(let tableName, let alias): + case let .table(tableName, alias): if let aliasName = context.aliasName(for: alias) { return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" } else { return "\(tableName.quotedDatabaseIdentifier)" } - case .query(let query): + case let .query(query): return try "(\(query.sql(db, &context)))" } } @@ -437,15 +448,22 @@ private struct SQLQualifiedJoin { case leftJoin = "LEFT JOIN" case innerJoin = "JOIN" } + let kind: Kind let condition: SQLAssociationCondition let relation: SQLQualifiedRelation - func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { + func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) } - private func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, allowingInnerJoin allowsInnerJoin: Bool) throws -> String { + private func sql( + _ db: Database, + _ context: inout SQLGenerationContext, + leftAlias: TableAlias, + allowingInnerJoin allowsInnerJoin: Bool) + throws -> String + { var allowsInnerJoin = allowsInnerJoin var sql = "" @@ -453,6 +471,10 @@ private struct SQLQualifiedJoin { case .innerJoin: guard allowsInnerJoin else { // TODO: chainOptionalRequired + // + // When we eventually implement this, make sure we both support: + // - joining(optional: assoc.joining(required: ...)) + // - having(assoc.joining(required: ...).isEmpty) fatalError("Not implemented: chaining a required association behind an optional association") } case .leftJoin: diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 52f16831f..6d7d71382 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -44,7 +44,9 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) { + public mutating func appendInterpolation( + _ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) + { sql += codingKey.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } @@ -133,7 +135,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) { sql += ordering.orderingTermSQL(&context) } - + /// Appends the request SQL, wrapped in parentheses /// /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 2c4c35c08..10a18d68b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -25,8 +25,19 @@ extension Database { /// - withoutRowID: If true, uses WITHOUT ROWID optimization. /// - 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, withoutRowID: Bool = false, body: (TableDefinition) -> Void) throws { - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool = false, + body: (TableDefinition) -> Void) + throws + { + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: withoutRowID) body(definition) let sql = try definition.sql(self) try execute(sql: sql) @@ -55,10 +66,22 @@ extension Database { /// - 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 { + 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) + // 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) @@ -84,14 +107,24 @@ extension Database { /// 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) + 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. /// /// See https://www.sqlite.org/lang_altertable.html @@ -150,10 +183,25 @@ extension Database { /// - ifNotExists: If false, no error is thrown if index already exists. /// - condition: If not nil, creates a partial index /// (see https://www.sqlite.org/partialindex.html). - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible? = nil) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + 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, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) + // 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) } @@ -176,10 +224,24 @@ extension Database { /// - 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 { + 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) + // 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) } @@ -199,10 +261,25 @@ extension Database { /// - 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 { + 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) + // 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) } @@ -253,7 +330,18 @@ extension Database { /// /// See https://www.sqlite.org/lang_createtable.html public final class TableDefinition { - private typealias KeyConstraint = (columns: [String], conflictResolution: Database.ConflictResolution?) + private typealias KeyConstraint = ( + columns: [String], + conflictResolution: Database.ConflictResolution?) + + private struct ForeignKeyConstraint { + var columns: [String] + var table: String + var destinationColumns: [String]? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var deferred: Bool + } private let name: String private let temporary: Bool @@ -262,7 +350,7 @@ public final class TableDefinition { private var columns: [ColumnDefinition] = [] private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] - private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var foreignKeyConstraints: [ForeignKeyConstraint] = [] private var checkConstraints: [SQLExpression] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { @@ -300,10 +388,14 @@ public final class TableDefinition { /// (see https://www.sqlite.org/lang_conflict.html). /// - returns: Self so that you can further refine the column definition. @discardableResult - public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition { + public func autoIncrementedPrimaryKey( + _ name: String, + onConflict conflictResolution: Database.ConflictResolution? = nil) + -> ColumnDefinition + { return column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) } - + /// Appends a table column. /// /// try db.create(table: "player") { t in @@ -383,8 +475,21 @@ public final class TableDefinition { /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. - public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) { - foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + public func foreignKey( + _ columns: [String], + references table: String, + columns destinationColumns: [String]? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred: Bool = false) + { + foreignKeyConstraints.append(ForeignKeyConstraint( + columns: columns, + table: table, + destinationColumns: destinationColumns, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) } /// Adds a CHECK constraint. @@ -451,12 +556,14 @@ public final class TableDefinition { do { var items: [String] = [] - try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) }) + try items.append(contentsOf: columns.map { + try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) + }) if let (columns, conflictResolution) = primaryKeyConstraint { var chunks: [String] = [] chunks.append("PRIMARY KEY") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -467,7 +574,7 @@ public final class TableDefinition { for (columns, conflictResolution) in uniqueKeyConstraints { var chunks: [String] = [] chunks.append("UNIQUE") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -475,28 +582,40 @@ public final class TableDefinition { items.append(chunks.joined(separator: " ")) } - for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints { + for constraint in foreignKeyConstraints { var chunks: [String] = [] chunks.append("FOREIGN KEY") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(constraint.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") chunks.append("REFERENCES") - if let destinationColumns = destinationColumns { - chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") - } else if table == name { - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + if let destinationColumns = constraint.destinationColumns { + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(destinationColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) + } else if constraint.table == name { + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } else { - let primaryKey = try db.primaryKey(table) - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKey = try db.primaryKey(constraint.table) + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKey.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } - if let deleteAction = deleteAction { + if let deleteAction = constraint.deleteAction { chunks.append("ON DELETE") chunks.append(deleteAction.rawValue) } - if let updateAction = updateAction { + if let updateAction = constraint.updateAction { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } - if deferred { + if constraint.deferred { chunks.append("DEFERRABLE INITIALLY DEFERRED") } items.append(chunks.joined(separator: " ")) @@ -504,7 +623,7 @@ public final class TableDefinition { for checkExpression in checkConstraints { var chunks: [String] = [] - chunks.append("CHECK (\(checkExpression.quotedSQL(wrappedInParenthesis: false)))") + chunks.append("CHECK (\(checkExpression.quotedSQL()))") items.append(chunks.joined(separator: " ")) } @@ -603,13 +722,22 @@ public final class ColumnDefinition { case index case unique(Database.ConflictResolution) } + + private struct ForeignKeyConstraint { + var table: String + var column: String? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var deferred: Bool + } + fileprivate let name: String private let type: Database.ColumnType? fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? private var index: Index = .none private var notNullConflictResolution: Database.ConflictResolution? private var checkConstraints: [SQLExpression] = [] - private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var foreignKeyConstraints: [ForeignKeyConstraint] = [] private var defaultExpression: SQLExpression? private var collationName: String? @@ -633,7 +761,11 @@ public final class ColumnDefinition { /// - autoincrement: If true, the primary key is autoincremented. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self { + public func primaryKey( + onConflict conflictResolution: Database.ConflictResolution? = nil, + autoincrement: Bool = false) + -> Self + { primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) return self } @@ -804,8 +936,19 @@ public final class ColumnDefinition { /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self { - foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + public func references( + _ table: String, + column: String? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred: Bool = false) -> Self + { + foreignKeyConstraints.append(ForeignKeyConstraint( + table: table, + column: column, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) return self } @@ -853,11 +996,11 @@ public final class ColumnDefinition { } for checkConstraint in checkConstraints { - chunks.append("CHECK (\(checkConstraint.quotedSQL(wrappedInParenthesis: false)))") + chunks.append("CHECK (\(checkConstraint.quotedSQL()))") } if let defaultExpression = defaultExpression { - chunks.append("DEFAULT \(defaultExpression.quotedSQL(wrappedInParenthesis: false))") + chunks.append("DEFAULT \(defaultExpression.quotedSQL())") } if let collationName = collationName { @@ -865,29 +1008,37 @@ public final class ColumnDefinition { chunks.append(collationName) } - for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints { + for constraint in foreignKeyConstraints { chunks.append("REFERENCES") - if let column = column { + if let column = constraint.column { // explicit reference - chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") - } else if table.lowercased() == tableName.lowercased() { + chunks.append("\(constraint.table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") + } else if constraint.table.lowercased() == tableName.lowercased() { // implicit autoreference - let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(constraint.table).columns + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } else { // implicit external reference - let primaryKeyColumns = try db.primaryKey(table).columns - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKeyColumns = try db.primaryKey(constraint.table).columns + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } - if let deleteAction = deleteAction { + if let deleteAction = constraint.deleteAction { chunks.append("ON DELETE") chunks.append(deleteAction.rawValue) } - if let updateAction = updateAction { + if let updateAction = constraint.updateAction { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } - if deferred { + if constraint.deferred { chunks.append("DEFERRABLE INITIALLY DEFERRED") } } @@ -931,9 +1082,13 @@ private struct IndexDefinition { } chunks.append(name.quotedDatabaseIdentifier) chunks.append("ON") - chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append(""" + \(table.quotedDatabaseIdentifier)(\ + \(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) if let condition = condition { - chunks.append("WHERE \(condition.quotedSQL(wrappedInParenthesis: false))") + chunks.append("WHERE \(condition.quotedSQL())") } return chunks.joined(separator: " ") } diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 06eaa3ea2..6534816b9 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -96,7 +96,13 @@ extension Database { /// - module: a VirtualTableModule /// - body: An optional closure that defines the virtual table. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws { + public func create( + virtualTable tableName: String, + ifNotExists: Bool = false, + using module: Module, + _ body: ((Module.TableDefinition) -> Void)? = nil) + throws + { // Define virtual table let definition = module.makeTableDefinition() if let body = body { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 5ea8bf58f..954418083 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -60,7 +60,6 @@ extension TableRecord { key: String? = nil, using foreignKey: ForeignKey? = nil) -> BelongsToAssociation - where Destination: TableRecord { let foreignKeyRequest = SQLForeignKeyRequest( originTable: databaseTableName, @@ -146,7 +145,6 @@ extension TableRecord { key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasManyAssociation - where Destination: TableRecord { let foreignKeyRequest = SQLForeignKeyRequest( originTable: Destination.databaseTableName, @@ -314,7 +312,6 @@ extension TableRecord { key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasOneAssociation - where Destination: TableRecord { let foreignKeyRequest = SQLForeignKeyRequest( originTable: Destination.databaseTableName, @@ -545,7 +542,10 @@ extension TableRecord where Self: EncodableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public func request(for association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in try [Row(PersistenceContainer(db, self))] }) @@ -558,35 +558,50 @@ extension TableRecord { // MARK: - Associations /// Creates a request that prefetches an association. - public static func including(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(all association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(all: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public static func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public static func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(required: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public static func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func joining(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().joining(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public static func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func joining(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().joining(required: association) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index fef01e1ad..fd7adae20 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -52,7 +52,11 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select(sql: "id, email") - public static func select(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func select( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return select(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -72,7 +76,11 @@ extension TableRecord { /// let request = Player.select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + _ selection: [SQLSelectable], + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(selection, as: type) } @@ -84,7 +92,11 @@ extension TableRecord { /// let request = Player.select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + _ selection: SQLSelectable..., + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(selection, as: type) } @@ -96,7 +108,12 @@ extension TableRecord { /// let request = Player.select(sql: "max(score)", as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -108,7 +125,11 @@ extension TableRecord { /// let request = Player.select(literal: SQLLiteral(sql: "max(score)"), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + literal sqlLiteral: SQLLiteral, + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(literal: sqlLiteral, as: type) } @@ -152,7 +173,10 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { + public static func filter(key: PrimaryKeyType?) + -> QueryInterfaceRequest + where PrimaryKeyType: DatabaseValueConvertible + { return all().filter(key: key) } @@ -164,7 +188,10 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { + public static func filter(keys: Sequence) + -> QueryInterfaceRequest + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { return all().filter(keys: keys) } @@ -206,7 +233,11 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func filter( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return filter(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -277,7 +308,11 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func order(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func order( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return all().order(literal: SQLLiteral(sql: sql, arguments: arguments)) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index f38439a71..85fbb95e9 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -45,7 +45,7 @@ private class RecordEncoder: Encoder { fatalError("single value encoding is not supported") } - private struct KeyedContainer : KeyedEncodingContainerProtocol { + private struct KeyedContainer: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } @@ -55,6 +55,7 @@ private class RecordEncoder: Encoder { var codingPath: [CodingKey] { return [] } + // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -69,13 +70,15 @@ private class RecordEncoder: Encoder { func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + // swiftlint:enable comma - func encode(_ value: T, forKey key: Key) throws where T : Encodable { + func encode(_ value: T, forKey key: Key) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) } + // swiftlint:disable comma func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -90,8 +93,9 @@ private class RecordEncoder: Encoder { func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + // swiftlint:disable comma - func encodeIfPresent(_ value: T?, forKey key: Key) throws where T : Encodable { + func encodeIfPresent(_ value: T?, forKey key: Key) throws where T: Encodable { if let value = value { try recordEncoder.encode(value, forKey: key) } else { @@ -99,7 +103,11 @@ private class RecordEncoder: Encoder { } } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer { + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: Key) + -> KeyedEncodingContainer + { fatalError("Not implemented") } @@ -123,7 +131,7 @@ private class RecordEncoder: Encoder { } @inline(__always) - fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T : Encodable { + fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T: Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { @@ -151,8 +159,9 @@ private class RecordEncoder: Encoder { // database inspection. Thanks to SQLite weak typing, we won't // have any trouble decoding this string into data when we // eventually perform JSON decoding. - // TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String + // TODO: possible optimization: avoid this conversion to string, + // and store raw data bytes as an SQLite string + let jsonString = String(data: jsonData, encoding: .utf8)! persist(jsonString, forKey: key) } } @@ -174,7 +183,7 @@ private class ColumnEncoder: Encoder { self.key = key } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. @@ -214,7 +223,7 @@ extension ColumnEncoder: SingleValueEncodingContainer { func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) } - func encode(_ value: T) throws where T : Encodable { + func encode(_ value: T) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } } @@ -233,7 +242,7 @@ private struct JSONRequiredEncoder: Encoder { self.codingPath = codingPath } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -265,9 +274,14 @@ private struct JSONRequiredEncoder: Encoder { func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: T, forKey key: KeyType) throws where T : Encodable { throw JSONRequiredError() } + func encode(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: KeyType) -> KeyedEncodingContainer where NestedKey : CodingKey { + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: KeyType) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { let container = KeyedContainer(codingPath: codingPath + [key]) return KeyedEncodingContainer(container) } @@ -302,13 +316,16 @@ extension JSONRequiredEncoder: SingleValueEncodingContainer { func encode(_ value: Float ) throws { throw JSONRequiredError() } func encode(_ value: Double) throws { throw JSONRequiredError() } func encode(_ value: String) throws { throw JSONRequiredError() } - func encode(_ value: T) throws where T : Encodable { throw JSONRequiredError() } + func encode(_ value: T) throws where T: Encodable { throw JSONRequiredError() } } extension JSONRequiredEncoder: UnkeyedEncodingContainer { var count: Int { return 0 } - mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy keyType: NestedKey.Type) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -323,15 +340,15 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) -fileprivate var iso8601Formatter: ISO8601DateFormatter = { +private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() -private extension DatabaseDateEncodingStrategy { +extension DatabaseDateEncodingStrategy { @inline(__always) - func encode(_ date: Date) -> DatabaseValueConvertible? { + fileprivate func encode(_ date: Date) -> DatabaseValueConvertible? { switch self { case .deferredToDate: return date.databaseValue @@ -357,9 +374,9 @@ private extension DatabaseDateEncodingStrategy { } } -private extension DatabaseUUIDEncodingStrategy { +extension DatabaseUUIDEncodingStrategy { @inline(__always) - func encode(_ uuid: UUID) -> DatabaseValueConvertible? { + fileprivate func encode(_ uuid: UUID) -> DatabaseValueConvertible? { switch self { case .deferredToUUID: return uuid.databaseValue diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 378fe7950..ae3e635b9 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -171,7 +171,8 @@ extension EncodableRecord { /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. public func databaseChanges(from record: Record) -> [String: DatabaseValue] { - return Dictionary(uniqueKeysWithValues: PersistenceContainer(self).changesIterator(from: PersistenceContainer(record))) + let changes = PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)) + return Dictionary(uniqueKeysWithValues: changes) } } diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index e37963192..fb6d49a94 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension FetchableRecord where Self: Decodable { @@ -85,6 +85,7 @@ private struct RowDecoder: Decoder { return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil) } + // swiftlint:disable comma func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] } @@ -99,8 +100,9 @@ private struct RowDecoder: Decoder { func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] } func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] } + // swiftlint:enable comma - func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -130,7 +132,7 @@ private struct RowDecoder: Decoder { return nil } - func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { + func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -159,7 +161,7 @@ private struct RowDecoder: Decoder { let decoder = PrefetchedRowsDecoder(rows: prefetchedRows, codingPath: codingPath) return try T(from: decoder) } - + // Key is not a column, and not a scope. // // Should be throw an error? Well... The use case is the following: @@ -193,7 +195,9 @@ private struct RowDecoder: Decoder { return try decode(type, fromRow: row, codingPath: codingPath + [key]) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) + throws -> KeyedDecodingContainer where NestedKey: CodingKey + { fatalError("not implemented") } @@ -215,7 +219,13 @@ private struct RowDecoder: Decoder { // Helper methods @inline(__always) - private func decode(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable { + private func decode( + _ type: T.Type, + fromRow row: Row, + codingPath: [CodingKey]) + throws -> T + where T: Decodable + { if let type = T.self as? FetchableRecord.Type { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T @@ -234,7 +244,14 @@ private struct RowDecoder: Decoder { } @inline(__always) - private func decode(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable { + private func decode( + _ type: T.Type, + fromRow row: Row, + columnAtIndex index: Int, + key: Key) + throws -> T + where T: Decodable + { do { // This decoding will fail for types that decode from keyed // or unkeyed containers, because we're decoding a single @@ -248,7 +265,10 @@ private struct RowDecoder: Decoder { } catch is JSONRequiredError { // Decode from JSON guard let data = row.dataNoCopy(atIndex: index) else { - fatalConversionError(to: T.self, from: row[index], conversionContext: ValueConversionContext(row).atColumn(index)) + fatalConversionError( + to: T.self, + from: row[index], + conversionContext: ValueConversionContext(row).atColumn(index)) } return try R .databaseJSONDecoder(for: key.stringValue) @@ -272,7 +292,7 @@ private struct PrefetchedRowsDecoder: Decoder { self.currentIndex = 0 } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key: CodingKey { fatalError("keyed decoding from prefetched rows is not supported") } @@ -298,13 +318,16 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { return false } - mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } let decoder = RowDecoder(row: rows[currentIndex], codingPath: codingPath) return try T(from: decoder) } - mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy type: NestedKey.Type) + throws -> KeyedDecodingContainer + where NestedKey: CodingKey + { fatalError("not implemented") } @@ -361,7 +384,7 @@ extension ColumnDecoder: SingleValueDecodingContainer { func decode(_ type: Double.Type) throws -> Double { return row[columnIndex] } func decode(_ type: String.Type) throws -> String { return row[columnIndex] } - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { @@ -385,15 +408,15 @@ private struct MissingColumnError: Error { } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) -fileprivate var iso8601Formatter: ISO8601DateFormatter = { +private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() -private extension DatabaseDateDecodingStrategy { +extension DatabaseDateDecodingStrategy { @inline(__always) - func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { + fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { if let sqliteStatement = row.sqliteStatement { return decodeIfPresent( sqliteStatement: sqliteStatement, @@ -406,7 +429,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { + fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { if let sqliteStatement = row.sqliteStatement { return decode( sqliteStatement: sqliteStatement, @@ -419,7 +442,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { + fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { switch self { case .deferredToDate: return Date(sqliteStatement: sqliteStatement, index: index) @@ -458,7 +481,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { + fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } @@ -466,7 +489,11 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + fileprivate func decode( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Date + { if let date = dateFromDatabaseValue(dbValue) { return date } else { @@ -475,7 +502,11 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + fileprivate func decodeIfPresent( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Date? + { if dbValue.isNull { return nil } else if let date = dateFromDatabaseValue(dbValue) { diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 937736486..17457deab 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -77,7 +77,10 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: Sequence) throws -> RecordCursor where Sequence.Element: DatabaseValueConvertible { + public static func fetchCursor(_ db: Database, keys: Sequence) + throws -> RecordCursor + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { return try filter(keys: keys).fetchCursor(db) } @@ -92,7 +95,9 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible { + public static func fetchAll(_ db: Database, keys: Sequence) + throws -> [Self] + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database @@ -110,7 +115,10 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: PrimaryKeyType?) throws -> Self? { + public static func fetchOne(_ db: Database, key: PrimaryKeyType?) + throws -> Self? + where PrimaryKeyType: DatabaseValueConvertible + { guard let key = key else { // Avoid hitting the database return nil @@ -126,7 +134,10 @@ extension FetchableRecord where Self: TableRecord { /// Returns a cursor over records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player + /// // Cursor of Player + /// let players = try Player.fetchCursor(db, keys: [ + /// ["email": "a@example.com"], + /// ["email": "b@example.com"]]) /// while let player = try players.next() { // Player /// ... /// } @@ -138,14 +149,19 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor { + public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) + throws -> RecordCursor + { return try filter(keys: keys).fetchCursor(db) } /// Returns an array of records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player] + /// // [Player] + /// let players = try Player.fetchAll(db, keys: [ + /// ["email": "a@example.com"], + /// ["email": "b@example.com"]]) /// /// The order of records in the returned array is undefined. /// diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 34653de2a..7dbb8b73f 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Types that adopt FetchableRecord can be initialized from a database Row. @@ -160,7 +160,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RecordCursor + { return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -175,7 +180,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -190,7 +200,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } } @@ -218,7 +233,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> RecordCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -233,7 +254,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -248,7 +275,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -319,7 +352,7 @@ extension FetchableRecord { return nil } try supplementaryFetch([row]) - return Self.init(row: row) + return .init(row: row) } else { return try fetchOne(request.statement, adapter: request.adapter) } @@ -385,7 +418,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// try dbQueue.read { db in /// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RecordCursor : Cursor { +public final class RecordCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _row: Row // Reused for performance @usableFromInline let _sqliteStatement: SQLiteStatement @@ -396,6 +429,9 @@ public final class RecordCursor : Cursor { _row = try Row(statement: statement).adapted(with: adapter, layout: statement) _sqliteStatement = statement.sqliteStatement _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { @@ -440,7 +476,7 @@ public final class RecordCursor : Cursor { public enum DatabaseDateDecodingStrategy { /// The strategy that uses formatting from the Date structure. /// - /// It decodes numeric values as a nunber of seconds since Epoch + /// It decodes numeric values as a number of seconds since Epoch /// (midnight UTC on January 1st, 1970). /// /// It decodes strings in the following formats, assuming UTC time zone. diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 645783cb4..46c07301f 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -1,7 +1,7 @@ import Foundation #if os(iOS) - import UIKit +import UIKit #endif /// You use FetchedRecordsController to track changes in the results of an @@ -85,7 +85,7 @@ public final class FetchedRecordsController { if let isSameRecord = isSameRecord { itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } } } else { - itemsAreIdenticalFactory = { _ in { _,_ in false } } + itemsAreIdenticalFactory = { _ in { _, _ in false } } } try self.init( @@ -112,7 +112,7 @@ public final class FetchedRecordsController { self.databaseWriter = databaseWriter self.queue = queue } - + /// Executes the controller's fetch request. /// /// After executing this method, you can access the the fetched objects with @@ -162,7 +162,10 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(_ request: Request) throws where Request: FetchRequest, Request.RowDecoder == Record { + public func setRequest(_ request: Request) + throws + where Request: FetchRequest, Request.RowDecoder == Record + { self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in let region = try request.databaseRegion(db) @@ -196,7 +199,12 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws { + public func setRequest( + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws + { try setRequest(SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -211,19 +219,27 @@ public final class FetchedRecordsController { /// removed, moved, or updated. /// - didChange: Invoked after records have been updated. public func trackChanges( - willChange: ((FetchedRecordsController) -> ())? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())? = nil, - didChange: ((FetchedRecordsController) -> ())? = nil) + willChange: ((FetchedRecordsController) -> Void)? = nil, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, + didChange: ((FetchedRecordsController) -> Void)? = nil) { - // I hate you SE-0110. - let wrappedWillChange: ((FetchedRecordsController, Void) -> ())? + // Without SE-0110, we could simply: + // + // trackChanges( + // fetchAlongside: { _ in }, + // willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, + // onChange: onChange, + // didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) + // + // But instead: + let wrappedWillChange: ((FetchedRecordsController, Void) -> Void)? if let willChange = willChange { wrappedWillChange = { (controller, _) in willChange(controller) } } else { wrappedWillChange = nil } - let wrappedDidChange: ((FetchedRecordsController, Void) -> ())? + let wrappedDidChange: ((FetchedRecordsController, Void) -> Void)? if let didChange = didChange { wrappedDidChange = { (controller, _) in didChange(controller) } } else { @@ -235,15 +251,8 @@ public final class FetchedRecordsController { willChange: wrappedWillChange, onChange: onChange, didChange: wrappedDidChange) - - // Without bloody SE-0110: -// trackChanges( -// fetchAlongside: { _ in }, -// willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, -// onChange: onChange, -// didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) } - + /// Registers changes notification callbacks. /// /// This method must be used from the controller's dispatch queue (the @@ -262,9 +271,9 @@ public final class FetchedRecordsController { /// - didChange: Invoked after records have been updated. public func trackChanges( fetchAlongside: @escaping (Database) throws -> T, - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())? = nil, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())? = nil) + willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, + didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil) { // If some changes are currently processed, make sure they are // discarded because they would trigger previously set callbacks. @@ -276,20 +285,20 @@ public final class FetchedRecordsController { return } - var willProcessTransaction: () -> () = { } - var didProcessTransaction: () -> () = { } + var willProcessTransaction: () -> Void = { } + var didProcessTransaction: () -> Void = { } #if os(iOS) - if let application = application { - var backgroundTaskID: UIBackgroundTaskIdentifier! = nil - willProcessTransaction = { - backgroundTaskID = application.beginBackgroundTask { - application.endBackgroundTask(backgroundTaskID) - } - } - didProcessTransaction = { + if let application = application { + var backgroundTaskID: UIBackgroundTaskIdentifier! = nil + willProcessTransaction = { + backgroundTaskID = application.beginBackgroundTask { application.endBackgroundTask(backgroundTaskID) } } + didProcessTransaction = { + application.endBackgroundTask(backgroundTaskID) + } + } #endif let initialItems = fetchedItems @@ -312,7 +321,7 @@ public final class FetchedRecordsController { } } } - + /// Registers an error callback. /// /// Whenever the controller could not look for changes after a transaction @@ -325,7 +334,7 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> ()) { + public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> Void) { self.errorHandler = errorHandler } @@ -369,7 +378,7 @@ public final class FetchedRecordsController { /// Support for allowBackgroundChangeTracking(in:) var application: UIApplication? #endif - + /// The items fileprivate var fetchedItems: [Item]? @@ -378,19 +387,19 @@ public final class FetchedRecordsController { /// The record comparator factory (support for request change) private let itemsAreIdenticalFactory: ItemComparatorFactory - + /// The request fileprivate typealias ItemRequest = AnyFetchRequest> fileprivate var request: ItemRequest /// The observed database region - private var region : DatabaseRegion + private var region: DatabaseRegion /// The eventual current database observer private var observer: FetchedRecordsObserver? /// The eventual error handler - fileprivate var errorHandler: ((FetchedRecordsController, Error) -> ())? + fileprivate var errorHandler: ((FetchedRecordsController, Error) -> Void)? } extension FetchedRecordsController where Record: TableRecord { @@ -510,15 +519,15 @@ extension FetchedRecordsController where Record: TableRecord { /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. -private final class FetchedRecordsObserver : TransactionObserver { +private final class FetchedRecordsObserver: TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item]! // ought to be not nil when observer has started tracking transactions let queue: DispatchQueue // protects items let region: DatabaseRegion - var fetchAndNotifyChanges: (FetchedRecordsObserver) -> () + var fetchAndNotifyChanges: (FetchedRecordsObserver) -> Void - init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> ()) { + init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> Void) { self.isValid = true self.items = nil self.needsComputeChanges = false @@ -565,12 +574,18 @@ private final class FetchedRecordsObserver : Transactio // MARK: - Changes +private typealias FetchCompletionHandler = ( + DatabaseResult<(fetchedItems: [Item], + fetchedAlongside: T, + observer: FetchedRecordsObserver)>) + -> Void + private func makeFetchFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, - willProcessTransaction: @escaping () -> (), - completion: @escaping (DatabaseResult<(fetchedItems: [Item], fetchedAlongside: T, observer: FetchedRecordsObserver)>) -> () - ) -> (FetchedRecordsObserver) -> () + willProcessTransaction: @escaping () -> Void, + completion: @escaping FetchCompletionHandler + ) -> (FetchedRecordsObserver) -> Void { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: @@ -623,12 +638,12 @@ private func makeFetchAndNotifyChangesFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, itemsAreIdentical: @escaping ItemComparator, - willProcessTransaction: @escaping () -> (), - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())?, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())?, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())?, - didProcessTransaction: @escaping () -> () - ) -> (FetchedRecordsObserver) -> () + willProcessTransaction: @escaping () -> Void, + willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)?, + didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, + didProcessTransaction: @escaping () -> Void + ) -> (FetchedRecordsObserver) -> Void { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: @@ -637,12 +652,16 @@ private func makeFetchAndNotifyChangesFunction( // // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. - return makeFetchFunction(controller: controller, fetchAlongside: fetchAlongside, willProcessTransaction: willProcessTransaction) { [weak controller] result in + return makeFetchFunction( + controller: controller, + fetchAlongside: fetchAlongside, + willProcessTransaction: willProcessTransaction) + { [weak controller] result in // Return if fetched records controller has been deallocated guard let callbackQueue = controller?.queue else { return } switch result { - case .failure(let error): + case let .failure(error): callbackQueue.async { // Now we can retain controller guard let strongController = controller else { return } @@ -650,7 +669,7 @@ private func makeFetchAndNotifyChangesFunction( didProcessTransaction() } - case .success((fetchedItems: let fetchedItems, fetchedAlongside: let fetchedAlongside, observer: let observer)): + case let .success((fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: observer)): // Return if there is no change let changes: [ItemChange] if onChange != nil { @@ -689,7 +708,12 @@ private func makeFetchAndNotifyChangesFunction( } } -private func computeChanges(from s: [Item], to t: [Item], itemsAreIdentical: ItemComparator) -> [ItemChange] { +private func computeChanges( + from s: [Item], + to t: [Item], + itemsAreIdentical: ItemComparator) + -> [ItemChange] +{ let m = s.count let n = t.count @@ -754,8 +778,12 @@ private func computeChanges(from s: [Item], to t: [Item] /// If *change* is a deletion or an insertion, and there is a matching inverse /// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned. /// As a convenience, the index of the matched change is returned as well. - func merge(change: ItemChange, in changes: [ItemChange], itemsAreIdentical: ItemComparator) -> (mergedChange: ItemChange, mergedIndex: Int)? { - + func merge( + change: ItemChange, + in changes: [ItemChange], + itemsAreIdentical: ItemComparator) + -> (mergedChange: ItemChange, mergedIndex: Int)? + { /// Returns the changes between two rows: a dictionary [key: oldValue] /// Precondition: both rows have the same columns func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] { @@ -770,30 +798,52 @@ private func computeChanges(from s: [Item], to t: [Item] } switch change { - case .insertion(let newItem, let newIndexPath): + case let .insertion(newItem, newIndexPath): // Look for a matching deletion for (index, otherChange) in changes.enumerated() { - guard case .deletion(let oldItem, let oldIndexPath) = otherChange else { continue } + guard case let .deletion(oldItem, oldIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return ( + ItemChange.update( + item: newItem, + indexPath: oldIndexPath, + changes: rowChanges), + index) } else { - return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return ( + ItemChange.move( + item: newItem, + indexPath: oldIndexPath, + newIndexPath: newIndexPath, + changes: rowChanges), + index) } } return nil - case .deletion(let oldItem, let oldIndexPath): + case let .deletion(oldItem, oldIndexPath): // Look for a matching insertion for (index, otherChange) in changes.enumerated() { - guard case .insertion(let newItem, let newIndexPath) = otherChange else { continue } + guard case let .insertion(newItem, newIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return ( + ItemChange.update( + item: newItem, + indexPath: oldIndexPath, + changes: rowChanges), + index) } else { - return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return ( + ItemChange.move( + item: newItem, + indexPath: oldIndexPath, + newIndexPath: newIndexPath, + changes: rowChanges), + index) } } return nil @@ -807,7 +857,9 @@ private func computeChanges(from s: [Item], to t: [Item] var mergedChanges: [ItemChange] = [] var updateChanges: [ItemChange] = [] for change in changes { - if let (mergedChange, mergedIndex) = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) { + if let (mergedChange, mergedIndex) + = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) + { mergedChanges.remove(at: mergedIndex) switch mergedChange { case .update: @@ -829,10 +881,8 @@ private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item IndexPath? { let item = Item(row: Row(record)) - guard let fetchedItems = fetchedItems, let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) else { - return nil + guard + let fetchedItems = fetchedItems, + let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) + else { + return nil } return IndexPath(indexes: [0, index]) } @@ -917,13 +970,13 @@ extension ItemChange { var fetchedRecordChange: FetchedRecordChange { switch self { - case .insertion(item: _, indexPath: let indexPath): + case let .insertion(item: _, indexPath: indexPath): return .insertion(indexPath: indexPath) - case .deletion(item: _, indexPath: let indexPath): + case let .deletion(item: _, indexPath: indexPath): return .deletion(indexPath: indexPath) - case .move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes): + case let .move(item: _, indexPath: indexPath, newIndexPath: newIndexPath, changes: changes): return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes) - case .update(item: _, indexPath: let indexPath, changes: let changes): + case let .update(item: _, indexPath: indexPath, changes: changes): return .update(indexPath: indexPath, changes: changes) } } @@ -932,16 +985,16 @@ extension ItemChange { extension ItemChange: CustomStringConvertible { var description: String { switch self { - case .insertion(let item, let indexPath): + case let .insertion(item, indexPath): return "Insert \(item) at \(indexPath)" - case .deletion(let item, let indexPath): + case let .deletion(item, indexPath): return "Delete \(item) from \(indexPath)" - case .move(let item, let indexPath, let newIndexPath, changes: let changes): + case let .move(item, indexPath, newIndexPath, changes: changes): return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)" - case .update(let item, let indexPath, let changes): + case let .update(item, indexPath, changes): return "Update \(item) at \(indexPath) with changes: \(changes)" } } @@ -973,16 +1026,16 @@ public enum FetchedRecordChange { extension FetchedRecordChange: CustomStringConvertible { public var description: String { switch self { - case .insertion(let indexPath): + case let .insertion(indexPath): return "Insertion at \(indexPath)" - case .deletion(let indexPath): + case let .deletion(indexPath): return "Deletion from \(indexPath)" - case .move(let indexPath, let newIndexPath, changes: let changes): + case let .move(indexPath, newIndexPath, changes: changes): return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)" - case .update(let indexPath, let changes): + case let .update(indexPath, changes): return "Update at \(indexPath) with changes: \(changes)" } } @@ -1014,11 +1067,11 @@ public struct FetchedRecordsSectionInfo { // MARK: - Item -private final class Item : FetchableRecord, Equatable { +private final class Item: FetchableRecord, Equatable { let row: Row // Records are lazily loaded - lazy var record: T = T(row: self.row) + lazy var record = T(row: self.row) init(row: Row) { self.row = row.copy() diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 1fb4772ea..e8dd673cd 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,6 +1,5 @@ extension Database.ConflictResolution { - @usableFromInline - var invalidatesLastInsertedRowID: Bool { + @usableFromInline var invalidatesLastInsertedRowID: Bool { switch self { case .abort, .fail, .rollback, .replace: return false @@ -55,7 +54,7 @@ public struct PersistenceConflictPolicy { } /// Types that adopt MutablePersistableRecord can be inserted, updated, and deleted. -public protocol MutablePersistableRecord : EncodableRecord, TableRecord { +public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -219,7 +218,10 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: ColumnExpression { + public func update(_ db: Database, columns: Sequence) + throws + where Sequence: Swift.Sequence, Sequence.Element: ColumnExpression + { try update(db, columns: Set(columns.map { $0.name })) } @@ -230,7 +232,10 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element == String { + public func update(_ db: Database, columns: Sequence) + throws + where Sequence: Swift.Sequence, Sequence.Element == String + { try update(db, columns: Set(columns)) } @@ -303,7 +308,7 @@ extension MutablePersistableRecord { try change(&self) return try updateChanges(db, from: container) } - + /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// @@ -392,9 +397,13 @@ extension MutablePersistableRecord { @inlinable public func performUpdate(_ db: Database, columns: Set) throws { let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { - // Nil primary key - throw dao.makeRecordNotFoundError() + guard + let statement = try dao.updateStatement( + columns: columns, + onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -463,7 +472,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord where Self: AnyObject { // MARK: - Record Comparison - + /// Mutates the record according to the provided closure, and then, if the /// record has any difference from its previous version, executes an /// UPDATE statement so that those differences and only those difference are @@ -534,7 +543,10 @@ extension MutablePersistableRecord { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible { + public static func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database @@ -563,7 +575,10 @@ extension MutablePersistableRecord { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType?) throws -> Bool { + public static func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { guard let key = key else { // Avoid hitting the database return false @@ -617,7 +632,7 @@ extension MutablePersistableRecord { /// /// Unlike MutablePersistableRecord, the insert() and save() methods are not /// mutating methods. -public protocol PersistableRecord : MutablePersistableRecord { +public protocol PersistableRecord: MutablePersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -749,7 +764,7 @@ extension PersistableRecord { extension PersistenceContainer { /// Convenience initializer from a database connection and a record - init(_ db: Database,_ record: Record) throws { + init(_ db: Database, _ record: Record) throws { let databaseTableName = type(of: record).databaseTableName let columnCount = try db.columns(in: databaseTableName).count self.init(minimumCapacity: columnCount) @@ -916,9 +931,16 @@ extension InsertQuery { let sql: String switch onConflict { case .abort: - sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + sql = """ + INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ default: - sql = "INSERT OR \(onConflict.rawValue) INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + sql = """ + INSERT OR \(onConflict.rawValue) \ + INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ } InsertQuery.sqlCache.write { $0[self] = sql } return sql @@ -946,9 +968,17 @@ extension UpdateQuery { let sql: String switch onConflict { case .abort: - sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + sql = """ + UPDATE \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ default: - sql = "UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + sql = """ + UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ } UpdateQuery.sqlCache.write { $0[self] = sql } return sql diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 4b220218e..2ee2b8a0b 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : FetchableRecord, TableRecord, PersistableRecord { +open class Record: FetchableRecord, TableRecord, PersistableRecord { // MARK: - Initializers @@ -11,7 +11,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { } /// Creates a Record from a row. - required public init(row: Row) { + public required init(row: Row) { if row.isFetched { // Take care of the hasDatabaseChanges flag. // @@ -93,7 +93,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { return [AllColumns()] } - + /// Defines the values persisted in the database. /// /// Store in the *container* argument all values that should be stored in @@ -216,7 +216,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// Reference row for the *hasDatabaseChanges* property. var referenceRow: Row? - + // MARK: - CRUD /// Executes an INSERT statement. @@ -274,9 +274,13 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { // // But this would trigger two calls to `encode(to:)`. let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { - // Nil primary key - throw dao.makeRecordNotFoundError() + guard + let statement = try dao.updateStatement( + columns: columns, + onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -302,7 +306,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - final public func updateChanges(_ db: Database) throws -> Bool { + public final func updateChanges(_ db: Database) throws -> Bool { let changedColumns = Set(databaseChanges.keys) if changedColumns.isEmpty { return false @@ -331,7 +335,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). - final public func save(_ db: Database) throws { + public final func save(_ db: Database) throws { try performSave(db) } diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index c9f527035..1d570786d 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -51,6 +51,7 @@ extension Inflections { // become more complete. This is a safety measure to keep existing // applications from breaking. // + // swiftlint:disable:next line_length // https://github.com/rails/rails/blob/b2eb1d1c55a59fee1e6c4cba7030d8ceb524267c/activesupport/lib/active_support/inflections.rb var inflections = Inflections() diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index f8dbabf33..da6c5b176 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -59,7 +59,11 @@ public struct Inflections { /// - options: Regular expression options (defaults to /// `[.caseInsensitive]`). /// - template: A replacement template string. - public mutating func plural(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String) { + public mutating func plural( + _ pattern: String, + options: NSRegularExpression.Options = [.caseInsensitive], + _ template: String) + { let reg = try! NSRegularExpression(pattern: pattern, options: options) pluralizeRules.append((reg, template)) } @@ -75,7 +79,11 @@ public struct Inflections { /// - options: Regular expression options (defaults to /// `[.caseInsensitive]`). /// - template: A replacement template string. - public mutating func singular(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String) { + public mutating func singular( + _ pattern: String, + options: NSRegularExpression.Options = [.caseInsensitive], + _ template: String) + { let reg = try! NSRegularExpression(pattern: pattern, options: options) singularizeRules.append((reg, template)) } @@ -155,7 +163,9 @@ public struct Inflections { /// inflections.pluralize("bar") // "bars" private mutating func uncountableWord(_ word: String) { let escWord = NSRegularExpression.escapedPattern(for: word) - uncountablesRegularExpressions[word] = try! NSRegularExpression(pattern: "\\b\(escWord)\\Z", options: [.caseInsensitive]) + uncountablesRegularExpressions[word] = try! NSRegularExpression( + pattern: "\\b\(escWord)\\Z", + options: [.caseInsensitive]) } private func isUncountable(_ string: String) -> Bool { @@ -181,7 +191,7 @@ public struct Inflections { \(string.suffix(from: endIndexOfDigitlessRadical)) """ } - + private func inflectWord(_ string: String, with rules: [(NSRegularExpression, String)]) -> String { if string.isEmpty { return string @@ -189,8 +199,8 @@ public struct Inflections { let range = NSRange(string.startIndex.. 0 { + let matchCount = reg.replaceMatches(in: result, options: [], range: range, withTemplate: template) + if matchCount > 0 { return String(result) } } @@ -203,7 +213,7 @@ public struct Inflections { /// startIndexOfLastWord("fooBar") -> "Bar" static func startIndexOfLastWord(_ string: String) -> String.Index { let range = NSRange(string.startIndex.. { keys.reserveCapacity(minimumCapacity) dictionary = Dictionary(minimumCapacity: minimumCapacity) } - + /// Returns the value associated with key, or nil. @usableFromInline subscript(_ key: Key) -> Value? { @@ -42,14 +42,14 @@ struct OrderedDictionary { } } } - + /// Returns the value associated with key, or the default value. @inlinable subscript(_ key: Key, default defaultValue: Value) -> Value { get { return dictionary[key] ?? defaultValue } set { self[key] = newValue } } - + /// Appends the given value for the given key. /// /// - precondition: There is no value associated with key yet. @@ -111,7 +111,8 @@ struct OrderedDictionary { } extension OrderedDictionary: Collection { - @usableFromInline typealias Index = Int + @usableFromInline + typealias Index = Int @usableFromInline var startIndex: Int { return 0 @@ -121,18 +122,21 @@ extension OrderedDictionary: Collection { return keys.count } - @usableFromInline func index(after i: Int) -> Int { + @usableFromInline + func index(after i: Int) -> Int { return i + 1 } - @usableFromInline subscript(position: Int) -> (key: Key, value: Value) { + @usableFromInline + subscript(position: Int) -> (key: Key, value: Value) { let key = keys[position] return (key: key, value: dictionary[key]!) } } extension OrderedDictionary: ExpressibleByDictionaryLiteral { - @usableFromInline init(dictionaryLiteral elements: (Key, Value)...) { + @usableFromInline + init(dictionaryLiteral elements: (Key, Value)...) { self.keys = elements.map { $0.0 } self.dictionary = Dictionary(uniqueKeysWithValues: elements) } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 444d9262d..8c9c49657 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -58,7 +58,7 @@ final class Pool { /// Returns a tuple (element, release) /// Client MUST call release() after the element has been used. - func get() throws -> (T, () -> ()) { + func get() throws -> (T, () -> Void) { _ = semaphore.wait(timeout: .distantFuture) do { let item = try items.write { items -> Item in @@ -97,7 +97,7 @@ final class Pool { /// Performs a block on each pool element, available or not. /// The block is run is some arbitrary dispatch queue. - func forEach(_ body: (T) throws -> ()) rethrows { + func forEach(_ body: (T) throws -> Void) rethrows { try items.read { items in for item in items { try body(item.element) @@ -112,7 +112,7 @@ final class Pool { /// Empty the pool. Currently used items won't be reused. /// Eventual block is executed before any other element is dequeued. - func clear(andThen block: () throws -> ()) rethrows { + func clear(andThen block: () throws -> Void) rethrows { try items.write { items in items.removeAll() try block() diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index ae666ec52..a29d65202 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -7,8 +7,7 @@ extension String { /// SQL query. /// /// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)") - @inlinable - public var quotedDatabaseIdentifier: String { + @inlinable public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html return "\"\(self)\"" } @@ -38,7 +37,7 @@ public protocol _OptionalProtocol { /// This conformance is an implementation detail of GRDB. Don't rely on it. /// /// :nodoc: -extension Optional : _OptionalProtocol { +extension Optional: _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public typealias _Wrapped = Wrapped @@ -49,7 +48,12 @@ extension Optional : _OptionalProtocol { /// Reserved for GRDB: do not use. @inlinable -func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) { +func GRDBPrecondition( + _ condition: @autoclosure() -> Bool, + _ message: @autoclosure() -> String = "", + file: StaticString = #file, + line: UInt = #line) +{ /// Custom precondition function which aims at solving /// https://bugs.swift.org/browse/SR-905 and /// https://github.com/groue/GRDB.swift/issues/37 @@ -87,7 +91,7 @@ extension DispatchQueue { DispatchQueue.main.setSpecific(key: key, value: ()) return key }() - + static var isMain: Bool { return DispatchQueue.getSpecific(key: mainKey) != nil } diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 78c0e0266..298832ba5 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -125,9 +125,9 @@ 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. @@ -335,12 +335,15 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllValues") -public typealias DatabaseValuesReducer = ValueReducers.AllValues where RowDecoder: DatabaseValueConvertible +public typealias DatabaseValuesReducer = ValueReducers.AllValues + where RowDecoder: DatabaseValueConvertible /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.OneValue") -public typealias DatabaseValueReducer = ValueReducers.OneValue where RowDecoder: DatabaseValueConvertible +public typealias DatabaseValueReducer = ValueReducers.OneValue + where RowDecoder: DatabaseValueConvertible /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllOptionalValues") -public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues where RowDecoder: DatabaseValueConvertible +public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues + where RowDecoder: DatabaseValueConvertible diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index b588a62d0..f54b4cae5 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -250,8 +250,12 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllRecords") -public typealias FetchableRecordsReducer = ValueReducers.AllRecords where RowDecoder: FetchableRecord +public typealias FetchableRecordsReducer + = ValueReducers.AllRecords + where RowDecoder: FetchableRecord /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.OneRecord") -public typealias FetchableRecordReducer = ValueReducers.OneRecord where RowDecoder: FetchableRecord +public typealias FetchableRecordReducer + = ValueReducers.OneRecord + where RowDecoder: FetchableRecord diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift index 0f9705c3b..b40084420 100644 --- a/GRDB/ValueObservation/ValueObservation+MapReducer.swift +++ b/GRDB/ValueObservation/ValueObservation+MapReducer.swift @@ -4,11 +4,11 @@ extension ValueObservation { /// Returns a ValueObservation with a transformed reducer. public func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) -> ValueObservation { let makeReducer = self.makeReducer - var observation = ValueObservation( - tracking: observedRegion, - reducer: { db in try transform(db, makeReducer(db)) }) - observation.scheduling = scheduling - observation.requiresWriteAccess = requiresWriteAccess - return observation + return ValueObservation( + baseRegion: baseRegion, + observesSelectedRegion: observesSelectedRegion, + makeReducer: { db in try transform(db, makeReducer(db)) }, + requiresWriteAccess: requiresWriteAccess, + scheduling: scheduling) } } diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index fa0f1ae77..43f748231 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -60,7 +60,7 @@ extension FetchRequest where RowDecoder == Row { } extension ValueObservation where Reducer == Void { - + // MARK: - Row Observation /// Creates a ValueObservation which observes *request*, and notifies diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 8a152f1c2..0f11dd39d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -74,9 +74,15 @@ public enum ValueScheduling { /// } public struct ValueObservation { /// A closure that is evaluated when the observation starts, and returns - /// the observed database region. - var observedRegion: (Database) throws -> DatabaseRegion + /// a "base" observed database region. + /// + /// See also `observesSelectedRegion` + var baseRegion: (Database) throws -> DatabaseRegion + /// If true, the region selected by the reducer is observed as well + /// as `baseRegion`. + var observesSelectedRegion: Bool + /// The reducer is created when observation starts, and is triggered upon /// each database change in *observedRegion*. var makeReducer: (Database) throws -> Reducer @@ -87,7 +93,7 @@ public struct ValueObservation { /// /// Don't set this flag to true unless you really need it. A read/write /// observation is less efficient than a read-only observation. - public var requiresWriteAccess: Bool = false + public var requiresWriteAccess: Bool /// `scheduling` controls how fresh values are notified. Default /// is `.mainQueue`. @@ -144,25 +150,7 @@ public struct ValueObservation { /// /// When the database changes, other values are notified on /// unspecified queues. - public var scheduling: ValueScheduling = .mainQueue - - // Not public because we foster DatabaseRegionConvertible. - // See ValueObservation.tracking(_:reducer:) - init( - tracking region: @escaping (Database) throws -> DatabaseRegion, - reducer: @escaping (Database) throws -> Reducer) - { - self.observedRegion = { db in - // Remove views from the observed region. - // - // We can do it because we are only interested in modifications in - // actual tables. And we want to do it because we have a fast path - // for simple regions that span a single table. - let views = try db.schema().names(ofType: .view) - return try region(db).ignoring(views) - } - self.makeReducer = reducer - } + public var scheduling: ValueScheduling } extension ValueObservation where Reducer: ValueReducer { @@ -208,7 +196,7 @@ extension ValueObservation where Reducer: ValueReducer { { return reader.add(observation: self, onError: onError, onChange: onChange) } - + // MARK: - Fetching Values /// Returns the observed value. @@ -239,7 +227,7 @@ private class ErrorCatcher { var error: Error? } -extension ValueObservation { +extension ValueObservation where Reducer: ValueReducer { // MARK: - Creating ValueObservation from ValueReducer @@ -323,8 +311,11 @@ extension ValueObservation { -> ValueObservation { return ValueObservation( - tracking: DatabaseRegion.union(regions), - reducer: reducer) + baseRegion: DatabaseRegion.union(regions), + observesSelectedRegion: false, + makeReducer: reducer, + requiresWriteAccess: false, + scheduling: .mainQueue) } } @@ -332,6 +323,41 @@ extension ValueObservation where Reducer == Void { // MARK: - Creating ValueObservation from Fetch Closures + /// Creates a ValueObservation which notifies the values returned by the + /// *fetch* closure whenever a database transaction changes them. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// 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 value: A closure that fetches a value. + public static func tracking( + value: @escaping (Database) throws -> Value) + -> ValueObservation> + { + return ValueObservation>( + baseRegion: { _ in DatabaseRegion() }, + observesSelectedRegion: true, + makeReducer: { _ in ValueReducers.Fetch(value) }, + requiresWriteAccess: false, + scheduling: .mainQueue) + } + /// Creates a ValueObservation which observes *regions*, and notifies the /// values returned by the *fetch* closure whenever one of the observed /// regions is modified by a database transaction. @@ -396,7 +422,10 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation>( - tracking: DatabaseRegion.union(regions), - reducer: { _ in ValueReducers.Fetch(fetch) }) + baseRegion: DatabaseRegion.union(regions), + observesSelectedRegion: false, + makeReducer: { _ in ValueReducers.Fetch(fetch) }, + requiresWriteAccess: false, + scheduling: .mainQueue) } } diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 99754cb22..c7852174f 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -3,14 +3,21 @@ import Foundation /// Support for ValueObservation. /// See DatabaseWriter.add(observation:onError:onChange:) class ValueObserver: TransactionObserver { - // Region, reducer, and notificationQueue must be set before observer is + // Reducer and notificationQueue must be set before observer is // added to a database. - var region: DatabaseRegion! var reducer: Reducer! var notificationQueue: DispatchQueue? - + + var baseRegion = DatabaseRegion() { + didSet { observedRegion = baseRegion.union(selectedRegion) } + } + var selectedRegion = DatabaseRegion() { + didSet { observedRegion = baseRegion.union(selectedRegion) } + } + var observedRegion: DatabaseRegion! // internal for testability private var requiresWriteAccess: Bool - unowned private var writer: DatabaseWriter + private var observesSelectedRegion: Bool + private unowned var writer: DatabaseWriter private let reduceQueue: DispatchQueue private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void @@ -19,6 +26,7 @@ class ValueObserver: TransactionObserver { init( requiresWriteAccess: Bool, + observesSelectedRegion: Bool, writer: DatabaseWriter, reduceQueue: DispatchQueue, onError: @escaping (Error) -> Void, @@ -26,6 +34,7 @@ class ValueObserver: TransactionObserver { { self.writer = writer self.requiresWriteAccess = requiresWriteAccess + self.observesSelectedRegion = observesSelectedRegion self.reduceQueue = reduceQueue self.onError = onError self.onChange = onChange @@ -37,12 +46,12 @@ class ValueObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { if isCancelled { return false } - return region.isModified(byEventsOfKind: eventKind) + return observedRegion.isModified(byEventsOfKind: eventKind) } func databaseDidChange(with event: DatabaseEvent) { if isCancelled { return } - if region.isModified(by: event) { + if observedRegion.isModified(by: event) { isChanged = true stopObservingDatabaseChangesUntilNextTransaction() } @@ -54,7 +63,56 @@ class ValueObserver: TransactionObserver { isChanged = false // Grab future fetched value - let future = reducer.fetchFuture(db, writer: writer, requiringWriteAccess: requiresWriteAccess) + let future: DatabaseFuture + if requiresWriteAccess { + // Synchronous read/write fetch + if observesSelectedRegion { + do { + var fetchedValue: Reducer.Fetched! + var selectedRegion: DatabaseRegion! + try db.inTransaction { + let (_fetchedValue, _selectedRegion) = try db.recordingSelectedRegion { + try reducer.fetch(db) + } + fetchedValue = _fetchedValue + selectedRegion = _selectedRegion + return .commit + } + self.selectedRegion = selectedRegion + future = DatabaseFuture(DatabaseResult.success(fetchedValue)) + } catch { + future = DatabaseFuture(DatabaseResult.failure(error)) + } + } else { + // Synchronous read/write fetch + future = DatabaseFuture(DatabaseResult { + var fetchedValue: Reducer.Fetched! + try db.inTransaction { + fetchedValue = try reducer.fetch(db) + return .commit + } + return fetchedValue + }) + } + } else { + if observesSelectedRegion { + // Synchronous read-only fetch + do { + let (fetchedValue, selectedRegion) = try db.readOnly { + try db.recordingSelectedRegion { + try reducer.fetch(db) + } + } + self.selectedRegion = selectedRegion + future = DatabaseFuture(DatabaseResult.success(fetchedValue)) + } catch { + future = DatabaseFuture(DatabaseResult.failure(error)) + } + } else { + // Concurrent fetch + future = writer.concurrentRead(reducer.fetch) + } + } // Wait for future fetched value in reduceQueue. This guarantees: // - that notifications have the same ordering as transactions. diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index 178cc06fb..d15cd102f 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -23,7 +23,7 @@ extension ValueReducers { r2.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) defer { @@ -51,12 +51,17 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0)) }, - reducer: { try ValueReducers.Combine2( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine2( o1.makeReducer($0), - o2.makeReducer($0)) }) + o2.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -102,7 +107,7 @@ extension ValueReducers { r3.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -135,14 +140,21 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0)) }, - reducer: { try ValueReducers.Combine3( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine3( o1.makeReducer($0), o2.makeReducer($0), - o3.makeReducer($0)) }) + o3.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -200,7 +212,7 @@ extension ValueReducers { r4.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -238,16 +250,25 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0)) }, - reducer: { try ValueReducers.Combine4( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine4( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), - o4.makeReducer($0)) }) + o4.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -313,7 +334,7 @@ extension ValueReducers { r5.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -356,18 +377,29 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0)) }, - reducer: { try ValueReducers.Combine5( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine5( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), o4.makeReducer($0), - o5.makeReducer($0)) }) + o5.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -441,7 +473,7 @@ extension ValueReducers { r6.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -489,20 +521,33 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0), - o6.observedRegion($0)) }, - reducer: { try ValueReducers.Combine6( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0), + o6.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion + || o6.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine6( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), o4.makeReducer($0), o5.makeReducer($0), - o6.makeReducer($0)) }) + o6.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess + || o6.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -556,7 +601,7 @@ extension ValueReducers { r7.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -609,22 +654,37 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0), - o6.observedRegion($0), - o7.observedRegion($0)) }, - reducer: { try ValueReducers.Combine7( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0), + o6.baseRegion($0), + o7.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion + || o6.observesSelectedRegion + || o7.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine7( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), o4.makeReducer($0), o5.makeReducer($0), o6.makeReducer($0), - o7.makeReducer($0)) }) + o7.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess + || o6.requiresWriteAccess + || o7.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -641,6 +701,7 @@ extension ValueReducers { R7: ValueReducer, R8: ValueReducer>: ValueReducer { + // swiftlint:disable:next line_length public typealias Fetched = (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched, R6.Fetched, R7.Fetched, R8.Fetched) public typealias Value = (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value, R6.Value, R7.Value, R8.Value) var r1: R1 @@ -683,7 +744,7 @@ extension ValueReducers { r8.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -741,16 +802,24 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0), - o6.observedRegion($0), - o7.observedRegion($0), - o8.observedRegion($0)) }, - reducer: { try ValueReducers.Combine8( + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0), + o6.baseRegion($0), + o7.baseRegion($0), + o8.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion + || o6.observesSelectedRegion + || o7.observesSelectedRegion + || o8.observesSelectedRegion, + makeReducer: { try ValueReducers.Combine8( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), @@ -758,6 +827,15 @@ extension ValueObservation where Reducer == Void { o5.makeReducer($0), o6.makeReducer($0), o7.makeReducer($0), - o8.makeReducer($0)) }) + o8.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess + || o6.requiresWriteAccess + || o7.requiresWriteAccess + || o8.requiresWriteAccess, + scheduling: .mainQueue) } } diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 0aec4ceff..fbffa9efa 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -66,4 +66,5 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.RemoveDuplicates") -public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates where Base: ValueReducer, Base.Value: Equatable +public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates + where Base: ValueReducer, Base.Value: Equatable diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index f77027198..198a9b611 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -34,25 +34,6 @@ extension ValueReducer { } } } - - /// Synchronous or asynchronous fetch - /// Support for ValueObserver - func fetchFuture(_ db: Database, writer: DatabaseWriter, requiringWriteAccess: Bool) -> DatabaseFuture { - if requiringWriteAccess { - // Synchronous fetch - return DatabaseFuture(DatabaseResult { - var fetchedValue: Fetched! - try db.inTransaction { - fetchedValue = try fetch(db) - return .commit - } - return fetchedValue - }) - } else { - // Concurrent fetch - return writer.concurrentRead(fetch) - } - } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ec118c411..a25ad20d2 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -303,6 +303,8 @@ 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBAB22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -886,6 +888,7 @@ 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; + 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -1108,9 +1111,9 @@ 5605F1501C672E4000235C62 /* NSNull.swift */, 5605F1511C672E4000235C62 /* NSNumber.swift */, 5605F1521C672E4000235C62 /* NSString.swift */, + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, - 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -1312,6 +1315,7 @@ 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, + 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */, 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */, ); @@ -1877,6 +1881,7 @@ F3BA7FFA1CFB25E4003DC1BA /* Frameworks */, F3BA7FFB1CFB25E4003DC1BA /* Headers */, F3BA7FFC1CFB25E4003DC1BA /* Resources */, + 56EB54FD22C9119B00850069 /* Swiftlint */, ); buildRules = ( ); @@ -1915,6 +1920,7 @@ F3BA80561CFB2BB2003DC1BA /* Frameworks */, F3BA80571CFB2BB2003DC1BA /* Headers */, F3BA80581CFB2BB2003DC1BA /* Resources */, + 56EB54FB22C9118600850069 /* Swiftlint */, ); buildRules = ( ); @@ -1951,16 +1957,16 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 1020; + LastUpgradeCheck = 1030; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { F3BA7FFD1CFB25E4003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0830; + LastSwiftMigration = 1020; }; F3BA80401CFB2AD7003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0800; + LastSwiftMigration = 1020; }; F3BA80591CFB2BB2003DC1BA = { CreatedOnToolsVersion = 7.3.1; @@ -2045,6 +2051,42 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 56EB54FB22C9118600850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; + 56EB54FD22C9119B00850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -2378,6 +2420,7 @@ 56DF0018228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */, 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, + 5676FBAB22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, 569BBA2C228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, @@ -2709,6 +2752,7 @@ 56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, + 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme index 4682c9c62..fb8c9c1a0 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme @@ -1,6 +1,6 @@ Be notified of database changes ```swift -let request = Place.order(Column("title")) -request.observationForAll().start( +let observation = ValueObservation.tracking { db in + try Place.fetchAll(db) +} +observation.start( in: dbQueue, onError: { error in print("fresh places could not be fetched") @@ -254,7 +256,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -324,10 +326,10 @@ See [Enabling FTS5 Support](#enabling-fts5-support) for the installation procedu [CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. To use GRDB with CocoaPods (version 1.2 or higher), specify in your `Podfile`: ```ruby -use_frameworks! pod 'GRDB.swift' ``` +GRDB can be installed as a framework, or a static library. ## Swift Package Manager @@ -336,7 +338,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di ```swift let package = Package( dependencies: [ - .package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.1.1")) + .package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.2.0")) ] ) ``` @@ -351,7 +353,7 @@ Note that Linux is not currently supported. ## Manually -1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.1.1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.1.1` command. +1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.2.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.2.0` command. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -466,7 +468,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) for more details. ## Database Pools @@ -547,7 +549,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -607,7 +609,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. In Swift 5, you can embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -808,7 +810,7 @@ Both arrays and cursors can iterate over database results. How do you choose one - **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays. -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.1/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.2/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -890,7 +892,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1173,7 +1175,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1580,7 +1582,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1694,7 +1696,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1953,7 +1955,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.1/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. +Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.2/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support). @@ -2099,8 +2101,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) - `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup) - `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values) -- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) -- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/4.1/Classes/Database.html) +- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) +- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/4.2/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) - `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController] - `sqlite3_config`: see [Error Log](#error-log) @@ -2111,9 +2113,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates) - `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - `sqlite3_set_authorizer`: **reserved by GRDB** -- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/4.1/Classes/Statement.html) -- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) -- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/4.1/Classes/DatabasePool.html) +- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/4.2/Classes/Statement.html) +- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) +- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/4.2/Classes/DatabasePool.html) Records @@ -2432,7 +2434,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place] try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -2810,7 +2812,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.1/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.1/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.1/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.2/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. > :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). @@ -2890,44 +2892,7 @@ extension Player: FetchableRecord, PersistableRecord { } ``` -Those columns let you build requests with the [query interface](#the-query-interface): - -```swift -extension Player { - static func filter(name: String) -> QueryInterfaceRequest { - return filter(Columns.name == name) - } - - static var maximumScore: QueryInterfaceRequest { - return select(max(Columns.score), as: Int.self) - } -} -``` - -Those requests can both fetch... - -```swift -// Fetch values -try dbQueue.read { db in - // SELECT * FROM player WHERE name = 'Arthur' - let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player? - - // SELECT MAX(score) FROM player - let maxScore = try Player.maximumScore.fetchOne(db) // Int? -} -``` - -... and feed database observation tools such as [ValueObservation]: - -```swift -// Observe changes -Player.maximumScore.observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (maxScore: Int?) in - print("The maximum score has changed") - }) -``` +See the [query interface](#the-query-interface) and [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) for further information. ## Record Class @@ -4190,7 +4155,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4275,7 +4240,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift // SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet - Planet.select((temperatureColumn * 1.8 + 32).aliased("farenheit")) + Planet.select((temperatureColumn * 1.8 + 32).forKey("farenheit")) ``` > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. @@ -4475,29 +4440,9 @@ let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -When you also want to use database observation tools such as [ValueObservation], you have to go one step further, and change the type of the request: +You can also change the request so that it knows the type it has to fetch: -- When you change the selection, prefer the `select(..., as:)` method: - - ```swift - // A request of Int - let request = Player.select(max(scoreColumn), as: Int.self) - - // Simple fetch - let maxScore = try dbQueue.read { db in - try request.fetchOne(db) // Int? - } - - // Observe with ValueObservation - request.observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (maxScore: Int?) in - print("The maximum score has changed") - }) - ``` - -- Otherwise, use `asRequest(of:)`. Here is an example that uses [Associations]: +- With `asRequest(of:)`, useful when you use [Associations]: ```swift struct BookInfo: FetchableRecord, Decodable { @@ -4510,18 +4455,20 @@ When you also want to use database observation tools such as [ValueObservation], .including(required: Book.author) .asRequest(of: BookInfo.self) - // Simple fetch let bookInfos = try dbQueue.read { db in try request.fetchAll(db) // [BookInfo] } + ``` - // Observe with ValueObservation - request.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (bookInfos: [BookInfo]) in - print("Books have changed") - }) +- With `select(..., as:)`, which is handy when you change the selection: + + ```swift + // A request of Int + let request = Player.select(max(scoreColumn), as: Int.self) + + let maxScore = try dbQueue.read { db in + try request.fetchOne(db) // Int? + } ``` @@ -4588,17 +4535,6 @@ let request = Player.filter(key: ["email": "arthur@example.com"]) let player = try request.fetchOne(db) // Player? ``` -Those requests can feed [ValueObservation]: - -```swift -Player.filter(key: 1).observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (player: Player?) in - print("Player 1 has changed") - }) -``` - ## Fetching Aggregated Values @@ -4709,17 +4645,6 @@ But you may prefer to bring some elegance back in, and build custom requests: try Player.customRequest().fetchAll(db) // [Player] ``` -Custom requests can also feed [ValueObservation]: - -```swift -Player.customRequest(...).observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (players: [Player]) in - print("Players have changed") - }) -``` - - [FetchRequest Protocol](#fetchrequest-protocol) - [Building Custom Requests](#building-custom-requests) - [Fetching From Custom Requests](#fetching-from-custom-requests) @@ -4763,7 +4688,7 @@ let request = Player.all() **To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol. -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.1/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.2/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4807,7 +4732,7 @@ let request = Player.all() - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.1/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.2/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests @@ -5237,7 +5162,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -5486,7 +5411,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -6129,7 +6054,9 @@ let request = Player.all() [ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): ```swift -let observation = request.observationForAll() +let observation = ValueObservation.tracking { db in + try request.fetchAll(db) +} let observer = observation.start( in: dbQueue, onError: { error in @@ -6172,8 +6099,9 @@ Changes are only notified after they have been committed in the database. No ins - **[ValueObservation Usage](#valueobservation-usage)** -- [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) +- [ValueObservation.tracking(value:)](#valueobservationtrackingvalue) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) +- [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) - [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ... - [ValueObservation Error Handling](#valueobservation-error-handling) - [ValueObservation Options](#valueobservation-options) @@ -6193,8 +6121,9 @@ class PlayerViewController: UIViewController { super.viewWillAppear(animated) // Define a ValueObservation which tracks a player - let request = Player.filter(key: 42) - let observation = request.observationForFirst() + let observation = ValueObservation.tracking { db in + try Player.fetchOne(db, key: 42) + } // Start observing the database observer = observation.start( @@ -6202,8 +6131,9 @@ class PlayerViewController: UIViewController { onError: { error in print("player could not be fetched") }, - onChange: { [unowned self] (player: Player?) in + onChange: { [weak self] (player: Player?) in // Player has been refreshed: update view + guard let self = self else { return } self.nameLabel.text = player?.name }) } @@ -6232,8 +6162,9 @@ The observer returned by the `start` method is stored in a property of the view > super.viewWillAppear(animated) > > // Define a ValueObservation which tracks a player -> let request = Player.filter(key: 42) -> var observation = request.observationForFirst() +> let observation = ValueObservation.tracking { db in +> try Player.fetchOne(db, key: 42) +> } > > // Observation is asynchronous > observation.scheduling = .async(onQueue: .main, startImmediately: true) @@ -6244,8 +6175,9 @@ The observer returned by the `start` method is stored in a property of the view > onError: { error in > print("player could not be fetched") > }, -> onChange: { [unowned self] (player: Player?) in +> onChange: { [weak self] (player: Player?) in > // Player has been refreshed: update view +> guard let self = self else { return } > self.activityIndicator.stopAnimating() > self.nameLabel.text = player?.name > }) @@ -6258,87 +6190,76 @@ The observer returned by the `start` method is stored in a property of the view > > See [ValueObservation.scheduling](#valueobservationscheduling) for more information. -### observationForCount, observationForAll, observationForFirst -Given a [request](#requests), you can observe its number of results, all results, or the first one: +### ValueObservation.tracking(value:) + +In order to observe database values, you will generally define a **ValueObservation** which tracks the value you are interested in, and then start the observation. + +For example: ```swift -request.observationForCount() -request.observationForAll() -request.observationForFirst() +// Track changes in a single player +let observation = ValueObservation.tracking { db in + try Player.fetchOne(db, key: 42) +} + +observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { (player: Player?) in + print("Fresh player: \(player)") + }) ``` -Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request methods: +**You can observe several requests and several tables if you need**: all writes that have an impact on the fetched values will trigger the observation, and call the `onChange` function. -- `observationForCount()` notifies counts: +**It may happen that such an observation notifies identical consecutive values.** This is because it will fetch a fresh value whenever a change *could* happen. For example, the observation for the maximum player score will notify a fresh value everytime a score is changed, inserted, or deleted, even if the maximum score is unchanged: - ```swift - // Observe number of players - let observer = Player.observationForCount().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (count: Int) in - print("Number of players have changed: \(count)") - }) - ``` +```swift +// Track changes in the maximum player score +// This observation may notify duplicate values +let observation = ValueObservation.tracking { db in + try Player.select(max(Column("score")), as: Int.self).fetchOne(db) +} +``` -- `observationForAll()` notifies arrays: - - ```swift - // Observe all players - let observer = Player.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (players: [Player]) in - print("Players have changed: \(players)") - }) - - // Observe all player names - let request = SQLRequest(sql: "SELECT name FROM player") - let observer = request.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (names: [String]) in - print("Player names have changed: \(names)") - }) - ``` - -- `observationForFirst()` notifies optional values, built from a single database row (if any): - - ```swift - // Observe a single player - let observer = Player.filter(key: 1).observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (player: Player?) in - print("Player has changed: \(player)") - }) +You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: - // Observe the maximum score - let request = Player.select(max(Column("score")), as: Int.self) - let observer = request.observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (maximumScore: Int?) in - print("Maximum score has changed: \(maximumScore)") - }) - ``` +```swift +let observation = ValueObservation + .tracking { db in + try Player.select(max(Column("score")), as: Int.self).fetchOne(db) + } + .removeDuplicates() +``` -> :point_up: **Note**: observations returned by those methods perform a filtering of consecutive identical values, based on raw database values. + +We will see below other ways to define observations. They all add a little convenience, or optimization. ### ValueObservation.tracking(_:fetch:) -Observing the database is not always easy to express with simple requests, as above. +The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue) method seen above. -For example, let's say that we have a struct that defines a "Hall of Fame": +The returned observation ouputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied. + +It accepts two arguments: + +1. A list of observed requests. +2. A closure that fetches a fresh value whenever one of the observed requests are modified. + +Changes that happen outside of the observed requests are ignored, so make sure you fully cover the database region you want to observe. This is the price you pay for the optimization. + +Let's give a practical example, and observe the "Hall of Fame": ```swift struct HallOfFame { var totalPlayerCount: Int var bestPlayers: [Player] +} - /// Fetch a HallOfFame +extension HallOfFame { + /// Fetch the HallOfFame static fetch(_ db: Database) throws -> HallOfFame { let totalPlayerCount = try Player.fetchCount(db) let bestPlayers = try Player @@ -6350,128 +6271,42 @@ struct HallOfFame { bestPlayers: bestPlayers) } } - -let hallOfFame = try dbQueue.read { db in try HallOfFame.fetch(db) } -print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) ``` -In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(_:fetch:)` method. It accepts two parameters: - -1. A list of observed requests. -2. A closure that fetches a fresh value whenever one of the observed requests are modified. - -In our case, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: +In order to track changes in the Hall of Fame in an optimized way, we see that any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: ```swift let observation = ValueObservation.tracking(Player.all(), fetch: { db in try HallOfFame.fetch(db) }) - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange:{ (hallOfFame: HallOfFame) in - print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) - }) ``` +> :point_up: **Note**: the initial parameter of `ValueObservation.tracking(_:fetch:)` can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. -#### Filtering out Consecutive Identical Values -It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players. +### observationForCount, observationForAll, observationForFirst -When such a database change happens, `ValueObservation.tracking(_:fetch:)` is triggered, just in case the best players would be modified, and ends up notifying identical consecutive values. - -You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: +Given a [request](#requests), even a [custom request](#custom-requests), you can observe its number of results, all results, or the first one: ```swift -extension HallOfFame: Equatable { ... } - -let observation = ValueObservation - .tracking(Player.all(), fetch: HallOfFame.fetch) - .removeDuplicates() - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (hallOfFame: HallOfFame) in - print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) - }) +request.observationForCount() +request.observationForAll() +request.observationForFirst() ``` - -#### DatabaseRegionConvertible Observation - -The initial parameter of the `ValueObservation.tracking(_:fetch:)` method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. - -Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed. +Those observations are equivalent to the following ones, defined with [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue): ```swift -/// A team and its players -struct TeamInfo { - var team: Team - var players: [Player] -} - -/// A request that can fetch TeamInfo, given a team id. -struct TeamInfoRequest { - var teamId: Int64 - - /// The request for the team - private var teamRequest: QueryInterfaceRequest { - return Team.filter(key: teamId) - } - - /// The request for the players - private var playersRequest: QueryInterfaceRequest { - return Player.filter(Column("teamId") == teamId) - } - - /// Fetch a TeamInfo - func fetch(_ db: Database) throws -> TeamInfo? { - guard let team = try teamRequest.fetchOne(db) else { - return nil - } - let players = try playersRequest.fetchAll(db) - return TeamInfo(team: team, players: players) - } -} - -/// Make TeamInfoRequest observable -extension TeamInfoRequest: DatabaseRegionConvertible { - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - // Returns the union of the team region and the players region - let teamRegion = try teamRequest.databaseRegion(db) - let playersRegion = try playersRequest.databaseRegion(db) - return teamRegion.union(playersRegion) - } -} - -let request = TeamInfoRequest(teamId: 1) - -// Simple fetch -let teamInfo: TeamInfo? = try dbQueue.read(request.fetch) - -// Observation -let observer = ValueObservation - .tracking(request, fetch: request.fetch) - .start( - in: dbQueue, - onError: { error in ... }, - onChange: { (teamInfo: TeamInfo?) in - print("Team and its players have hanged.") - }) +ValueObservation.tracking { db in try request.fetchCount(db) } +ValueObservation.tracking { db in try request.fetchAll(db) } +ValueObservation.tracking { db in try request.fetchOne(db) } ``` +Yet they are **optimized**: + +- They perform a filtering of consecutive identical values, based on raw database values, so that you are not notified of database changes that do not impact the result of the request. +- They can perform better when you use a [database pool](#database-pools), and the fetch is slow. + ### ValueObservation Transformations @@ -6489,7 +6324,8 @@ For example: ```swift // Observe a player's profile image -let observation = Player.filter(key: 42).observationForFirst() +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } .map { player in player?.image } let observer = observation.start( @@ -6511,7 +6347,8 @@ For example: ```swift // Observe a player -let observation = Player.filter(key: 42).observationForFirst() +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } .compactMap { $0 } let observer = observation.start( @@ -6532,19 +6369,15 @@ The `removeDuplicates` method filters out the consecutive equal values notified For example: ```swift -let observation = Player.filter(key: 42).observationForFirst() - .map { player in player != nil } // existence test +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } .removeDuplicates() let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (exists: Bool) in - if exists { - print("Player 42 exists.") - } else { - print("Player 42 does not exist.") - } + onChange: { (player: Player) in + print("Player: \(player)") }) ``` @@ -6553,45 +6386,47 @@ let observer = observation.start( #### ValueObservation.combine(...) -Sometimes you need to observe several requests at the same time. - -When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: +The `ValueObservation.combine(...)` method builds a single observation from several: ```swift -struct HallOfFame { - /// Total number of players - var playerCount: Int - - /// The best ones - var bestPlayers: [Player] +// Two base observations +let playerCountObservation = ValueObservation.tracking { db in + try Player.fetchCount(db) +} +let bestPlayersObservation = ValueObservation.tracking { db in + try Player + .limit(10) + .order(Column("score").desc) + .fetchAll(db) } -// The two base observations -let playerCountObservation = Player.observationForCount() -let bestPlayersObservation = Player - .limit(10) - .order(Column("score").desc) - .observationForAll() - // The combined observation -let observation = ValueObservation - .combine(playerCountObservation, bestPlayersObservation) - .map { HallOfFame(playerCount: $0, bestPlayers: $1) } - +let observation = ValueObservation.combine( + playerCountObservation, + bestPlayersObservation) + // Start tracking the hall of fame let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (hallOfFame: HallOfFame) in - print("The hall of fame has changed.") + onChange: { (totalPlayerCount, bestPlayers) in + print(""" + Best players out of \(totalPlayerCount): + \(bestPlayers) + """) }) ``` `combine` also exists as an instance method: ```swift +struct HallOfFame { + var totalPlayerCount: Int + var bestPlayers: [Player] +} + let observation = playerCountObservation.combine(bestPlayersObservation) { - HallOfFame(playerCount: $0, bestPlayers: $1) + HallOfFame(totalPlayerCount: $0, bestPlayers: $1) } ``` @@ -6649,36 +6484,34 @@ The `scheduling` property lets you control how fresh values are notified: ```swift // On main queue - let observer = Player.observationForAll().start( + let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in + onChange: { value in // On main queue - print("fresh players: \(players)") + print("fresh value: \(value)") }) - // <- here "fresh players" is already printed. + // <- Here "fresh value" is already printed. ``` If the observation does not start on the main queue, an initial value is also notified on the main queue, but asynchronously: ```swift // Not on the main queue - let observer = Player.observationForAll().start( + let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in + onChange: { value in // On main queue - print("fresh players: \(players)") + print("fresh value: \(value)") }) ``` - When the database changes, fresh values are asynchronously notified: + After the initial value has been notified, all subsequent values are notified asynchronously: ```swift - // Eventually prints "fresh players" on the main queue - try dbQueue.write { db in - try Player(...).insert(db) - } + try dbQueue.write { db in ... } + // <- Eventually prints "fresh value" on the main queue ``` - `.async(onQueue:startImmediately:)`: all values are asychronously notified on the specified queue. @@ -6689,16 +6522,16 @@ The `scheduling` property lets you control how fresh values are notified: ```swift // On main queue - var observation = Player.observationForAll() + var observation = ... observation.scheduling = .async(onQueue: .main, startImmediately: true) let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in + onChange: { value in // On main queue - print("fresh players: \(players)")s + print("fresh value: \(value)") }) - // <- here "fresh players" is not printed yet. + // <- Eventually prints "fresh value" ``` - `unsafe(startImmediately:)`: values are not all notified on the same dispatch queue. @@ -6707,18 +6540,18 @@ The `scheduling` property lets you control how fresh values are notified: ```swift // On any queue - var observation = Player.observationForAll() + var observation = ... observation.scheduling = .unsafe(startImmediately: true) let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in - print("fresh players: \(players)") + onChange: { value in + print("fresh value: \(value)") }) - // <- here "fresh players" is already printed. + // <- Here "fresh value" is already printed. ``` - When the database changes, other values are notified on unspecified queues. + After the initial value has been notified, all subsequent values are notified on unspecified queues. > :point_up: **Note**: this unsafe mode is intended for third-party libraries that provide their own scheduling engine. @@ -6728,9 +6561,10 @@ The `scheduling` property lets you control how fresh values are notified: The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): ```swift -var observation = ValueObservation.tracking(..., fetch: { db in +var observation = ValueObservation.tracking { db in // write access allowed -}) + ... +} observation.requiresWriteAccess = true ``` @@ -7461,7 +7295,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.1/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.2/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. @@ -7471,7 +7305,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.1/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.2/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7486,7 +7320,7 @@ protocol DatabaseRegionConvertible { All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. -Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from observation APIs. See [DatabaseRegionConvertible Observation](#databaseregionconvertible-observation) for more information. +Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from optimized observation APIs. See [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) for more information. ### Support for SQLite Pre-Update Hooks @@ -8336,7 +8170,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.1/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.2/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: @@ -8590,7 +8424,7 @@ If you absolutely need multiple connections, then: - Read about [isolation in SQLite](https://www.sqlite.org/isolation.html) - Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html) - Become a master of the [WAL mode](https://www.sqlite.org/wal.html) -- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) +- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) - [Ask questions](https://github.com/groue/GRDB.swift/issues) @@ -9039,7 +8873,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@gusrota](https://github.com/gusrota), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@gusrota](https://github.com/gusrota), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. diff --git a/Support/Info.plist b/Support/Info.plist index 29e41ada3..33a5640f0 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.1.1 + 4.2.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index 60b4a6b87..ceca30204 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,17 @@ -- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool? +## Cleanup + - [ ] SQLCipher: sqlite3_rekey is discouraged (https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320) -- [ ] Query builder +- [ ] Write regression tests for #156 and #157 +- [ ] Fix matchingRowIds (todo: what is the problem, already?) +- [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation +- [ ] https://github.com/groue/GRDB.swift/issues/514 +- [ ] Test NOT TESTED methods + + +## Features + +- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool? +- [ ] SQL Generation - [ ] date functions - [ ] NOW/CURRENT_TIMESTAMP - [ ] ROUND() http://marc.info/?l=sqlite-users&m=130419182719263 @@ -8,65 +19,55 @@ - [ ] GLOB https://www.sqlite.org/lang_expr.html - [ ] REGEXP https://www.sqlite.org/lang_expr.html - [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html -- [ ] Write regression tests for #156 and #157 - [ ] Allow concurrent reads from a snapshot - [ ] Decode NSDecimalNumber from text database values - [ ] Check https://sqlite.org/sqlar.html -- [ ] filter(rowid:), filter(rowids:) -- [ ] Fix matchingRowIds -- [ ] Simplify Range extensions for Swift 4.1 -- [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 -- [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation -- [ ] Joins and full-text tables -- [ ] UPSERT https://www.sqlite.org/lang_UPSERT.html -- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md -- [ ] Avoid code duplication: https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 -- [ ] Allow joining methods on DerivableRequest -- [ ] DatabaseWriter.assertWriteAccess() -- [ ] Configuration.crashOnError = true -- [ ] Support for "INSERT INTO ... SELECT ...". For example: - - ```swift - // INSERT INTO rigth (id, name) SELECT id, name FROM left - let lefts = Left.select(Left.Columns.id, Left.Columns.name) - try Right.insert(lefts) - ``` -- [ ] select values from a JSON column: - - ```swift - let nesteds = try Record - .select(Column("nested"), as: Nested.self) - .fetchAll(db) - ``` -- [ ] Consider renaming dbQueue.inDatabase, dbPool.writeWithoutTransaction -> dbQueue/Pool.exclusive -- [ ] FetchedRecordsController diff algorithm: check https://github.com/RxSwiftCommunity/RxDataSources/issues/256 -- [ ] https://github.com/groue/GRDB.swift/issues/514 -- [ ] Look at the jazzy configuration of https://github.com/bignerdranch/Deferred - [ ] FTS: prefix queries -- [ ] Test NOT TESTED methods - [ ] A way to stop a ValueObservation observer without waiting for deinit -- [ ] Glossary (Database Access Methods, etc.) -- [ ] One use case for query interface updates that is uneasy to deal with raw SQL: +- [ ] More schema alterations +- [ ] Query interface updates. One use case for query interface updates that is uneasy to deal with raw SQL: - ``` + ```swift // Uneasy to do with raw SQL let players = Player.filter(...) // Returns a request that filters on column A or column B depending on the argument players.update(...) // Runs the expected UPDATE statement ``` -Swift 4.2 -- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0208-package-manager-system-library-targets.md -- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0201-package-manager-local-dependencies.md +## Unsure if necessary -Not sure - -- [ ] HiddenColumnsAdapter +- [ ] filter(rowid:), filter(rowids:) +- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md +- [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 +- [ ] Configuration.crashOnError = true +- [ ] Glossary (Database Access Methods, etc.) +- [ ] ValueObservation.flatMap. Not sure it is still useful now that we have ValueObservation.tracking(value:) +- [ ] rename fetchOne to fetchFirst. Not sure because it is a big breaking change. Not sure because ValueObservation.tracking(value:) has reduced the need for observationForFirst. - [ ] Not sure: type safety for SQL expressions - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Encode/decode nested records/arrays/dictionaries as JSON? - [ ] Cursor.underestimatedCount, which could speed up Array(cursor) and fetchAll() +- [ ] Remove prefix from association keys when association name is namespaced: https://github.com/groue/GRDB.swift/issues/584#issuecomment-517658122 + + +## Unsure how + +- [ ] Joins and full-text tables +- [ ] UPSERT https://www.sqlite.org/lang_UPSERT.html +- [ ] Support for "INSERT INTO ... SELECT ...". +- [ ] Look at the jazzy configuration of https://github.com/bignerdranch/Deferred +- [ ] Predicates, so that a filter can be evaluated both on the database, and on a record instance. + + After investigation, we can't do it reliably without knowing the collation used by a column. And SQLite does not provide this information elsewhere than in the full CREATE TABLE statement stored in sqlite_master. +- [ ] ValueObservation erasure + + ``` + // Do better than this + observation.mapReducer { _, reducer in AnyValueReducer(reducer) } + ``` + +- [ ] FetchedRecordsController diff algorithm: check https://github.com/RxSwiftCommunity/RxDataSources/issues/256 +- [ ] new.updateChanges(from: old) vs. old.updateChanges(with: { old.a = new.a }). This is confusing. - [ ] Support for OR ROLLBACK, and mismatch between the Swift depth and the SQLite depth of nested transactions/savepoint: ```swift @@ -108,13 +109,7 @@ Not sure ``` -Requires recompilation of SQLite: - -- [ ] https://www.sqlite.org/c3ref/column_database_name.html could help extracting out of a row a subrow only made of columns that come from a specific table. Requires SQLITE_ENABLE_COLUMN_METADATA which is not set on the sqlite3 lib that ships with OSX. - - - -Reading list: +## Reading list - Documentation generation: https://twitter.com/jckarter/status/987525569196650496: cmark is the implementation the Swift compiler uses for doc comments etc. - VACUUM (https://blogs.gnome.org/jnelson/) diff --git a/Tests/CocoaPods/GRDBiOS/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile similarity index 74% rename from Tests/CocoaPods/GRDBiOS/Podfile rename to Tests/CocoaPods/GRDBiOS-framework/Podfile index 7648899ac..55aeffee7 100644 --- a/Tests/CocoaPods/GRDBiOS/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -1,5 +1,5 @@ use_frameworks! - target 'iOS' platform :ios, '9.0' +supports_swift_versions '4.2' pod 'GRDB.swift', :path => '../../..' diff --git a/Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj similarity index 97% rename from Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.pbxproj rename to Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj index 05a63958b..458f4e78e 100644 --- a/Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj @@ -15,7 +15,7 @@ 567374431B4D46600089DE44 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374411B4D46600089DE44 /* Main.storyboard */; }; 567374451B4D46600089DE44 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567374441B4D46600089DE44 /* Assets.xcassets */; }; 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; }; - A1CCD2E34F7DE41D2EC4186E /* Pods_iOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C57F470F1DCB1126DFB5EB63 /* Pods_iOS.framework */; }; + 905ECD161513DA7089DC0E4F /* Pods_iOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44319992BE6EA64810E8982A /* Pods_iOS.framework */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -32,6 +32,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 44319992BE6EA64810E8982A /* Pods_iOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 5626974C2110308E0066800A /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; 5626974D2110308E0066800A /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; 5626974E2110308E0066800A /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; @@ -44,7 +45,6 @@ 567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.debug.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.debug.xcconfig"; sourceTree = ""; }; 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.release.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.release.xcconfig"; sourceTree = ""; }; - C57F470F1DCB1126DFB5EB63 /* Pods_iOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -52,7 +52,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - A1CCD2E34F7DE41D2EC4186E /* Pods_iOS.framework in Frameworks */, + 905ECD161513DA7089DC0E4F /* Pods_iOS.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -97,7 +97,7 @@ 8D9BFC4007F760CC8E01ACC6 /* Frameworks */ = { isa = PBXGroup; children = ( - C57F470F1DCB1126DFB5EB63 /* Pods_iOS.framework */, + 44319992BE6EA64810E8982A /* Pods_iOS.framework */, ); name = Frameworks; sourceTree = ""; @@ -123,7 +123,7 @@ 567374351B4D46600089DE44 /* Frameworks */, 567374361B4D46600089DE44 /* Resources */, 5644E4071C1072CA0090716E /* Embed Frameworks */, - CED3A5EE3229C5F98D69D6AF /* [CP] Embed Pods Frameworks */, + 42992B3BE6585CF939B0D8EF /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -183,6 +183,24 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 42992B3BE6585CF939B0D8EF /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/GRDB.swift/GRDB.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GRDB.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; C5E9DF0928754FE22F481D3A /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -201,24 +219,6 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - CED3A5EE3229C5F98D69D6AF /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/GRDB.swift/GRDB.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GRDB.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/Tests/CocoaPods/GRDBiOS/iOS.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Tests/CocoaPods/GRDBiOS/iOS.xcworkspace/contents.xcworkspacedata rename to Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/contents.xcworkspacedata diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile new file mode 100644 index 000000000..c20cb2f16 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -0,0 +1,4 @@ +target 'iOS' +platform :ios, '9.0' +supports_swift_versions '4.2' +pod 'GRDB.swift', :path => '../../..' diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj new file mode 100644 index 000000000..a4c9947c5 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj @@ -0,0 +1,401 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 562697512110308F0066800A /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974C2110308E0066800A /* PlayersViewController.swift */; }; + 562697522110308F0066800A /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974D2110308E0066800A /* Player.swift */; }; + 562697532110308F0066800A /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974E2110308E0066800A /* PlayerEditionViewController.swift */; }; + 562697542110308F0066800A /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974F2110308E0066800A /* AppDatabase.swift */; }; + 562697552110308F0066800A /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562697502110308E0066800A /* AppDelegate.swift */; }; + 567374431B4D46600089DE44 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374411B4D46600089DE44 /* Main.storyboard */; }; + 567374451B4D46600089DE44 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567374441B4D46600089DE44 /* Assets.xcassets */; }; + 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; }; + D246CFB4904D46E7D400E2CE /* libPods-iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9E46153E91609427B4025BC7 /* libPods-iOS.a */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 5644E4071C1072CA0090716E /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 5626974C2110308E0066800A /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; + 5626974D2110308E0066800A /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; + 5626974E2110308E0066800A /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; + 5626974F2110308E0066800A /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; + 562697502110308E0066800A /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 567374381B4D46600089DE44 /* iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 567374421B4D46600089DE44 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 567374441B4D46600089DE44 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 567374471B4D46600089DE44 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.debug.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.debug.xcconfig"; sourceTree = ""; }; + 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.release.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.release.xcconfig"; sourceTree = ""; }; + 9E46153E91609427B4025BC7 /* libPods-iOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-iOS.a"; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 567374351B4D46600089DE44 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D246CFB4904D46E7D400E2CE /* libPods-iOS.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 5673742F1B4D46600089DE44 = { + isa = PBXGroup; + children = ( + 5673743A1B4D46600089DE44 /* GRDBDemoiOS */, + 567374391B4D46600089DE44 /* Products */, + 9ABB37395508D35C98A292E7 /* Pods */, + 8D9BFC4007F760CC8E01ACC6 /* Frameworks */, + ); + sourceTree = ""; + }; + 567374391B4D46600089DE44 /* Products */ = { + isa = PBXGroup; + children = ( + 567374381B4D46600089DE44 /* iOS.app */, + ); + name = Products; + sourceTree = ""; + }; + 5673743A1B4D46600089DE44 /* GRDBDemoiOS */ = { + isa = PBXGroup; + children = ( + 5626974F2110308E0066800A /* AppDatabase.swift */, + 562697502110308E0066800A /* AppDelegate.swift */, + 5626974D2110308E0066800A /* Player.swift */, + 5626974E2110308E0066800A /* PlayerEditionViewController.swift */, + 5626974C2110308E0066800A /* PlayersViewController.swift */, + 567374441B4D46600089DE44 /* Assets.xcassets */, + 567374491B4D46600089DE44 /* Info.plist */, + 567374461B4D46600089DE44 /* LaunchScreen.storyboard */, + 567374411B4D46600089DE44 /* Main.storyboard */, + ); + name = GRDBDemoiOS; + path = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS; + sourceTree = ""; + }; + 8D9BFC4007F760CC8E01ACC6 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 9E46153E91609427B4025BC7 /* libPods-iOS.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9ABB37395508D35C98A292E7 /* Pods */ = { + isa = PBXGroup; + children = ( + 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */, + 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 567374371B4D46600089DE44 /* iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 567374621B4D46600089DE44 /* Build configuration list for PBXNativeTarget "iOS" */; + buildPhases = ( + C5E9DF0928754FE22F481D3A /* [CP] Check Pods Manifest.lock */, + 567374341B4D46600089DE44 /* Sources */, + 567374351B4D46600089DE44 /* Frameworks */, + 567374361B4D46600089DE44 /* Resources */, + 5644E4071C1072CA0090716E /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = iOS; + productName = iOS; + productReference = 567374381B4D46600089DE44 /* iOS.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 567374301B4D46600089DE44 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0940; + ORGANIZATIONNAME = "Gwendal Roué"; + TargetAttributes = { + 567374371B4D46600089DE44 = { + CreatedOnToolsVersion = 7.0; + DevelopmentTeam = AMD8W895CT; + LastSwiftMigration = 0940; + }; + }; + }; + buildConfigurationList = 567374331B4D46600089DE44 /* Build configuration list for PBXProject "iOS" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 5673742F1B4D46600089DE44; + productRefGroup = 567374391B4D46600089DE44 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 567374371B4D46600089DE44 /* iOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 567374361B4D46600089DE44 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */, + 567374451B4D46600089DE44 /* Assets.xcassets in Resources */, + 567374431B4D46600089DE44 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + C5E9DF0928754FE22F481D3A /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-iOS-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 567374341B4D46600089DE44 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 562697522110308F0066800A /* Player.swift in Sources */, + 562697532110308F0066800A /* PlayerEditionViewController.swift in Sources */, + 562697542110308F0066800A /* AppDatabase.swift in Sources */, + 562697552110308F0066800A /* AppDelegate.swift in Sources */, + 562697512110308F0066800A /* PlayersViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 567374411B4D46600089DE44 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 567374421B4D46600089DE44 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 567374461B4D46600089DE44 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 567374471B4D46600089DE44 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 567374601B4D46600089DE44 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 567374611B4D46600089DE44 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 567374631B4D46600089DE44 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + INFOPLIST_FILE = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + }; + name = Debug; + }; + 567374641B4D46600089DE44 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + INFOPLIST_FILE = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + SWIFT_VERSION = 4.2; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 567374331B4D46600089DE44 /* Build configuration list for PBXProject "iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 567374601B4D46600089DE44 /* Debug */, + 567374611B4D46600089DE44 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 567374621B4D46600089DE44 /* Build configuration list for PBXNativeTarget "iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 567374631B4D46600089DE44 /* Debug */, + 567374641B4D46600089DE44 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 567374301B4D46600089DE44 /* Project object */; +} diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..92a930669 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..7f03e784a --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index c3bfffee0..b68c3c6f9 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 51; objects = { /* Begin PBXBuildFile section */ @@ -383,13 +383,15 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 5656A802229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A803229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; + 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 569BBA31228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 569BBA32228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 56DF0027228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0028228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0029228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF002A228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; }; + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; /* End PBXBuildFile section */ @@ -589,6 +591,7 @@ 564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; + 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; @@ -603,7 +606,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -831,6 +834,7 @@ 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, + 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */, 564A1F9C226B89DA001F64F1 /* ValueObservationRowTests.swift */, 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */, 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */, @@ -1097,6 +1101,7 @@ 564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */, 564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */, @@ -1294,6 +1299,7 @@ 564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */, 564A20D3226B8E18001F64F1 /* DatabaseValueTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 83c84248a..573504ba6 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 51; objects = { /* Begin PBXBuildFile section */ @@ -385,13 +385,15 @@ 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 5656A805229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; + 5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 569BBA2E228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 569BBA2F228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 56DF0021228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF0022228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF0023228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0024228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; }; + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; /* End PBXBuildFile section */ @@ -592,6 +594,7 @@ 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; + 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; @@ -606,7 +609,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -835,6 +838,7 @@ 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, + 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */, 564A1F9C226B89DA001F64F1 /* ValueObservationRowTests.swift */, 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */, 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */, @@ -1103,6 +1107,7 @@ 564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */, 564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */, @@ -1300,6 +1305,7 @@ 564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */, 564A20D3226B8E18001F64F1 /* DatabaseValueTests.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 7ddc99b49..28123e05d 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -653,15 +653,15 @@ class AssociationAggregateTests: GRDBTestCase { } } - func testAnnotatedWithHasManyAggregateAlias() throws { + func testAnnotatedWithHasManyAggregateWithCustomKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score")).aliased("a1")) - .annotated(with: Team.players.count.aliased("a2")) - .annotated(with: Team.players.max(Column("score")).aliased("a3")) - .annotated(with: Team.players.min(Column("score")).aliased("a4")) - .annotated(with: Team.players.sum(Column("score")).aliased("a5")) + .annotated(with: Team.players.average(Column("score")).forKey("a1")) + .annotated(with: Team.players.count.forKey("a2")) + .annotated(with: Team.players.max(Column("score")).forKey("a3")) + .annotated(with: Team.players.min(Column("score")).forKey("a4")) + .annotated(with: Team.players.sum(Column("score")).forKey("a5")) try assertEqualSQL(db, request, """ SELECT "team".*, \ @@ -681,10 +681,10 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score") * Column("score")).aliased("a1")) - .annotated(with: Team.players.max(Column("score") * 10).aliased("a3")) - .annotated(with: Team.players.min(-Column("score")).aliased("a4")) - .annotated(with: Team.players.sum(Column("score") * Column("score")).aliased("a5")) + .annotated(with: Team.players.average(Column("score") * Column("score")).forKey("a1")) + .annotated(with: Team.players.max(Column("score") * 10).forKey("a3")) + .annotated(with: Team.players.min(-Column("score")).forKey("a4")) + .annotated(with: Team.players.sum(Column("score") * Column("score")).forKey("a5")) try assertEqualSQL(db, request, """ SELECT "team".*, \ AVG("player"."score" * "player"."score") AS "a1", \ diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index 747e8f80b..3b938b8cf 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -95,7 +95,7 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase { .including(required: A.b .select( Column("name"), - (Column("id") + aAlias[Column("id")]).aliased("foo"))) + (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ FROM "a" \ diff --git a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift index 8e443f23d..4c8c585bb 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift @@ -175,10 +175,10 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { ac: CAssociation, bCondition: String, cCondition: String) throws - where BAssociation: Association, + where + BAssociation: Association, CAssociation: Association, - BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder: TableRecord + BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder { let A = BAssociation.OriginRowDecoder.self diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index aae37ab09..d9e4d3d15 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -95,7 +95,7 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase { .including(required: A.b .select( Column("name"), - (Column("id") + aAlias[Column("id")]).aliased("foo"))) + (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ FROM "a" \ diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index 01303f108..f4039353e 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -107,7 +107,7 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { .including(required: A.c .select( Column("name"), - (Column("id") + aAlias[Column("id")]).aliased("foo"))) + (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "c"."name", "c"."id" + "a"."id" AS "foo" \ FROM "a" \ diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift index 52135450d..485ccc821 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift @@ -177,10 +177,10 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { ac: CAssociation, bCondition: String, cCondition: String) throws - where BAssociation: AssociationToOne, + where + BAssociation: AssociationToOne, CAssociation: AssociationToOne, - BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder: TableRecord + BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder { let A = BAssociation.OriginRowDecoder.self @@ -783,14 +783,14 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: String, cCondition: String, dCondition: String) throws - where BAssociation: AssociationToOne, + where + BAssociation: AssociationToOne, CAssociation: AssociationToOne, DCAssociation: AssociationToOne, DBAssociation: AssociationToOne, BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, BAssociation.OriginRowDecoder == DCAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder == DBAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder: TableRecord + BAssociation.OriginRowDecoder == DBAssociation.OriginRowDecoder { let A = CAssociation.OriginRowDecoder.self diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index a8a2f85f3..5d8c9ad14 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -20,7 +20,7 @@ private struct C: TableRecord, FetchableRecord, Decodable, Equatable { } private struct D: TableRecord, FetchableRecord, Decodable, Equatable { var cold1: Int64 - var cold2: Int64 + var cold2: Int64? var cold3: String } @@ -61,6 +61,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); + INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", @@ -77,6 +78,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", + 14, nil, "d5", ]) } } @@ -791,7 +793,6 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -1014,6 +1015,72 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } } + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + // Record (flat) + do { + struct Record: FetchableRecord, Decodable, Equatable { + var d: D + var bs: [B] // not optional + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + Record( + d: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 14, "cold2": nil, "cold3": "d5"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ])) + } + } + } + } + } + func testSelfJoin() throws { struct Employee: TableRecord, FetchableRecord, Decodable, Hashable { static let subordinates = hasMany(Employee.self, key: "subordinates") diff --git a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift index e7cd853b1..1b99ee0a3 100644 --- a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift @@ -36,7 +36,7 @@ private struct C: TableRecord, FetchableRecord, Equatable { } private struct D: TableRecord, FetchableRecord, Equatable { var cold1: Int64 - var cold2: Int64 + var cold2: Int64? var cold3: String init(row: Row) { @@ -83,6 +83,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); + INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", @@ -99,6 +100,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", + 14, nil, "d5", ]) } } @@ -973,7 +975,6 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -1243,4 +1244,79 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { } } } + + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + // Record (flat) + do { + struct Record: FetchableRecord, Equatable { + var d: D + var bs: [B] // not optional + + init(d: D, bs: [B]) { + self.d = d + self.bs = bs + } + + init(row: Row) { + self.init(d: D(row: row), bs: row["bs"]) + } + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + Record( + d: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 14, "cold2": nil, "cold3": "d5"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ])) + } + } + } + } + } } diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index fc37d82c3..35c8de862 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -236,7 +236,6 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -287,4 +286,25 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { } } } + + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + try XCTAssert([ + "a(*),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)", // iOS 12 + "a(cola1),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)", // iOS 9 + ].contains(request.databaseRegion(db).description)) + } + } + } } diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index 8413ce108..f3af02c95 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -47,6 +47,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase { INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); + INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", @@ -63,6 +64,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase { 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", + 14, nil, "d5", ]) } } @@ -779,7 +781,6 @@ class AssociationPrefetchingRowTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -991,6 +992,76 @@ class AssociationPrefetchingRowTests: GRDBTestCase { } } + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + // Row.fetchAll + do { + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].description, "[cold1:10 cold2:7 cold3:\"d1\"]") + XCTAssertEqual(rows[0].debugDescription, """ + ▿ [cold1:10 cold2:7 cold3:"d1"] + + bs: 2 rows + """) + + XCTAssertEqual(rows[0].unscoped, ["cold1": 10, "cold2": 7, "cold3": "d1"]) + XCTAssertEqual(rows[0].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[0].prefetchedRows["bs"]!.count, 2) + XCTAssertEqual(rows[0].prefetchedRows["bs"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colc1": 7]) + XCTAssertEqual(rows[0].prefetchedRows["bs"]![1], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colc1": 7]) + XCTAssertEqual(rows[0].scopes.count, 0) + + XCTAssertEqual(rows[1].unscoped, ["cold1": 11, "cold2": 8, "cold3": "d2"]) + XCTAssertEqual(rows[1].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[1].prefetchedRows["bs"]!.count, 1) + XCTAssertEqual(rows[1].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colc1": 8]) + XCTAssertEqual(rows[1].scopes.count, 0) + + XCTAssertEqual(rows[2].unscoped, ["cold1": 12, "cold2": 8, "cold3": "d3"]) + XCTAssertEqual(rows[2].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[2].prefetchedRows["bs"]!.count, 1) + XCTAssertEqual(rows[2].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colc1": 8]) + XCTAssertEqual(rows[2].scopes.count, 0) + + XCTAssertEqual(rows[3].unscoped, ["cold1": 13, "cold2": 9, "cold3": "d4"]) + XCTAssertEqual(rows[3].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[3].prefetchedRows["bs"]!.count, 1) + XCTAssertEqual(rows[3].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colc1": 9]) + XCTAssertEqual(rows[3].scopes.count, 0) + + XCTAssertEqual(rows[4].unscoped, ["cold1": 14, "cold2": nil, "cold3": "d5"]) + XCTAssertEqual(rows[4].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[4].prefetchedRows["bs"]!.count, 0) + XCTAssertEqual(rows[4].scopes.count, 0) + } + + // Row.fetchOne + do { + let row = try Row.fetchOne(db, request)! + + XCTAssertEqual(row.unscoped, ["cold1": 10, "cold2": 7, "cold3": "d1"]) + XCTAssertEqual(row.prefetchedRows.keys, ["bs"]) + XCTAssertEqual(row.prefetchedRows["bs"]!.count, 2) + XCTAssertEqual(row.prefetchedRows["bs"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colc1": 7]) + XCTAssertEqual(row.prefetchedRows["bs"]![1], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colc1": 7]) + XCTAssertEqual(row.scopes.count, 0) + } + } + } + } + func testEquatable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 9238115a7..8d4d38f16 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -12,6 +12,12 @@ private struct D: TableRecord { } class AssociationPrefetchingSQLTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { + // A.hasMany(B) + // A.hasMany(C) + // B.belongsTo(A) + // C.belongsTo(A) + // C.hasMany(D) + // D.belongsTo(C) try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") @@ -81,7 +87,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -106,7 +112,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\" @@ -132,7 +138,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" \ @@ -190,7 +196,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "parent" ORDER BY "parentA", "parentB" @@ -213,7 +219,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB" @@ -232,7 +238,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB" @@ -262,7 +268,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -296,7 +302,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -348,7 +354,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * \ @@ -413,7 +419,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -442,7 +448,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -495,7 +501,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * \ @@ -537,7 +543,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -573,7 +579,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" \ @@ -617,7 +623,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -652,7 +658,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -690,7 +696,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -732,7 +738,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -766,7 +772,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -806,7 +812,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -848,7 +854,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -894,7 +900,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -918,7 +924,6 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -936,7 +941,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "b".*, "a".* \ @@ -988,7 +993,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "b".*, "a1".*, "a2".* \ @@ -1028,4 +1033,508 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } } + + func testIncludingOptionalHasOneIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = A + .including(optional: A + .hasOne(C.self) + .including(all: C + .hasMany(D.self) + .orderByPrimaryKey()) + ) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "c" ON "c"."colc2" = "a"."cola1" \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2, 3)) \ + ORDER BY "d"."cold1" + """]) + } + + // Request with filters + do { + let request = A + .including(optional: A + .hasOne(C.self) + .filter(Column("colc1") == 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c1")) + .including(optional: A + .hasOne(C.self) + .filter(Column("colc1") != 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c2")) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".*, "c1".*, "c2".* \ + FROM "a" \ + LEFT JOIN "c" "c1" ON ("c1"."colc2" = "a"."cola1") AND ("c1"."colc1" = 9) \ + LEFT JOIN "c" "c2" ON ("c2"."colc2" = "a"."cola1") AND ("c2"."colc1" <> 9) \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """]) + } + } + } + + func testIncludingOptionalBelongsToIncludingOptionalBelongsToIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .including(optional: D + .belongsTo(C.self) + .including(optional: C + .belongsTo(A.self) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey()))) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".*, "c".*, "a".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } + + func testIncludingOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .including(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".*, "a".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } + + func testJoiningOptionalBelongsToIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = B + .joining(optional: B + .belongsTo(A.self) + .including(all: A + .hasMany(C.self) + .orderByPrimaryKey()) + ) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. + XCTAssertEqual(selectQueries, [ + """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON "a"."cola1" = "b"."colb2" \ + ORDER BY "b"."colb1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola1" IN (1, 2)) \ + ORDER BY "c"."colc1" + """]) + } + + // Request with filters + do { + let request = B + .joining(optional: B + .belongsTo(A.self) + .filter(Column("cola2") == "a1") + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") == 9) + .orderByPrimaryKey() + .forKey("cs1")) + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") != 9) + .orderByPrimaryKey() + .forKey("cs2")) + .forKey("a1")) + .joining(optional: B + .belongsTo(A.self) + .filter(Column("cola2") == "a2") + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") == 9) + .orderByPrimaryKey() + .forKey("cs1")) + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") != 9) + .orderByPrimaryKey() + .forKey("cs2")) + .forKey("a2")) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. + XCTAssertEqual(selectQueries, [ + """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" "a1" ON ("a1"."cola1" = "b"."colb2") AND ("a1"."cola2" = 'a1') \ + LEFT JOIN "a" "a2" ON ("a2"."cola1" = "b"."colb2") AND ("a2"."cola2" = 'a2') \ + ORDER BY "b"."colb1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" = 9 \ + ORDER BY "c"."colc1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" <> 9 \ + ORDER BY "c"."colc1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" = 9 \ + ORDER BY "c"."colc1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" <> 9 \ + ORDER BY "c"."colc1" + """]) + } + } + } + + func testJoiningOptionalHasOneIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = A + .joining(optional: A + .hasOne(C.self) + .including(all: C + .hasMany(D.self) + .orderByPrimaryKey()) + ) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "c" ON "c"."colc2" = "a"."cola1" \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2, 3)) \ + ORDER BY "d"."cold1" + """]) + } + + // Request with filters + do { + let request = A + .joining(optional: A + .hasOne(C.self) + .filter(Column("colc1") == 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c1")) + .joining(optional: A + .hasOne(C.self) + .filter(Column("colc1") != 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c2")) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "c" "c1" ON ("c1"."colc2" = "a"."cola1") AND ("c1"."colc1" = 9) \ + LEFT JOIN "c" "c2" ON ("c2"."colc2" = "a"."cola1") AND ("c2"."colc1" <> 9) \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """]) + } + } + } + + func testJoiningOptionalBelongsToJoiningOptionalBelongsToIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .belongsTo(C.self) + .joining(optional: C + .belongsTo(A.self) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey()))) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } + + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 02a2733e5..f6e82c1f4 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -70,4 +70,104 @@ class DatabaseCursorTests: GRDBTestCase { } } } + + // Regression test for http://github.com/groue/GRDB.swift/issues/583 + func testIssue583() throws { + struct User: Codable, TableRecord, FetchableRecord, MutablePersistableRecord { + static let databaseTableName: String = "user" + + var id: Int64? + var username: String + var isFlagged: Bool + + init(id: Int64? = nil, username: String, isFlagged: Bool = false) { + self.id = id + self.username = username + self.isFlagged = isFlagged + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + struct FlagUser: Codable, TableRecord, FetchableRecord, MutablePersistableRecord { + static let databaseTableName: String = "flagUser" + + var username: String + } + + let queue = try makeDatabaseQueue() + try queue.write { database in + try database.create(table: User.databaseTableName) { definition in + definition.column("id", .integer).primaryKey(autoincrement: true) + definition.column("username", .text).notNull() + definition.column("isFlagged", .boolean).notNull().defaults(to: false) + } + + try database.create(table: FlagUser.databaseTableName) { definition in + definition.column("username", .text).notNull() + } + + try [Int](0...50).forEach { + var user = User(username: "User\($0)") + try user.insert(database) + } + + try [Int](40...60).forEach { + var flag = FlagUser(username: "User\($0)") + try flag.insert(database) + } + } + + let query = "SELECT * FROM flagUser WHERE (SELECT COUNT(id) FROM user WHERE username = flagUser.username AND isFlagged = 1) = 0" + try queue.inDatabase { database in + let cursor = try FlagUser.fetchCursor(database, sql: query) + while let flagged = try cursor.next() { + _ = try User.fetchOne(database, sql: "SELECT * FROM user WHERE username = '\(flagged.username)' LIMIT 1") ?? + User(username: flagged.username) + } + } + + // For the record, the lines below show how this test used to fail, + // with raw C SQLite3 apis. The faulty line is the call to + // sqlite3_set_authorizer during the statement iteration. + +// if #available(OSX 10.14, *) { +// var connection: SQLiteConnection? = nil +// sqlite3_open_v2(":memory:", &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, nil) +// sqlite3_extended_result_codes(connection, 1) +// +// sqlite3_exec(connection, """ +// CREATE TABLE user (username TEXT NOT NULL); +// CREATE TABLE flagUser (username TEXT NOT NULL); +// INSERT INTO flagUser (username) VALUES ('User1'); +// INSERT INTO flagUser (username) VALUES ('User2'); +// """, nil, nil, nil) +// +// var statement: SQLiteStatement? = nil +// sqlite3_set_authorizer(connection, { (_, _, _, _, _, _) in SQLITE_OK }, nil) +// sqlite3_prepare_v3(connection, """ +// SELECT * FROM flagUser WHERE (SELECT COUNT(*) FROM user WHERE username = flagUser.username) = 0 +// """, -1, 0, &statement, nil) +// sqlite3_set_authorizer(connection, nil, nil) +// while true { +// let code = sqlite3_step(statement) +// if code == SQLITE_DONE { +// break +// } else if code == SQLITE_ROW { +// // part of the compilation of another statement, here +// // reduced to the strict minimum that reproduces +// // the error. +// sqlite3_set_authorizer(connection, nil, nil) +// } else { +// print(String(cString: sqlite3_errmsg(connection))) +// XCTFail("Error \(code)") +// break +// } +// } +// sqlite3_finalize(statement) +// sqlite3_close_v2(connection) +// } + } } diff --git a/Tests/GRDBTests/DatabasePoolCollationTests.swift b/Tests/GRDBTests/DatabasePoolCollationTests.swift index 5a53822b5..ce0551253 100644 --- a/Tests/GRDBTests/DatabasePoolCollationTests.swift +++ b/Tests/GRDBTests/DatabasePoolCollationTests.swift @@ -15,24 +15,50 @@ class DatabasePoolCollationTests: GRDBTestCase { } dbPool.add(collation: collation1) - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE items (text TEXT COLLATE collation1)") - try db.execute(sql: "INSERT INTO items (text) VALUES ('a')") - try db.execute(sql: "INSERT INTO items (text) VALUES ('b')") - try db.execute(sql: "INSERT INTO items (text) VALUES ('c')") - } - try dbPool.read { db in - XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["a", "b", "c"]) - XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) - } - let collation2 = DatabaseCollation("collation2") { (string1, string2) in return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedDescending : .orderedAscending) } dbPool.add(collation: collation2) + try dbPool.write { db in + // Both collations are available in writer + try db.execute(sql: """ + CREATE TABLE items (text TEXT COLLATE collation2); + INSERT INTO items (text) VALUES ('a'); + INSERT INTO items (text) VALUES ('b'); + INSERT INTO items (text) VALUES ('c'); + """) + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["c", "b", "a"]) + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) + } + try dbPool.read { db in + // Both collations are available in reader + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["c", "b", "a"]) + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation2"), ["c", "b", "a"]) } + + dbPool.remove(collation: collation1) + + do { + // collation1 is no longer available in writer + try dbPool.write { db in + _ = try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1") + } + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssert(error.message!.contains("collation1")) + } + + do { + // collation1 is no longer available in reader + try dbPool.read { db in + _ = try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1") + } + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssert(error.message!.contains("collation1")) + } } } diff --git a/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift index 5eabe8c86..76e3a1c93 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift @@ -9,27 +9,27 @@ import XCTest class DatabaseValueConvertibleEscapingTests: GRDBTestCase { func testText() { - XCTAssertEqual("".databaseValue.quotedSQL(wrappedInParenthesis: false), "''") - XCTAssertEqual("foo".databaseValue.quotedSQL(wrappedInParenthesis: false), "'foo'") - XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(wrappedInParenthesis: false), "'\"foo\"'") - XCTAssertEqual("'foo'".databaseValue.quotedSQL(wrappedInParenthesis: false), "'''foo'''") + XCTAssertEqual("".databaseValue.quotedSQL(), "''") + XCTAssertEqual("foo".databaseValue.quotedSQL(), "'foo'") + XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(), "'\"foo\"'") + XCTAssertEqual("'foo'".databaseValue.quotedSQL(), "'''foo'''") } func testInteger() { - XCTAssertEqual(0.databaseValue.quotedSQL(wrappedInParenthesis: false), "0") - XCTAssertEqual(Int64.min.databaseValue.quotedSQL(wrappedInParenthesis: false), "-9223372036854775808") - XCTAssertEqual(Int64.max.databaseValue.quotedSQL(wrappedInParenthesis: false), "9223372036854775807") + XCTAssertEqual(0.databaseValue.quotedSQL(), "0") + XCTAssertEqual(Int64.min.databaseValue.quotedSQL(), "-9223372036854775808") + XCTAssertEqual(Int64.max.databaseValue.quotedSQL(), "9223372036854775807") } func testDouble() { - XCTAssertEqual(0.0.databaseValue.quotedSQL(wrappedInParenthesis: false), "0.0") - XCTAssertEqual(1.0.databaseValue.quotedSQL(wrappedInParenthesis: false), "1.0") - XCTAssertEqual((-1.0).databaseValue.quotedSQL(wrappedInParenthesis: false), "-1.0") - XCTAssertEqual(1.5.databaseValue.quotedSQL(wrappedInParenthesis: false), "1.5") + XCTAssertEqual(0.0.databaseValue.quotedSQL(), "0.0") + XCTAssertEqual(1.0.databaseValue.quotedSQL(), "1.0") + XCTAssertEqual((-1.0).databaseValue.quotedSQL(), "-1.0") + XCTAssertEqual(1.5.databaseValue.quotedSQL(), "1.5") } func testBlob() { - XCTAssertEqual(Data().databaseValue.quotedSQL(wrappedInParenthesis: false), "X''") - XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(wrappedInParenthesis: false), "X'666F6F'") + XCTAssertEqual(Data().databaseValue.quotedSQL(), "X''") + XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(), "X'666F6F'") } } diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 9d0f991b7..bc77b5ba5 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -1,8 +1,8 @@ import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite +import GRDBCustomSQLite #else - import GRDB +import GRDB #endif private struct Author: FetchableRecord, PersistableRecord, Codable { @@ -18,10 +18,12 @@ private struct Author: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "author" static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { return request(for: Author.books) } } + private struct Book: FetchableRecord, PersistableRecord, Codable { var id: Int64 var authorId: Int64 @@ -29,11 +31,22 @@ private struct Book: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "book" static let author = belongsTo(Author.self) + static let bookFts4 = hasOne(BookFts4.self, using: ForeignKey([Column.rowID])) + #if SQLITE_ENABLE_FTS5 + static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([Column.rowID])) + #endif + var author: QueryInterfaceRequest { return request(for: Book.author) } } +private struct BookFts4: TableRecord { } + +#if SQLITE_ENABLE_FTS5 +private struct BookFts5: TableRecord { } +#endif + private var libraryMigrator: DatabaseMigrator = { var migrator = DatabaseMigrator() migrator.registerMigration("library") { db in @@ -48,6 +61,16 @@ private var libraryMigrator: DatabaseMigrator = { t.column("authorId", .integer).notNull().references("author") t.column("title", .text).notNull() } + try db.create(virtualTable: "bookFts4", using: FTS4()) { t in + t.synchronize(withTable: "book") + t.column("title") + } + #if SQLITE_ENABLE_FTS5 + try db.create(virtualTable: "bookFts5", using: FTS5()) { t in + t.synchronize(withTable: "book") + t.column("title") + } + #endif } migrator.registerMigration("fixture") { db in try Author(id: 1, firstName: "Herman", lastName: "Melville", country: "US").insert(db) @@ -88,6 +111,28 @@ extension DerivableRequest where RowDecoder == Book { func filter(authorCountry: String) -> Self { return joining(required: Book.author.filter(country: authorCountry)) } + + // TableRequest & FilteredRequest + func filter(id: Int) -> Self { + return filter(key: id) + } + + // TableRequest & FilteredRequest + func matchingFts4(_ pattern: FTS3Pattern?) -> Self { + return joining(required: Book.bookFts4.matching(pattern)) + } + + #if SQLITE_ENABLE_FTS5 + // TableRequest & FilteredRequest + func matchingFts5(_ pattern: FTS3Pattern?) -> Self { + return joining(required: Book.bookFts5.matching(pattern)) + } + #endif + + // TableRequest & OrderedRequest + func orderById() -> Self { + return orderByPrimaryKey() + } } class DerivableRequestTests: GRDBTestCase { @@ -263,4 +308,113 @@ class DerivableRequestTests: GRDBTestCase { } } } + + func testTableRequestFilteredRequest() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // filter(id:) + do { + let title = try Book.all() + .filter(id: 2) + .fetchOne(db) + .map { $0.title } + XCTAssertEqual(title, "Du côté de chez Swann") + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "book" WHERE "id" = 2 + """) + + let fullName = try Author + .joining(required: Author.books.filter(id: 2)) + .fetchOne(db) + .map { $0.fullName } + XCTAssertEqual(fullName, "Marcel Proust") + XCTAssertEqual(lastSQLQuery, """ + SELECT "author".* FROM "author" \ + JOIN "book" ON ("book"."authorId" = "author"."id") AND ("book"."id" = 2) \ + LIMIT 1 + """) + } + + // matchingFts4 + do { + sqlQueries.removeAll() + let title = try Book.all() + .matchingFts4(FTS3Pattern(rawPattern: "moby dick")) + .fetchOne(db) + .map { $0.title } + XCTAssertEqual(title, "Moby-Dick") + XCTAssert(sqlQueries.contains(""" + SELECT "book".* FROM "book" \ + JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ + LIMIT 1 + """)) + + sqlQueries.removeAll() + let fullName = try Author + .joining(required: Author.books.matchingFts4(FTS3Pattern(rawPattern: "moby dick"))) + .fetchOne(db) + .map { $0.fullName } + XCTAssertEqual(fullName, "Herman Melville") + XCTAssert(sqlQueries.contains(""" + SELECT "author".* FROM "author" \ + JOIN "book" ON "book"."authorId" = "author"."id" \ + JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ + LIMIT 1 + """)) + } + + #if SQLITE_ENABLE_FTS5 + // matchingFts5 + do { + sqlQueries.removeAll() + let title = try Book.all() + .matchingFts5(FTS3Pattern(rawPattern: "cote swann")) + .fetchOne(db) + .map { $0.title } + XCTAssertEqual(title, "Du côté de chez Swann") + XCTAssert(sqlQueries.contains(""" + SELECT "book".* FROM "book" \ + JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ + LIMIT 1 + """)) + + sqlQueries.removeAll() + let fullName = try Author + .joining(required: Author.books.matchingFts5(FTS3Pattern(rawPattern: "cote swann"))) + .fetchOne(db) + .map { $0.fullName } + XCTAssertEqual(fullName, "Marcel Proust") + XCTAssert(sqlQueries.contains(""" + SELECT "author".* FROM "author" \ + JOIN "book" ON "book"."authorId" = "author"."id" \ + JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ + LIMIT 1 + """)) + } + #endif + + // orderById + do { + let titles = try Book.all() + .orderById() + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(titles, ["Moby-Dick", "Du côté de chez Swann"]) + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "book" ORDER BY "id" + """) + + let fullNames = try Author + .joining(required: Author.books.orderById()) + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(fullNames, ["Herman Melville", "Marcel Proust"]) + XCTAssertEqual(lastSQLQuery, """ + SELECT "author".* FROM "author" \ + JOIN "book" ON "book"."authorId" = "author"."id" ORDER BY "book"."id" + """) + } + } + } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 18740104b..b9af335f6 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -127,8 +127,8 @@ class GRDBTestCase: XCTestCase { } } - func assertDidExecute(sql: String) { - XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)") + func assertDidExecute(sql: String, file: StaticString = #file, line: UInt = #line) { + XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index f97bee356..203c01efc 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -122,7 +122,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(try tableRequest.select(Col.age * 2).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try tableRequest.select((Col.age * 2).aliased("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select((Col.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") XCTAssertEqual(try tableRequest.select(Col.name, Col.age).fetchCount(db), 0) @@ -229,12 +229,12 @@ class QueryInterfaceRequestTests: GRDBTestCase { } } - func testSelectAliased() throws { + func testSelectionCustomKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) - let request = tableRequest.select(Col.name.aliased("nom"), (Col.age + 1).aliased("agePlusOne")) + let request = tableRequest.select(Col.name.forKey("nom"), (Col.age + 1).forKey("agePlusOne")) let row = try Row.fetchOne(db, request)! XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", \"age\" + 1 AS \"agePlusOne\" FROM \"readers\" LIMIT 1") XCTAssertEqual(row["nom"] as String, "Arthur") diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index a8ca2be03..b7791daf7 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -65,7 +65,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(try Reader.select(Col.age * 2).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try Reader.select((Col.age * 2).aliased("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(try Reader.select((Col.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") XCTAssertEqual(try Reader.select(Col.name, Col.age).fetchCount(db), 0) diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index eb42f82ab..6bf7e7ca1 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -334,7 +334,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { notificationExpectation.fulfill() } let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.region.description, "t(id,name)") // view is not tracked + XCTAssertEqual(token.observer.observedRegion.description, "t(id,name)") // view is not tracked try withExtendedLifetime(observer) { // Test view observation try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift new file mode 100644 index 000000000..baa448377 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -0,0 +1,325 @@ +import XCTest +#if GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +class ValueObservationRegionRecordingTests: GRDBTestCase { + func testRecordingSelectedRegion() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE team(id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE player(id INTEGER PRIMARY KEY, name TEXT); + """) + + do { + let (_, region) = db.recordingSelectedRegion { } + XCTAssertTrue(region.isEmpty) + } + + do { + let (_, region) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM team") + } + XCTAssertEqual(region.description, "team(id,name)") + } + + do { + let (_, region) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT name FROM player") + } + XCTAssertEqual(region.description, "player(name)") + } + + do { + // Test for rowID optimization + struct Player: TableRecord, FetchableRecord, Decodable { } + let (_, region) = try db.recordingSelectedRegion { + _ = try Player.fetchOne(db, key: 123) + } + XCTAssertEqual(region.description, "player(id,name)[123]") + } + + do { + let (_, region) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM team") + _ = try Row.fetchAll(db, sql: "SELECT * FROM player") + } + XCTAssertEqual(region.description, "player(id,name),team(id,name)") + } + + do { + var region1 = DatabaseRegion() + var region2 = DatabaseRegion() + var region3 = DatabaseRegion() + var region4 = DatabaseRegion() + (_, region1) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM team") + (_, region2) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT name FROM player") + (_, region3) = db.recordingSelectedRegion { } + } + (_, region4) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM player") + } + } + XCTAssertEqual(region1.description, "player(id,name),team(id,name)") + XCTAssertEqual(region2.description, "player(name)") + XCTAssertTrue(region3.isEmpty) + XCTAssertEqual(region4.description, "player(id,name)") + } + } + } + + func testTupleObservation() throws { + // Here we just test that user can destructure an observed tuple. + // I'm completely paranoid about tuple destructuring - I can't wrap my + // head about the rules that allow or disallow it. + let dbQueue = try makeDatabaseQueue() + let observation = ValueObservation.tracking { db -> (Int, String) in + (0, "") + } + _ = observation.start( + in: dbQueue, + onError: { _ in }, + onChange: { (int: Int, string: String) in }) // <- destructure + } + + func testMainQueueScheduling() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + let observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + } + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "a(value),source(name)") + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [0, 1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") + } + } + + func testAsyncSchedulingWithoutInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + } + observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: false) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + // Can't test observedRegion because it is defined asynchronously + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") + } + } + + func testAsyncSchedulingWithInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + } + observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: true) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + // Can't test observedRegion because it is defined asynchronously + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [0, 1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") + } + } + + func testUnsafeSchedulingWithoutInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + } + observation.scheduling = .unsafe(startImmediately: false) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + // Can't test observedRegion because it is defined asynchronously + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") + } + } + + func testUnsafeSchedulingWithInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! + } + observation.scheduling = .unsafe(startImmediately: true) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "a(value),source(name)") + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [0, 1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") + } + } +} diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme index f56ee5c19..fbeee5d2e 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/xcshareddata/xcschemes/GRDBProfiling.xcscheme @@ -1,6 +1,6 @@