diff --git a/.travis.yml b/.travis.yml index 86c84f8fb..6216911dd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,238 @@ git: jobs: include: + ########################################### + ## Test GRDB Xcode 11 + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBOSX (Swift 5.1, macOS) + script: make test_framework_GRDBOSX_maxSwift + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBOSX (Swift 4.2, macOS) + script: make test_framework_GRDBOSX_minSwift + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBWatchOS (watchOS) + script: make test_framework_GRDBWatchOS + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBiOS (Swift 5.1, iOS ) + script: make test_framework_GRDBiOS_maxTarget_maxSwift + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBiOS (Swift 4.2, iOS ) + script: make test_framework_GRDBiOS_maxTarget_minSwift + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBiOS (Swift 5.1, iOS ) + script: make test_framework_GRDBiOS_minTarget + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBtvOS (Swift 5.1, tvOS ) + script: make test_framework_GRDBtvOS_maxTarget_maxSwift + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBtvOS (Swift 4.2, tvOS ) + script: make test_framework_GRDBtvOS_maxTarget_minSwift + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBtvOS (Swift 5.1, tvOS ) + script: make test_framework_GRDBtvOS_minTarget + + - stage: Test GRDB Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDB [SPM] (macOS) + script: make test_SPM + + ########################################### + ## Test GRDBCustom Xcode 11 + + - stage: Test GRDBCustom Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBOSX (Swift 5.1, macOS) + script: make test_framework_GRDBCustomSQLiteOSX + + - stage: Test GRDBCustom Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBiOS (Swift 5.1, iOS ) + script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift + + - stage: Test GRDBCustom Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBiOS (Swift 4.2, iOS ) + script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift + + - stage: Test GRDBCustom Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=GRDBiOS (Swift 5.1, iOS ) + script: make test_framework_GRDBCustomSQLiteiOS_minTarget + + ########################################### + ## Test SQLCipher Xcode 11 + + - stage: Test SQLCipher Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=SQLCipher 3 + script: make test_framework_SQLCipher3 + + - stage: Test SQLCipher Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=SQLCipher 4 + script: make test_framework_SQLCipher4 + + ########################################### + ## Test Installation Xcode 11 + + # Manual Install + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=Manual Install + script: make test_install_manual + + # CocoaPods Lint + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=CocoaPods Lint + script: make test_CocoaPodsLint_GRDB + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=CocoaPods GRDB (framework) + script: make test_install_GRDB_CocoaPods_framework + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=CocoaPods GRDB (static) + script: make test_install_GRDB_CocoaPods_static + + # SPM Install + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=SPM Package + script: make test_install_SPM_Package + + # SPM Install + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=SPM Package in Xcode Project + script: make test_install_SPM_Project + + # Custom SQLite Install + - stage: Test Installation Xcode 11 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode11 + env: + - TID=Custom SQLite + script: make test_install_customSQLite + + ########################################### + ## Test GRDB Xcode 10.3 + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDBOSX (Swift 5, macOS) + script: make test_framework_GRDBOSX_maxSwift + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDBWatchOS (watchOS) + script: make test_framework_GRDBWatchOS + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDBiOS (Swift 5, iOS ) + script: make test_framework_GRDBiOS_maxTarget_maxSwift + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDBiOS (Swift 5, iOS ) + script: make test_framework_GRDBiOS_minTarget + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDBtvOS (Swift 5, tvOS ) + script: make test_framework_GRDBtvOS_maxTarget_maxSwift + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDBtvOS (Swift 5, tvOS ) + script: make test_framework_GRDBtvOS_minTarget + + - stage: Test GRDB Xcode 10.3 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.3 + env: + - TID=GRDB [SPM] (macOS) + script: make test_SPM + ########################################### ## Test GRDB Xcode 10.2 @@ -32,13 +264,6 @@ jobs: - TID=GRDBOSX (Swift 5, macOS) script: make test_framework_GRDBOSX_maxSwift - - stage: Test GRDB Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBOSX (Swift 4.2, macOS) - script: make test_framework_GRDBOSX_minSwift - - stage: Test GRDB Xcode 10.2 gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode10.2 @@ -53,13 +278,6 @@ jobs: - TID=GRDBiOS (Swift 5, iOS ) script: make test_framework_GRDBiOS_maxTarget_maxSwift - - stage: Test GRDB Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBiOS (Swift 4.2, iOS ) - script: make test_framework_GRDBiOS_maxTarget_minSwift - - stage: Test GRDB Xcode 10.2 gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode10.2 @@ -74,13 +292,6 @@ jobs: - TID=GRDBtvOS (Swift 5, tvOS ) script: make test_framework_GRDBtvOS_maxTarget_maxSwift - - stage: Test GRDB Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBtvOS (Swift 4.2, tvOS ) - script: make test_framework_GRDBtvOS_maxTarget_minSwift - - stage: Test GRDB Xcode 10.2 gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode10.2 @@ -95,97 +306,6 @@ jobs: - TID=GRDB [SPM] (macOS) script: make test_SPM - ########################################### - ## Test GRDBCustom Xcode 10.2 - - - stage: Test GRDBCustom Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBOSX (Swift 5, macOS) - script: make test_framework_GRDBCustomSQLiteOSX - - - stage: Test GRDBCustom Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBiOS (Swift 5, iOS ) - script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift - - - stage: Test GRDBCustom Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBiOS (Swift 4.2, iOS ) - script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift - - - stage: Test GRDBCustom Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=GRDBiOS (Swift 5, iOS ) - script: make test_framework_GRDBCustomSQLiteiOS_minTarget - - ########################################### - ## Test SQLCipher Xcode 10.2 - - - stage: Test SQLCipher Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=SQLCipher 3 - script: make test_framework_SQLCipher3 - - - stage: Test SQLCipher Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=SQLCipher 4 - script: make test_framework_SQLCipher4 - - ########################################### - ## Test Installation Xcode 10.2 - - # Manual Install - - stage: Test Installation Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=Manual Install - script: make test_install_manual - - # CocoaPods Lint - - stage: Test Installation Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=CocoaPods Lint - script: make test_CocoaPodsLint_GRDB - - # CocoaPods Install GRDB - - stage: Test Installation Xcode 10.2 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - 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 - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode10.2 - env: - - TID=SPM - script: make test_install_SPM - ########################################### ## Test GRDB Xcode 10.1 @@ -238,30 +358,6 @@ jobs: - TID=GRDB [SPM] (macOS) script: make test_SPM - # ########################################### - # ## Test GRDBCustom Xcode 10.1 - # - # - stage: Test GRDBCustom Xcode 10.1 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10.1 - # env: - # - TID=GRDBOSX (Swift 4.2, macOS) - # script: make test_framework_GRDBCustomSQLiteOSX - # - # - stage: Test GRDBCustom Xcode 10.1 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10.1 - # env: - # - TID=GRDBiOS (Swift 4.2, iOS ) - # script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift - # - # - stage: Test GRDBCustom Xcode 10.1 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10.1 - # env: - # - TID=GRDBiOS (Swift 4.2, iOS ) - # script: make test_framework_GRDBCustomSQLiteiOS_minTarget - ########################################### ## Test GRDB Xcode 10 @@ -314,66 +410,6 @@ jobs: - TID=GRDB [SPM] (macOS) script: make test_SPM - # ########################################### - # ## Test GRDBCustom Xcode 10 - # - # - stage: Test GRDBCustom Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=GRDBOSX (Swift 4.2, macOS) - # script: make test_framework_GRDBCustomSQLiteOSX - # - # - stage: Test GRDBCustom Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=GRDBiOS (Swift 4.2, iOS ) - # script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift - # - # - stage: Test GRDBCustom Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=GRDBiOS (Swift 4.2, iOS ) - # script: make test_framework_GRDBCustomSQLiteiOS_minTarget - # - # ########################################### - # ## Test SQLCipher Xcode 10 - # - # - stage: Test SQLCipher Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=SQLCipher 3 - # script: make test_framework_SQLCipher3 - # - # - stage: Test SQLCipher Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=SQLCipher 4 - # script: make test_framework_SQLCipher4 - - ########################################### - ## Test Installation Xcode 10 - - # # Manual Install - # - stage: Test Installation Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=Manual Install - # script: make test_install_manual - # - # # CocoaPods Lint - # - stage: Test Installation Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=CocoaPods Lint - # script: make test_CocoaPodsLint_GRDB - # CocoaPods Install GRDB - stage: Test Installation Xcode 10 gemfile: .ci/gemfiles/Gemfile.travis @@ -389,11 +425,11 @@ jobs: env: - TID=CocoaPods GRDB (static) script: make test_install_GRDB_CocoaPods_static - - # # SPM Install - # - stage: Test Installation Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=SPM - # script: make test_install_SPM + + # Custom SQLite Install + - stage: Test Installation Xcode 10 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10 + env: + - TID=Custom SQLite + script: make test_install_customSQLite diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d0622365..0141e3c2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: #### 4.x Releases +- `4.5.x` Releases - [4.5.0](#450) - `4.4.x` Releases - [4.4.0](#440) - `4.3.x` Releases - [4.3.0](#430) - `4.2.x` Releases - [4.2.0](#420) | [4.2.1](#421) @@ -61,6 +62,31 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release --> +## 4.5.0 + +Released October 15, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.4.0...v4.5.0) + +**Fixed** + +- The `DatabaseMigrator.eraseDatabaseOnSchemaChange` option no longer fails when migrations depend on database configuration. +- Fixed `DatabasePool.reentrantRead` which was not actually reentrant. +- [#631](https://github.com/groue/GRDB.swift/pull/631): Fix custom SQLite builds +- [#632](https://github.com/groue/GRDB.swift/pull/632) by [@runhum](https://github.com/runhum): Fix documentation typo + +**New** + +- [#622](https://github.com/groue/GRDB.swift/pull/622): Allow observation of FTS4 virtual tables +- [#627](https://github.com/groue/GRDB.swift/pull/627): Swift Package Manager: define SQLite as a system library target +- [#633](https://github.com/groue/GRDB.swift/pull/633): SQLITE_ENABLE_PREUPDATE_HOOK support with CocoaPods +- [#635](https://github.com/groue/GRDB.swift/pull/635): Sunset FetchedRecordsController + +### Documentation Diff + +The [Support for SQLite Pre-Update Hooks](README.md#support-for-sqlite-pre-update-hooks) chapter has been updated with a way to enable extra GRDB APIs for the SQLITE_ENABLE_PREUPDATE_HOOK option with CocoaPods. + +The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) no longer uses [FetchedRecordsController](Documentation/FetchedRecordsController.md), which has been sunsetted. Instead, it tracks database changes with [ValueObservation](README.md#valueobservation), and animates its table view with the Swift built-in [difference(from:)](https://developer.apple.com/documentation/swift/bidirectionalcollection/3200721-difference) method. + + ## 4.4.0 Released September 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.3.0...v4.4.0) @@ -1231,7 +1257,7 @@ Released September 23, 2018 • [diff](https://github.com/groue/GRDB.swift/co ### Documentation Diff -- Enhanced visibility of the [Demo Application](DemoApps/GRDBDemoiOS) +- Enhanced visibility of the [Demo Application](Documentation/DemoApps/GRDBDemoiOS) ## 3.3.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 833b6245e..58b6b9a16 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -78,9 +78,6 @@ The ideas, in alphabetical order: - [Date and Time Functions] - [Decode NSDecimalNumber from Text Columns] - [Documentation] -- [FetchedRecordsController Diffing Algorithm] -- [FetchedRecordsController Support for Any Request] -- [FetchedRecordsController Support for Sections] - [Full Text Search Demo Application] - [JSON] - [Linux] @@ -205,50 +202,6 @@ Inline documentation, the one which is embedded right into the source code and i If you are a good writer, your help will be very warmly welcomed. -### FetchedRecordsController Diffing Algorithm - -:muscle: Hard - -[FetchedRecordsController] uses a Levenshtein-based diffing algorithm which has a terrible algorithmic complexity. This makes this very useful class unable to deal with more than hundreds of elements. - -There exists much more efficient O(n) diffing algorithms that would lift this limitation. - -Starting points: - -- [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources) -- [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit) -- [tonyarnold/Differ](https://github.com/tonyarnold/Differ) -- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff) -- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff) - - -### FetchedRecordsController Support for Any Request - -:muscle: Hard - -[FetchedRecordsController] is able to deal with records, but not with raw rows or values: - -```swift -// Supported by FetchedRecordsController -let recordRequest = Player.all() - -// Not supported by FetchedRecordsController -let stringRequest = Player.select(Column("name"), as: String.self) -let rowRequest = SQLRequest("SELECT ...") -``` - -This limitation does not apply to [ValueObservation] and [RxGRDB]. It would be nice if FetchedRecordsController would become just as versatile. - - -### FetchedRecordsController Support for Sections - -:muscle: Hard - -[FetchedRecordsController] mimics the API of Core Data's [NSFetchedResultsController](https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller), but does not yet support table and collection view sections. - -This improvement most certainly depends on a refreshing of the [FetchedRecordsController Diffing Algorithm]. - - ### Full Text Search Demo Application :baby: Starter Task :pencil: Documentation @@ -360,10 +313,6 @@ Features that blur this focus are non-goals: [Date and Time Functions]: #date-and-time-functions [Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns [Documentation]: #documentation -[FetchedRecordsController]: README.md#fetchedrecordscontroller -[FetchedRecordsController Diffing Algorithm]: #fetchedrecordscontroller-diffing-algorithm -[FetchedRecordsController Support for Any Request]: #fetchedrecordscontroller-support-for-any-request -[FetchedRecordsController Support for Sections]: #fetchedrecordscontroller-support-for-sections [Full Text Search Demo Application]: #full-text-search-demo-application [How is the Library Organized?]: Documentation/LibraryOrganization.md [How is the Repository Organized?]: Documentation/RepositoryOrganization.md diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 2d7991381..2e3be05ed 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.4.0 + git checkout v4.5.0 git submodule update --init SQLiteCustom/src ```` @@ -120,6 +120,8 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ``` The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file. + + Select your application target in the "Provide build settings from" menu. 9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System). diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj similarity index 87% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index f22440fa0..58ba33852 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; }; + 56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; }; + 56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; }; 568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; }; 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; @@ -14,8 +18,6 @@ 568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; }; 568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; }; 568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */; }; - 568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */; }; - 568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */; }; 56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; }; 56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; }; @@ -24,18 +26,93 @@ 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; }; - 56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; }; - 56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = { + 56606D092355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = DC3773F319C8CBB3004FCF85; + remoteInfo = GRDBOSX; + }; + 56606D0B2355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 56E5D7F91B4D422D00430942; + remoteInfo = GRDBOSXTests; + }; + 56606D0D2355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 560C981A1C0E22D300BF8471; + remoteInfo = GRDBOSXPerformanceTests; + }; + 56606D0F2355931F00185962 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; proxyType = 2; remoteGlobalIDString = 56439B501F4CA1DC0066043F; remoteInfo = GRDBOSXPerformanceComparisonTests; }; + 56606D112355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 56553C181C3E906C00522B5C; + remoteInfo = GRDBOSXCrashTests; + }; + 56606D132355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 56E5D7CA1B4D3FED00430942; + remoteInfo = GRDBiOS; + }; + 56606D152355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 56E5D7D31B4D3FEE00430942; + remoteInfo = GRDBiOSTests; + }; + 56606D172355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 565490A01D5A4798005622CB; + remoteInfo = GRDBWatchOS; + }; + 56606D192355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = AAA4DCFE230F1E0600C74B15; + remoteInfo = GRDBtvOS; + }; + 56606D1B2355931F00185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = AAA4DDD4230F262000C74B15; + remoteInfo = GRDBtvOSTests; + }; + 56606D1D2355937900185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 56E5D7C91B4D3FED00430942; + remoteInfo = GRDBiOS; + }; + 56606D22235593A300185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 5654909F1D5A4798005622CB; + remoteInfo = GRDBWatchOS; + }; 568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; @@ -50,83 +127,6 @@ remoteGlobalIDString = 568E5FBE1E926430002582E0; remoteInfo = GRDBDemoWatchOS; }; - 568E5FE21E926535002582E0 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = 5654909F1D5A4798005622CB; - remoteInfo = GRDBWatchOS; - }; - 568E5FE61E926547002582E0 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = 5654909F1D5A4798005622CB; - remoteInfo = GRDBWatchOS; - }; - 56B0363A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DC3773F319C8CBB3004FCF85; - remoteInfo = GRDBOSX; - }; - 56B0363C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56E5D7F91B4D422D00430942; - remoteInfo = GRDBOSXTests; - }; - 56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 560C981A1C0E22D300BF8471; - remoteInfo = GRDBOSXPerformanceTests; - }; - 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56553C181C3E906C00522B5C; - remoteInfo = GRDBOSXCrashTests; - }; - 56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56E5D7CA1B4D3FED00430942; - remoteInfo = GRDBiOS; - }; - 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56E5D7D31B4D3FEE00430942; - remoteInfo = GRDBiOSTests; - }; - 56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 565490A01D5A4798005622CB; - remoteInfo = GRDBWatchOS; - }; - 56B0365C1E8D9F8F003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = 56E5D7C91B4D3FED00430942; - remoteInfo = GRDBiOS; - }; - 56B036601E8D9FB1003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = 56E5D7C91B4D3FED00430942; - remoteInfo = GRDBiOS; - }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -158,7 +158,7 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( - 568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */, + 56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; @@ -169,7 +169,7 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( - 56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */, + 56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; @@ -196,7 +196,7 @@ 56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; - 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = ""; }; + 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -204,7 +204,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */, + 56606D24235593AB00185962 /* GRDB.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -212,13 +212,37 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */, + 56606D202355938A00185962 /* GRDB.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 56606CFD2355931F00185962 /* Products */ = { + isa = PBXGroup; + children = ( + 56606D0A2355931F00185962 /* GRDB.framework */, + 56606D0C2355931F00185962 /* GRDBOSXTests.xctest */, + 56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */, + 56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.xctest */, + 56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */, + 56606D142355931F00185962 /* GRDB.framework */, + 56606D162355931F00185962 /* GRDBiOSTests.xctest */, + 56606D182355931F00185962 /* GRDB.framework */, + 56606D1A2355931F00185962 /* GRDB.framework */, + 56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 56606D1F2355938A00185962 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; 568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = { isa = PBXGroup; children = ( @@ -248,6 +272,7 @@ 568E5FC01E926430002582E0 /* GRDBDemoWatchOS */, 568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */, 56B036041E8D9EBE003B6DA4 /* Products */, + 56606D1F2355938A00185962 /* Frameworks */, ); sourceTree = ""; }; @@ -277,21 +302,6 @@ path = GRDBDemoiOS; sourceTree = ""; }; - 56B036271E8D9F79003B6DA4 /* Products */ = { - isa = PBXGroup; - children = ( - 56B0363B1E8D9F79003B6DA4 /* GRDB.framework */, - 56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */, - 56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */, - 563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */, - 56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */, - 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */, - 56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */, - 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */, - ); - name = Products; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -324,8 +334,7 @@ buildRules = ( ); dependencies = ( - 568E5FE31E926535002582E0 /* PBXTargetDependency */, - 568E5FE71E926547002582E0 /* PBXTargetDependency */, + 56606D23235593A300185962 /* PBXTargetDependency */, ); name = "GRDBDemoWatchOS Extension"; productName = "GRDBDemoWatchOS Extension"; @@ -345,8 +354,7 @@ buildRules = ( ); dependencies = ( - 56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */, - 56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */, + 56606D1E2355937900185962 /* PBXTargetDependency */, 568E5FD81E926430002582E0 /* PBXTargetDependency */, ); name = GRDBDemoiOS; @@ -396,7 +404,7 @@ projectDirPath = ""; projectReferences = ( { - ProductGroup = 56B036271E8D9F79003B6DA4 /* Products */; + ProductGroup = 56606CFD2355931F00185962 /* Products */; ProjectRef = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; }, ); @@ -410,60 +418,74 @@ /* End PBXProject section */ /* Begin PBXReferenceProxy section */ - 563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBOSXPerformanceComparisonTests.xctest; - remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = { + 56606D0A2355931F00185962 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; path = GRDB.framework; - remoteRef = 56B0363A1E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */ = { + 56606D0C2355931F00185962 /* GRDBOSXTests.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; path = GRDBOSXTests.xctest; - remoteRef = 56B0363C1E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */ = { + 56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; path = GRDBOSXPerformanceTests.xctest; - remoteRef = 56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D0D2355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */ = { + 56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBOSXPerformanceComparisonTests.xctest; + remoteRef = 56606D0F2355931F00185962 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; path = GRDBOSXCrashTests.xctest; - remoteRef = 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D112355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */ = { + 56606D142355931F00185962 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; path = GRDB.framework; - remoteRef = 56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D132355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */ = { + 56606D162355931F00185962 /* GRDBiOSTests.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; path = GRDBiOSTests.xctest; - remoteRef = 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D152355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */ = { + 56606D182355931F00185962 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; path = GRDB.framework; - remoteRef = 56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */; + remoteRef = 56606D172355931F00185962 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56606D1A2355931F00185962 /* GRDB.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = GRDB.framework; + remoteRef = 56606D192355931F00185962 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBtvOSTests.xctest; + remoteRef = 56606D1B2355931F00185962 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ @@ -523,6 +545,16 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 56606D1E2355937900185962 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GRDBiOS; + targetProxy = 56606D1D2355937900185962 /* PBXContainerItemProxy */; + }; + 56606D23235593A300185962 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GRDBWatchOS; + targetProxy = 56606D22235593A300185962 /* PBXContainerItemProxy */; + }; 568E5FCE1E926430002582E0 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */; @@ -533,26 +565,6 @@ target = 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */; targetProxy = 568E5FD71E926430002582E0 /* PBXContainerItemProxy */; }; - 568E5FE31E926535002582E0 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDBWatchOS; - targetProxy = 568E5FE21E926535002582E0 /* PBXContainerItemProxy */; - }; - 568E5FE71E926547002582E0 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDBWatchOS; - targetProxy = 568E5FE61E926547002582E0 /* PBXContainerItemProxy */; - }; - 56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDBiOS; - targetProxy = 56B0365C1E8D9F8F003B6DA4 /* PBXContainerItemProxy */; - }; - 56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDBiOS; - targetProxy = 56B036601E8D9FB1003B6DA4 /* PBXContainerItemProxy */; - }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -708,7 +720,7 @@ SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -759,7 +771,7 @@ MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; VALIDATE_PRODUCT = YES; }; name = Release; diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme similarity index 100% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme similarity index 96% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme rename to Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme index 78cd878d4..cfd6faf50 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme @@ -27,8 +27,6 @@ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> - - - - + + - - ! + private var players: [Player] = [] + private var playersObserver: TransactionObserver? private var playerCountObserver: TransactionObserver? private var playerOrdering: PlayerOrdering = .byScore { didSet { - try! playersController.setRequest(playersRequest) configureOrderingBarButtonItem() + configureTableView() } } private var playersRequest: QueryInterfaceRequest { @@ -79,7 +80,8 @@ class PlayersViewController: UITableViewController { onError: { error in fatalError("Unexpected error: \(error)") }, - onChange: { [unowned self] count in + onChange: { [weak self] count in + guard let self = self else { return } switch count { case 0: self.navigationItem.title = "No Player" case 1: self.navigationItem.title = "1 Player" @@ -89,46 +91,49 @@ class PlayersViewController: UITableViewController { } private func configureTableView() { - // Track changes in the database players - playersController = try! FetchedRecordsController(dbQueue, request: playersRequest) - - // Animate changes in the table view - playersController.trackChanges( - willChange: { [unowned self] _ in - self.tableView.beginUpdates() - }, - onChange: { [unowned self] (controller, record, change) in - switch change { - case .insertion(let indexPath): - self.tableView.insertRows(at: [indexPath], with: .fade) - - case .deletion(let indexPath): - self.tableView.deleteRows(at: [indexPath], with: .fade) - - case .update(let indexPath, _): - if let cell = self.tableView.cellForRow(at: indexPath) { - self.configure(cell, at: indexPath) + // Track changes in the list of players + let request = self.playersRequest + let observation = ValueObservation.tracking { db in + try request.fetchAll(db) + } + playersObserver = observation.start( + in: dbQueue, + onError: { error in + fatalError("Unexpected error: \(error)") + }, + onChange: { [weak self] players in + guard let self = self else { return } + + // Compute difference between current and new list of players + let difference = players + .difference(from: self.players) + .inferringMoves() + + // Apply those changes to the table view + self.tableView.performBatchUpdates({ + self.players = players + for change in difference { + switch change { + case let .remove(offset, _, associatedWith): + if let associatedWith = associatedWith { + self.tableView.moveRow( + at: IndexPath(row: offset, section: 0), + to: IndexPath(row: associatedWith, section: 0)) + } else { + self.tableView.deleteRows( + at: [IndexPath(row: offset, section: 0)], + with: .fade) + } + case let .insert(offset, _, associatedWith): + if associatedWith == nil { + self.tableView.insertRows( + at: [IndexPath(row: offset, section: 0)], + with: .fade) + } + } } - - case .move(let indexPath, let newIndexPath, _): - // Actually move cells around for more demo effect :-) - let cell = self.tableView.cellForRow(at: indexPath) - self.tableView.moveRow(at: indexPath, to: newIndexPath) - if let cell = cell { - self.configure(cell, at: newIndexPath) - } - - // A quieter animation: - // self.tableView.deleteRows(at: [indexPath], with: .fade) - // self.tableView.insertRows(at: [newIndexPath], with: .fade) - } - }, - didChange: { [unowned self] _ in - self.tableView.endUpdates() + }, completion: nil) }) - - // Initial fetch - try! playersController.performFetch() } } @@ -139,7 +144,7 @@ extension PlayersViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Edit" { - let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let player = players[tableView.indexPathForSelectedRow!.row] let controller = segue.destination as! PlayerEditionViewController controller.title = player.name controller.player = player @@ -168,12 +173,8 @@ extension PlayersViewController { // MARK: - UITableViewDataSource extension PlayersViewController { - override func numberOfSections(in tableView: UITableView) -> Int { - return playersController.sections.count - } - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return playersController.sections[section].numberOfRecords + return players.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { @@ -184,14 +185,14 @@ extension PlayersViewController { override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Delete the player - let player = playersController.record(at: indexPath) + let player = players[indexPath.row] try! dbQueue.write { db in _ = try player.delete(db) } } private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let player = playersController.record(at: indexPath) + let player = players[indexPath.row] if player.name.isEmpty { cell.textLabel?.text = "-" } else { diff --git a/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md similarity index 79% rename from DemoApps/GRDBDemoiOS/README.md rename to Documentation/DemoApps/GRDBDemoiOS/README.md index 9c0eb9562..a4fde46ce 100644 --- a/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -7,7 +7,7 @@ Demo Application - how to setup a database in an iOS app - how to define a simple [Codable Record](../../README.md#codable-records) -- how to track database changes and animate a table view with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). +- how to track database changes and animate a table view with [ValueObservation](../../README.md#valueobservation). **Files of interest:** @@ -25,7 +25,7 @@ Demo Application - [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift) - `PlayersViewController` displays a list of players. It keeps its title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). + `PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation). - [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift) diff --git a/Documentation/FetchedRecordsController.md b/Documentation/FetchedRecordsController.md new file mode 100644 index 000000000..f61851d18 --- /dev/null +++ b/Documentation/FetchedRecordsController.md @@ -0,0 +1,347 @@ +# FetchedRecordsController + +**FetchedRecordsController is a sunsetted GRDB API.** + +It is not deprecated. But FetchedRecordsController has known limitations which are not planned to be lifted. + +You are advised to use [ValueObservation] instead of FetchedRecordsController. + +--- + +**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.** + +It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). + +Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. + +- [Creating the Fetched Records Controller](#creating-the-fetched-records-controller) +- [Responding to Changes](#responding-to-changes) +- [The Changes Notifications](#the-changes-notifications) +- [Modifying the Fetch Request](#modifying-the-fetch-request) +- [Table and Collection Views](#table-and-collection-views) + - [Implementing the Table View Datasource Methods](#implementing-the-table-view-datasource-methods) + - [Implementing Table View Updates](#implementing-table-view-updates) +- [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) + + +## Creating the Fetched Records Controller + +When you initialize a fetched records controller, you provide the following mandatory information: + +- A [database connection](../README.md#database-connections) +- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class +- A fetch request + +```swift +class Player : Record { ... } +let dbQueue = DatabaseQueue(...) // or DatabasePool + +// Using a Request from the Query Interface: +let controller = FetchedRecordsController( + dbQueue, + request: Player.order(Column("name"))) + +// Using SQL, and eventual arguments: +let controller = FetchedRecordsController( + dbQueue, + sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?", + arguments: ["FR"]) +``` + +The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request. + +```swift +let controller = FetchedRecordsController( + dbQueue, + sql: """ + SELECT author.name, COUNT(book.id) AS bookCount + FROM author + LEFT JOIN book ON book.authorId = author.id + GROUP BY author.id + ORDER BY author.name + """) +``` + + +After creating an instance, you invoke `performFetch()` to actually execute +the fetch. + +```swift +try controller.performFetch() +``` + + +## Responding to Changes + +In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values. + +Changes are not reflected until they are applied in the database by a successful [transaction](../README.md#transactions-and-savepoints): + +```swift +// One transaction +try dbQueue.write { db in // or dbPool.write + try player1.insert(db) + try player2.insert(db) +} + +// One transaction +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try player1.insert(db) + try player2.insert(db) + return .commit +} + +// Two transactions +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + try player1.insert(db) + try player2.insert(db) +} +``` + +When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together. + + +## The Changes Notifications + +An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of *callbacks*: + +```swift +let controller = try FetchedRecordsController(...) + +controller.trackChanges( + // controller's records are about to change: + willChange: { controller in ... }, + + // notification of individual record changes: + onChange: { (controller, record, change) in ... }, + + // controller's records have changed: + didChange: { controller in ... }) + +try controller.performFetch() +``` + +See [Implementing Table View Updates](#implementing-table-view-updates) for more detail on table view updates. + +**All callbacks are optional.** When you only need to grab the latest results, you can omit the `didChange` argument name: + +```swift +controller.trackChanges { controller in + let newPlayers = controller.fetchedRecords // [Player] +} +``` + +> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. + +Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks: + +```swift +// BAD: memory leak +controller.trackChanges { _ in + let newPlayers = controller.fetchedRecords +} + +// GOOD +controller.trackChanges { controller in + let newPlayers = controller.fetchedRecords +} +``` + +**Callbacks are invoked asynchronously.** See [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) for more information. + +**Values fetched from inside callbacks may be inconsistent with the controller's records.** This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen. + +To avoid inconsistencies, provide a `fetchAlongside` argument to the `trackChanges` method, as below: + +```swift +controller.trackChanges( + fetchAlongside: { db in + // Fetch any extra value, for example the number of fetched records: + return try Player.fetchCount(db) + }, + didChange: { (controller, count) in + // The extra value is the second argument. + let recordsCount = controller.fetchedRecords.count + assert(count == recordsCount) // guaranteed + }) +``` + +Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch. + +```swift +controller.trackErrors { (controller, error) in + print("Missed a transaction because \(error)") +} +``` + + +## Modifying the Fetch Request + +You can change a fetched records controller's fetch request or SQL query. + +```swift +controller.setRequest(Player.order(Column("name"))) +controller.setRequest(sql: "SELECT ...", arguments: ...) +``` + +The [notification callbacks](#the-changes-notifications) are notified of eventual changes if the new request fetches a different set of records. + +> :point_up: **Note**: This behavior differs from Core Data's NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced. + +**Change callbacks are invoked asynchronously.** This means that modifying the request from the main thread does *not* immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called: + +```swift +// Change request on the main thread: +controller.setRequest(Player.order(Column("name"))) +// Here callbacks have not been called yet. +// You can cancel them, and refresh records immediately: +try controller.performFetch() +``` + +## Table and Collection Views + +FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content. + +For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key: + +```swift +class Player : TableRecord { ... } +let controller = FetchedRecordsController( + dbQueue, + request: Player.all()) +``` + +For other types, the fetched records controller needs you to be more explicit: + +```swift +let controller = FetchedRecordsController( + dbQueue, + request: ..., + isSameRecord: { (player1, player2) in player1.id == player2.id }) +``` + + +### Implementing the Table View Datasource Methods + +The table view data source asks the fetched records controller to provide relevant information: + +```swift +func numberOfSections(in tableView: UITableView) -> Int { + return fetchedRecordsController.sections.count +} + +func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return fetchedRecordsController.sections[section].numberOfRecords +} + +func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = ... + let record = fetchedRecordsController.record(at: indexPath) + // Configure the cell + return cell +} +``` + +> :point_up: **Note**: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section. + + +### Implementing Table View Updates + +When changes in the fetched records should reload the whole table view, you can simply tell so: + +```swift +controller.trackChanges { [unowned self] _ in + self.tableView.reloadData() +} +``` + +Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView. + + +#### Typical Table View Updates + +For animated table view updates, use the `willChange` and `didChange` callbacks to bracket events provided by the fetched records controller, as illustrated in the following example: + +```swift +// Assume self has a tableView property, and a cell configuration +// method named configure(_:at:). + +controller.trackChanges( + // controller's records are about to change: + willChange: { [unowned self] _ in + self.tableView.beginUpdates() + }, + + // notification of individual record changes: + onChange: { [unowned self] (controller, record, change) in + switch change { + case .insertion(let indexPath): + self.tableView.insertRows(at: [indexPath], with: .fade) + + case .deletion(let indexPath): + self.tableView.deleteRows(at: [indexPath], with: .fade) + + case .update(let indexPath, _): + if let cell = self.tableView.cellForRow(at: indexPath) { + self.configure(cell, at: indexPath) + } + + case .move(let indexPath, let newIndexPath, _): + self.tableView.deleteRows(at: [indexPath], with: .fade) + self.tableView.insertRows(at: [newIndexPath], with: .fade) + + // // Alternate technique which actually moves cells around: + // let cell = self.tableView.cellForRow(at: indexPath) + // self.tableView.moveRow(at: indexPath, to: newIndexPath) + // if let cell = cell { + // self.configure(cell, at: newIndexPath) + // } + } + }, + + // controller's records have changed: + didChange: { [unowned self] _ in + self.tableView.endUpdates() + }) +``` + +> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. +> +> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references. + + +## FetchedRecordsController Concurrency + +**A fetched records controller *can not* be used from any thread.** + +When the database itself can be read and modified from [any thread](../README.md#database-connections), fetched records controllers **must** be used from the main thread. Record changes are also [notified](#the-changes-notifications) on the main thread. + +**Change callbacks are invoked asynchronously.** This means that changes made from the main thread are *not* immediately notified. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called: + +```swift +// Change database on the main thread: +try dbQueue.write { db in + try Player(...).insert(db) +} +// Here callbacks have not been called yet. +// You can cancel them, and refresh records immediately: +try controller.performFetch() +``` + +> :point_up: **Note**: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well. +> +> ```swift +> let queue = DispatchQueue() +> queue.async { +> let controller = try FetchedRecordsController(..., queue: queue) +> controller.trackChanges { /* in queue */ } +> try controller.performFetch() +> } +> ``` + + +[ValueObservation]: ../README.md#valueobservation +[GRDBCombine]: http://github.com/groue/GRDBCombine +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[FetchableRecord]: ../README.md#fetchablerecord-protocol +[TableRecord]: ../README.md#tablerecord-protocol diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 2e708cd5c..ded26fe62 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -505,7 +505,6 @@ If you have time, you may dig deeper in GRDB 3 with those updated documentation [If You Use Custom Requests]: #if-you-use-custom-requests [If You Use RxGRDB]: #if-you-use-rxgrdb [Notable Documentation Updates]: #notable-documentation-updates -[FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Associations]: AssociationsBasics.md [DatabaseMigrator]: ../README.md#migrations diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 71de44db3..5824e3788 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -679,8 +679,6 @@ Instead, have a look at [Database Observation]: > :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes. > -> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view. -> > :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way. > > :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way. @@ -711,7 +709,6 @@ Instead, have a look at [Database Observation]: [PersistableRecord]: ../README.md#persistablerecord-protocol [Database Observation]: ../README.md#database-changes-observation [ValueObservation]: ../README.md#valueobservation -[FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [GRDBCombine]: http://github.com/groue/GRDBCombine [TransactionObserver]: ../README.md#transactionobserver-protocol diff --git a/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift similarity index 100% rename from Playgrounds/Associations.playground/Contents.swift rename to Documentation/Playgrounds/Associations.playground/Contents.swift diff --git a/Playgrounds/Associations.playground/contents.xcplayground b/Documentation/Playgrounds/Associations.playground/contents.xcplayground similarity index 100% rename from Playgrounds/Associations.playground/contents.xcplayground rename to Documentation/Playgrounds/Associations.playground/contents.xcplayground diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift similarity index 100% rename from Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift rename to Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground b/Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground similarity index 100% rename from Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground rename to Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground diff --git a/Playgrounds/Issue156.playground/Contents.swift b/Documentation/Playgrounds/Issue156.playground/Contents.swift similarity index 100% rename from Playgrounds/Issue156.playground/Contents.swift rename to Documentation/Playgrounds/Issue156.playground/Contents.swift diff --git a/Playgrounds/Issue156.playground/contents.xcplayground b/Documentation/Playgrounds/Issue156.playground/contents.xcplayground similarity index 100% rename from Playgrounds/Issue156.playground/contents.xcplayground rename to Documentation/Playgrounds/Issue156.playground/contents.xcplayground diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift similarity index 100% rename from Playgrounds/JSONSynchronization.playground/Contents.swift rename to Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift diff --git a/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift similarity index 100% rename from Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift rename to Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift diff --git a/Playgrounds/JSONSynchronization.playground/contents.xcplayground b/Documentation/Playgrounds/JSONSynchronization.playground/contents.xcplayground similarity index 100% rename from Playgrounds/JSONSynchronization.playground/contents.xcplayground rename to Documentation/Playgrounds/JSONSynchronization.playground/contents.xcplayground diff --git a/Playgrounds/JSONSynchronization.playground/playground.xcworkspace/contents.xcworkspacedata b/Documentation/Playgrounds/JSONSynchronization.playground/playground.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Playgrounds/JSONSynchronization.playground/playground.xcworkspace/contents.xcworkspacedata rename to Documentation/Playgrounds/JSONSynchronization.playground/playground.xcworkspace/contents.xcworkspacedata diff --git a/Playgrounds/MyPlayground.playground/Contents.swift b/Documentation/Playgrounds/MyPlayground.playground/Contents.swift similarity index 100% rename from Playgrounds/MyPlayground.playground/Contents.swift rename to Documentation/Playgrounds/MyPlayground.playground/Contents.swift diff --git a/Playgrounds/MyPlayground.playground/contents.xcplayground b/Documentation/Playgrounds/MyPlayground.playground/contents.xcplayground similarity index 100% rename from Playgrounds/MyPlayground.playground/contents.xcplayground rename to Documentation/Playgrounds/MyPlayground.playground/contents.xcplayground diff --git a/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift similarity index 100% rename from Playgrounds/Tour.playground/Contents.swift rename to Documentation/Playgrounds/Tour.playground/Contents.swift diff --git a/Playgrounds/Tour.playground/contents.xcplayground b/Documentation/Playgrounds/Tour.playground/contents.xcplayground similarity index 100% rename from Playgrounds/Tour.playground/contents.xcplayground rename to Documentation/Playgrounds/Tour.playground/contents.xcplayground diff --git a/Playgrounds/TransactionObserver.playground/Contents.swift b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift similarity index 100% rename from Playgrounds/TransactionObserver.playground/Contents.swift rename to Documentation/Playgrounds/TransactionObserver.playground/Contents.swift diff --git a/Playgrounds/TransactionObserver.playground/contents.xcplayground b/Documentation/Playgrounds/TransactionObserver.playground/contents.xcplayground similarity index 100% rename from Playgrounds/TransactionObserver.playground/contents.xcplayground rename to Documentation/Playgrounds/TransactionObserver.playground/contents.xcplayground diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index ad44337dd..4f722c3f5 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -117,7 +117,7 @@ let players = try Player.fetchAll(db) **Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant. -There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change, or [FetchedRecordsController], which animates table and collection views. And don't forget [GRDBCombine] and [RxGRDB], two sets of reactive extensions based on [Combine] and [RxSwift]: +There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change. And don't forget [GRDBCombine] and [RxGRDB], two sets of reactive extensions based on [Combine] and [RxSwift]: ```swift Player.all().rx @@ -292,7 +292,6 @@ Happy GRDB! :gift: [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel [ValueObservation]: ../README.md#valueobservation -[FetchedRecordsController]: ../README.md#fetchedrecordscontroller [Fluent]: https://github.com/vapor/fluent [FMDB]: http://github.com/ccgus/fmdb [GRDB]: http://github.com/groue/GRDB.swift diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index ad71b7afa..d48c8133a 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.4.0' + s.version = '4.5.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 09e2a5b62..2a6ee6f41 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -428,6 +428,10 @@ 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; + 566BE71F2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; + 566BE7202342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; + 566BE7212342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; }; @@ -1451,6 +1455,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; @@ -1575,8 +1580,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.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 = ""; }; + 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-11.0/Realm.framework"; sourceTree = ""; }; + 56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-11.0/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 = ""; }; @@ -2103,6 +2108,7 @@ 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */, 563EF4492161F179007DAACD /* Inflections.swift */, 569BBA482291707D00478429 /* Inflections+English.swift */, + 566BE7172342542F00A8254B /* LockedBox.swift */, 563EF414215F87EB007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */, @@ -2320,8 +2326,8 @@ 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */, - 56FBFED82210731A00945324 /* SQLRequest.swift */, 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */, + 56FBFED82210731A00945324 /* SQLRequest.swift */, 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, @@ -2811,11 +2817,18 @@ 56E5D7D21B4D3FEE00430942 = { CreatedOnToolsVersion = 7.0; LastSwiftMigration = 0800; + ProvisioningStyle = Manual; }; 56E5D7F81B4D422D00430942 = { CreatedOnToolsVersion = 7.0; LastSwiftMigration = 1020; }; + AAA4DC75230F1E0600C74B15 = { + ProvisioningStyle = Manual; + }; + AAA4DD07230F262000C74B15 = { + ProvisioningStyle = Manual; + }; DC3773F219C8CBB3004FCF85 = { CreatedOnToolsVersion = 6.1; LastSwiftMigration = 1020; @@ -3212,6 +3225,7 @@ 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */, + 566BE7202342542F00A8254B /* LockedBox.swift in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 564CE4D821B2DEB600652B19 /* CompactMap.swift in Sources */, @@ -3335,6 +3349,7 @@ 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */, + 566BE71F2342542F00A8254B /* LockedBox.swift in Sources */, 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, @@ -3871,6 +3886,7 @@ AAA4DCCC230F1E0600C74B15 /* DatabaseQueue.swift in Sources */, AAA4DCCD230F1E0600C74B15 /* ValueObservation.swift in Sources */, AAA4DCCE230F1E0600C74B15 /* DatabasePromise.swift in Sources */, + 566BE7212342542F00A8254B /* LockedBox.swift in Sources */, AAA4DCCF230F1E0600C74B15 /* VirtualTableModule.swift in Sources */, AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */, AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */, @@ -4205,6 +4221,7 @@ 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, + 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, @@ -4330,7 +4347,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3", + "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-11.0", ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -4353,7 +4370,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3", + "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-11.0", ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -4511,13 +4528,17 @@ buildSettings = { CLANG_ENABLE_OBJC_WEAK = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CODE_SIGN_STYLE = Manual; DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + "PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = ""; SDKROOT = iphoneos; }; name = Debug; @@ -4528,14 +4549,18 @@ buildSettings = { CLANG_ENABLE_OBJC_WEAK = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CODE_SIGN_STYLE = Manual; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + "PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = ""; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; @@ -4587,14 +4612,17 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + CODE_SIGN_STYLE = Manual; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -4612,15 +4640,18 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + CODE_SIGN_STYLE = Manual; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; @@ -4633,14 +4664,18 @@ baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { CLANG_ENABLE_OBJC_WEAK = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CODE_SIGN_STYLE = Manual; DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBtvOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -4651,15 +4686,19 @@ baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { CLANG_ENABLE_OBJC_WEAK = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CODE_SIGN_STYLE = Manual; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBtvOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TVOS_DEPLOYMENT_TARGET = 9.0; diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index b95c60b9f..4919b79c0 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -2,7 +2,7 @@ @@ -51,6 +51,6 @@ location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj"> + location = "group:Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj"> diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 71e0b773a..83389587c 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -10,6 +10,13 @@ extension Database { // MARK: - Database Schema + func withSchemaCache(_ schemaCache: DatabaseSchemaCache, _ block: () throws -> T) rethrows -> T { + var oldCache = self.schemaCache + defer { self.schemaCache = oldCache } + self.schemaCache = schemaCache + return try block() + } + /// Clears the database schema cache. /// /// You may need to clear the cache manually if the database schema is diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index bb4db1c17..01aae0eb5 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -114,7 +114,7 @@ public final class Database { // > connection while this routine is running, then the return value // > is undefined. SchedulingWatchdog.preconditionValidQueue(self) - if isClosed { return false } // Support for SerializedDatabasae.deinit + if isClosed { return false } // Support for SerializedDatabase.deinit return sqlite3_get_autocommit(sqliteConnection) == 0 } @@ -629,7 +629,15 @@ extension Database { } extension Database { - + func checkpoint(_ kind: Database.CheckpointMode) throws { + let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: lastErrorMessage) + } + } +} + +extension Database { // MARK: - Transactions & Savepoint /// Executes a block inside a database transaction. @@ -792,7 +800,7 @@ extension Database { /// Begins a database transaction and take a snapshot of the last committed /// database state. - func beginSnapshotIsolation() throws { + func beginSnapshotTransaction() throws { // https://www.sqlite.org/isolation.html // // > In WAL mode, SQLite exhibits "snapshot isolation". When a read diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 1ab665c6a..98baa755e 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -14,14 +14,14 @@ import UIKit /// A DatabasePool grants concurrent accesses to an SQLite database. public final class DatabasePool: DatabaseWriter { private let writer: SerializedDatabase - private var readerConfig: Configuration private var readerPool: Pool! + var readerConfiguration: Configuration private var functions = Set() private var collations = Set() private var tokenizerRegistrations: [(Database) -> Void] = [] - var snapshotCount = ReadWriteBox(0) + var databaseSnapshotCount = LockedBox(value: 0) #if os(iOS) private weak var application: UIApplication? @@ -61,6 +61,29 @@ public final class DatabasePool: DatabaseWriter { defaultLabel: "GRDB.DatabasePool", purpose: "writer") + // Readers + readerConfiguration = configuration + readerConfiguration.readonly = true + // Readers use deferred transactions by default. + // Other transaction kinds are forbidden by SQLite in read-only connections. + readerConfiguration.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. + readerConfiguration.allowsUnsafeTransactions = false + var readerCount = 0 + readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in + readerCount += 1 // protected by pool (TODO: documented this protection behavior) + let reader = try SerializedDatabase( + path: path, + configuration: self.readerConfiguration, + schemaCache: SimpleDatabaseSchemaCache(), + defaultLabel: "GRDB.DatabasePool", + purpose: "reader.\(readerCount)") + reader.sync { self.setupDatabase($0) } + return reader + }) + // Activate WAL Mode unless readonly if !configuration.readonly { try writer.sync { db in @@ -79,36 +102,16 @@ 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.inSavepoint { + try db.execute(sql: """ + CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); + DROP TABLE grdb_issue_102; + """) + return .commit + } } } } - - // Readers - readerConfig = configuration - readerConfig.readonly = true - // 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) - let reader = try SerializedDatabase( - path: path, - configuration: self.readerConfig, - schemaCache: SimpleDatabaseSchemaCache(), - defaultLabel: "GRDB.DatabasePool", - purpose: "reader.\(readerCount)") - reader.sync { self.setupDatabase($0) } - return reader - }) } #if os(iOS) @@ -154,13 +157,7 @@ extension DatabasePool { /// - parameter kind: The checkpoint mode (default passive) public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { try writer.sync { db in - // TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and - // check whether we need a busy handler on writer and/or readers - // 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) - } + try db.checkpoint(kind) } } } @@ -247,7 +244,7 @@ extension DatabasePool { try readerPool.barrier { try writer.sync { try $0.changePassphrase(passphrase) } readerPool.removeAll() - readerConfig._passphrase = passphrase + readerConfiguration._passphrase = passphrase } } } @@ -293,8 +290,9 @@ extension DatabasePool: DatabaseReader { // See DatabasePoolTests.testReadMethodIsolationOfBlock(). try db.inTransaction(.deferred) { // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - result = try block(db) + result = try db.withSchemaCache(SimpleDatabaseSchemaCache()) { + try block(db) + } return .commit } return result! @@ -340,9 +338,9 @@ extension DatabasePool: DatabaseReader { try db.beginTransaction(.deferred) // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - - block(.success(db)) + db.withSchemaCache(SimpleDatabaseSchemaCache()) { + block(.success(db)) + } } catch { block(.failure(error)) } @@ -385,8 +383,9 @@ extension DatabasePool: DatabaseReader { return try readerPool.get { reader in try reader.sync { db in // No schema cache when snapshot isolation is not established - db.schemaCache = EmptyDatabaseSchemaCache() - return try block(db) + return try db.withSchemaCache(EmptyDatabaseSchemaCache()) { + try block(db) + } } } } @@ -425,8 +424,9 @@ extension DatabasePool: DatabaseReader { return try readerPool.get { reader in try reader.sync { db in // No schema cache when snapshot isolation is not established - db.schemaCache = EmptyDatabaseSchemaCache() - return try block(db) + return try db.withSchemaCache(EmptyDatabaseSchemaCache()) { + try block(db) + } } } } @@ -467,7 +467,7 @@ extension DatabasePool: DatabaseReader { releaseReader() } do { - try db.beginSnapshotIsolation() + try db.beginSnapshotTransaction() } catch { futureResult = .failure(error) isolationSemaphore.signal() @@ -571,7 +571,7 @@ extension DatabasePool: DatabaseReader { releaseReader() } do { - try db.beginSnapshotIsolation() + try db.beginSnapshotTransaction() } catch { isolationSemaphore.signal() block(.failure(error)) @@ -582,10 +582,10 @@ extension DatabasePool: DatabaseReader { isolationSemaphore.signal() // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - - // Fetch and release the future - block(.success(db)) + db.withSchemaCache(SimpleDatabaseSchemaCache()) { + // Fetch and release the future + block(.success(db)) + } } } catch { isolationSemaphore.signal() @@ -869,7 +869,7 @@ extension DatabasePool { path: path, configuration: writer.configuration, defaultLabel: "GRDB.DatabasePool", - purpose: "snapshot.\(snapshotCount.increment())") + purpose: "snapshot.\(databaseSnapshotCount.increment())") snapshot.read { setupDatabase($0) } return snapshot } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 793c82f4b..9a739e2ff 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -184,27 +184,17 @@ extension DatabaseRegion { return true } - if tableRegions.count == 1 { - // Fast path when the region contains a single table. - // - // We can apply the precondition: due to the filtering of events - // performed in observes(eventsOfKind:), the event argument is - // guaranteed to be about the fetched table. We thus only have to - // check for rowIds. - assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check in debug mode - let tableRegion = tableRegions[tableRegions.startIndex].value - return tableRegion.contains(rowID: event.rowID) - } else { - // 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:) - """) - } - return tableRegion.contains(rowID: event.rowID) + guard let tableRegion = tableRegions[event.tableName] else { + // FTS4 (and maybe other virtual tables) perform unadvertised + // changes. For example, an "INSERT INTO document ..." statement + // advertises an insertion in the `document` table, but the + // actual change events happen in the `document_content` shadow + // table. When such a non-advertised event happens, assume that + // the region is modified. + // See https://github.com/groue/GRDB.swift/issues/620 + return true } + return tableRegion.contains(rowID: event.rowID) } } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 094423cf2..77acfe18b 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -32,7 +32,7 @@ public class DatabaseSnapshot: DatabaseReader { guard journalMode == "wal" else { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } - try db.beginSnapshotIsolation() + try db.beginSnapshotTransaction() } } @@ -80,18 +80,14 @@ extension DatabaseSnapshot { } #endif - /// Alias for `read`. See `DatabaseReader.unsafeRead`. - /// /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { return try serializedDatabase.sync(block) } - /// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`. - /// /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - return try serializedDatabase.sync(block) + return try serializedDatabase.reentrantSync(block) } // MARK: - Functions diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index d0328e5af..e1c4d3ad1 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -21,16 +21,8 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// /// let rows = try Row.fetchCursor(db, sql: "SELECT ...") /// let players = try Player.fetchAll(db, sql: "SELECT ...") - /// - /// This row keeps an unmanaged reference to the statement, and a handle to - /// the sqlite statement, so that we avoid many retain/release invocations. - /// - /// The statementRef is released in deinit. - let statementRef: Unmanaged? + @usableFromInline let statement: SelectStatement? @usableFromInline let sqliteStatement: SQLiteStatement? - var statement: SelectStatement? { - return statementRef?.takeUnretainedValue() - } /// The number of columns in the row. public let count: Int @@ -96,10 +88,6 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, return impl.isFetched } - deinit { - statementRef?.release() - } - /// Creates a row that maps an SQLite statement. Further calls to /// sqlite3_step() modify the row. /// @@ -107,18 +95,17 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// access to the SQLite statement. Iteration of the statement does modify /// the row. init(statement: SelectStatement) { - let statementRef = Unmanaged.passRetained(statement) // released in deinit - self.statementRef = statementRef + self.statement = statement self.sqliteStatement = statement.sqliteStatement - self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statementRef: statementRef) + self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement) self.count = Int(sqlite3_column_count(sqliteStatement)) } /// Creates a row that maps an SQLite statement. Further calls to /// sqlite3_step() modify the row. init(sqliteStatement: SQLiteStatement) { + self.statement = nil self.sqliteStatement = sqliteStatement - self.statementRef = nil self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement) self.count = Int(sqlite3_column_count(sqliteStatement)) } @@ -131,18 +118,18 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// statement does not modify the row. convenience init( copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, - statementRef: Unmanaged) + statement: SelectStatement) { self.init(impl: StatementCopyRowImpl( sqliteStatement: sqliteStatement, - columnNames: statementRef.takeUnretainedValue().columnNames)) + columnNames: statement.columnNames)) } init(impl: RowImpl) { + self.statement = nil + self.sqliteStatement = nil self.impl = impl self.count = impl.count - self.statementRef = nil - self.sqliteStatement = nil } } @@ -1750,12 +1737,12 @@ private struct StatementCopyRowImpl: RowImpl { /// See Row.init(statement:) private struct StatementRowImpl: RowImpl { - let statementRef: Unmanaged + let statement: SelectStatement let sqliteStatement: SQLiteStatement let lowercaseColumnIndexes: [String: Int] - init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged) { - self.statementRef = statementRef + init(sqliteStatement: SQLiteStatement, statement: SelectStatement) { + self.statement = statement self.sqliteStatement = sqliteStatement // Optimize row[columnName] let lowercaseColumnNames = (0.. String { - return statementRef.takeUnretainedValue().columnNames[index] + return statement.columnNames[index] } func index(ofColumn name: String) -> Int? { @@ -1821,7 +1808,7 @@ private struct StatementRowImpl: RowImpl { } func copiedRow(_ row: Row) -> Row { - return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef) + return Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement) } } @@ -1839,6 +1826,17 @@ private struct SQLiteStatementRowImpl: RowImpl { return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) } + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { + guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + return nil + } + guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + return Data() + } + let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) + } + func index(ofColumn name: String) -> Int? { let name = name.lowercased() for index in 0..?) -> Int32 { - // print(""" - // StatementCompilationAuthorizer: \ - // \(actionCode) \ - // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) - // """) +// print(""" +// StatementCompilationAuthorizer: \ +// \(AuthorizerActionCode(rawValue: actionCode)) \ +// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) +// """) switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, @@ -181,11 +181,58 @@ final class TruncateOptimizationBlocker: StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print(""" - // TruncateOptimizationBlocker: \ - // \(actionCode) \ - // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) - // """) +// print(""" +// TruncateOptimizationBlocker: \ +// \(AuthorizerActionCode(rawValue: actionCode)) \ +// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) +// """) return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK } } + +private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible { + let rawValue: Int32 + init(rawValue: Int32) { + self.rawValue = rawValue + } + + var description: String { + switch rawValue { + case 1: return "SQLITE_CREATE_INDEX" + case 2: return "SQLITE_CREATE_TABLE" + case 3: return "SQLITE_CREATE_TEMP_INDEX" + case 4: return "SQLITE_CREATE_TEMP_TABLE" + case 5: return "SQLITE_CREATE_TEMP_TRIGGER" + case 6: return "SQLITE_CREATE_TEMP_VIEW" + case 7: return "SQLITE_CREATE_TRIGGER" + case 8: return "SQLITE_CREATE_VIEW" + case 9: return "SQLITE_DELETE" + case 10: return "SQLITE_DROP_INDEX" + case 11: return "SQLITE_DROP_TABLE" + case 12: return "SQLITE_DROP_TEMP_INDEX" + case 13: return "SQLITE_DROP_TEMP_TABLE" + case 14: return "SQLITE_DROP_TEMP_TRIGGER" + case 15: return "SQLITE_DROP_TEMP_VIEW" + case 16: return "SQLITE_DROP_TRIGGER" + case 17: return "SQLITE_DROP_VIEW" + case 18: return "SQLITE_INSERT" + case 19: return "SQLITE_PRAGMA" + case 20: return "SQLITE_READ" + case 21: return "SQLITE_SELECT" + case 22: return "SQLITE_TRANSACTION" + case 23: return "SQLITE_UPDATE" + case 24: return "SQLITE_ATTACH" + case 25: return "SQLITE_DETACH" + case 26: return "SQLITE_ALTER_TABLE" + case 27: return "SQLITE_REINDEX" + case 28: return "SQLITE_ANALYZE" + case 29: return "SQLITE_CREATE_VTABLE" + case 30: return "SQLITE_DROP_VTABLE" + case 31: return "SQLITE_FUNCTION" + case 32: return "SQLITE_SAVEPOINT" + case 0: return "SQLITE_COPY" + case 33: return "SQLITE_RECURSIVE" + default: return "\(rawValue)" + } + } +} diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 13cd61a2e..8ecb9dc5b 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -283,7 +283,11 @@ class DatabaseObservationBroker { // observation will only be notified of individual events that // match one of the observed kinds. - return (observation, DatabaseEventPredicate.matching(observedKinds)) + return ( + observation, + DatabaseEventPredicate.matching( + observedKinds: observedKinds, + advertisedKinds: eventKinds)) } } @@ -336,7 +340,8 @@ class DatabaseObservationBroker { // BEGIN DEFERRED TRANSACTION; COMMIT // // This special case has a dedicated handling: - return try databaseDidCommitEmptyDeferredTransaction() + try databaseDidCommitEmptyDeferredTransaction() + return } case .rollbackTransaction: @@ -356,7 +361,8 @@ class DatabaseObservationBroker { // SAVEPOINT foo; RELEASE SAVEPOINT foo // // This special case has a dedicated handling: - return try databaseDidCommitEmptyDeferredTransaction() + try databaseDidCommitEmptyDeferredTransaction() + return } if savepointStack.isEmpty { @@ -729,7 +735,6 @@ public protocol TransactionObserver: AnyObject { /// /// The databaseDidChangeWithEvent callback is always available, /// and may provide most/all of what you need. - /// (For example, FetchedRecordsController is built without databaseWillChange) func databaseWillChange(with event: DatabasePreUpdateEvent) #endif } @@ -1312,15 +1317,28 @@ private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { enum DatabaseEventPredicate { // Yes filter case `true` - // Only events that match one of those kinds - case matching([DatabaseEventKind]) + // Only events that match observedKinds + case matching(observedKinds: [DatabaseEventKind], advertisedKinds: [DatabaseEventKind]) func evaluate(_ event: DatabaseEventProtocol) -> Bool { switch self { case .true: return true - case .matching(let kinds): - return kinds.contains { event.matchesKind($0) } + case let .matching(observedKinds: observedKinds, advertisedKinds: advertisedKinds): + if observedKinds.contains(where: { event.matchesKind($0) }) { + return true + } + if !advertisedKinds.contains(where: { event.matchesKind($0) }) { + // FTS4 (and maybe other virtual tables) perform unadvertised + // changes. For example, an "INSERT INTO document ..." statement + // advertises an insertion in the `document` table, but the + // actual change events happen in the `document_content` shadow + // table. When such a non-advertised event happens, assume that + // the event has to be notified. + // See https://github.com/groue/GRDB.swift/issues/620 + return true + } + return false } } } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 70520ce1b..bb6867c56 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -176,9 +176,11 @@ public struct DatabaseMigrator { /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { if eraseDatabaseOnSchemaChange { - let witness = try DatabaseQueue(path: "") + // Create a temporary witness database, on disk, just in case + // migrations would involve a lot of data. + let witness = try DatabaseQueue(path: "", configuration: writer.configuration) - // Erase database if we detect a change in the *current* schema. + // Erase database if we detect a change in the current schema. let (currentIdentifier, currentSchema) = try writer.writeWithoutTransaction { db -> (String?, SchemaInfo) in try setupMigrations(db) let identifiers = try appliedIdentifiers(db) @@ -188,6 +190,7 @@ public struct DatabaseMigrator { .identifier return try (currentIdentifier, db.schema()) } + if let currentIdentifier = currentIdentifier { let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in try setupMigrations(db) @@ -199,33 +202,12 @@ public struct DatabaseMigrator { try writer.erase() } } - - // Migrate to *target* schema - let schema: SchemaInfo = try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - return try db.schema() - } - - // Erase database if we detect a change in the *target* schema. - let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - return try db.schema() - } - - if schema != witnessSchema { - try writer.erase() - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - } - } - } else { - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - } + } + + // Migrate to target schema + try writer.writeWithoutTransaction { db in + try setupMigrations(db) + try runMigrations(db, upTo: targetIdentifier) } } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index e8dd673cd..5381b922a 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -921,7 +921,7 @@ private struct InsertQuery: Hashable { } extension InsertQuery { - static let sqlCache = ReadWriteBox([InsertQuery: String]()) + static let sqlCache = ReadWriteBox(value: [InsertQuery: String]()) var sql: String { if let sql = InsertQuery.sqlCache.read({ $0[self] }) { return sql @@ -958,7 +958,7 @@ private struct UpdateQuery: Hashable { } extension UpdateQuery { - static let sqlCache = ReadWriteBox([UpdateQuery: String]()) + static let sqlCache = ReadWriteBox(value: [UpdateQuery: String]()) var sql: String { if let sql = UpdateQuery.sqlCache.read({ $0[self] }) { return sql diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift new file mode 100644 index 000000000..84ea6435b --- /dev/null +++ b/GRDB/Utils/LockedBox.swift @@ -0,0 +1,46 @@ +import Foundation + +/// A LockedBox protects a value with an NSLock. +final class LockedBox { + private var _value: T + private var lock = NSLock() + + var value: T { + get { return read { $0 } } + set { write { $0 = newValue } } + } + + init(value: T) { + _value = value + } + + func read(_ block: (T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try block(_value) + } + + func write(_ block: (inout T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try block(&_value) + } +} + +extension LockedBox where T: Numeric { + @discardableResult + func increment() -> T { + return write { n in + n += 1 + return n + } + } + + @discardableResult + func decrement() -> T { + return write { n in + n -= 1 + return n + } + } +} diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index b4555a289..bf5894814 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -47,7 +47,7 @@ final class Pool { } private let makeElement: () throws -> T - private var items: ReadWriteBox<[Item]> = ReadWriteBox([]) + private var items: ReadWriteBox<[Item]> = ReadWriteBox(value: []) private let itemsSemaphore: DispatchSemaphore // limits the number of elements private let itemsGroup: DispatchGroup // knows when no element is used private let barrierQueue: DispatchQueue diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift index b7c0b4449..1e11f2ea7 100644 --- a/GRDB/Utils/ReadWriteBox.swift +++ b/GRDB/Utils/ReadWriteBox.swift @@ -2,12 +2,15 @@ import Dispatch /// A ReadWriteBox grants multiple readers and single-writer guarantees on a value. final class ReadWriteBox { + private var _value: T + private var queue: DispatchQueue + var value: T { get { return read { $0 } } set { write { $0 = newValue } } } - init(_ value: T) { + init(value: T) { _value = value queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent]) } @@ -23,9 +26,6 @@ final class ReadWriteBox { try block(&_value) } } - - private var _value: T - private var queue: DispatchQueue } extension ReadWriteBox where T: Numeric { @@ -36,4 +36,12 @@ extension ReadWriteBox where T: Numeric { return n } } + + @discardableResult + func decrement() -> T { + return write { n in + n -= 1 + return n + } + } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index cfff7548f..9f6a4b1ee 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -279,6 +279,8 @@ 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; + 566BE7162342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; @@ -875,6 +877,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; @@ -1453,6 +1456,7 @@ 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */, 563EF44C2161F196007DAACD /* Inflections.swift */, 569BBA4B229170B300478429 /* Inflections+English.swift */, + 566BE7132342541F00A8254B /* LockedBox.swift */, 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */, @@ -1978,7 +1982,7 @@ }; F3BA80591CFB2BB2003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 1020; + LastSwiftMigration = 1110; }; F3BA809A1CFB2F6F003DC1BA = { CreatedOnToolsVersion = 7.3.1; @@ -2224,6 +2228,7 @@ 5690C3451D23E82A00E59934 /* Data.swift in Sources */, 5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86E2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, + 566BE7162342541F00A8254B /* LockedBox.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, @@ -2558,6 +2563,7 @@ 5690C3421D23E82A00E59934 /* Data.swift in Sources */, 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86D2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, + 566BE7152342541F00A8254B /* LockedBox.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme index fb8c9c1a0..3a409e265 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme @@ -1,6 +1,6 @@ + shouldUseLaunchSchemeArgsEnv = "YES" + codeCoverageEnabled = "YES"> + + + + @@ -54,17 +63,6 @@ - - - - - - - - + shouldUseLaunchSchemeArgsEnv = "YES" + codeCoverageEnabled = "YES"> + + + + @@ -54,17 +63,6 @@ - - - - - - - - 'MIT', :file => 'LICENSE' } - s.summary = 'A toolkit for SQLite databases, with a focus on application development.' - s.homepage = 'https://github.com/groue/GRDB.swift' - s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } - s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } - s.module_name = 'GRDB' - - s.ios.deployment_target = '11.4' - s.osx.deployment_target = '10.13' - s.watchos.deployment_target = '4.3' - - s.source_files = 'GRDB/**/*.swift', 'Support/*.h' - s.module_map = 'Support/module.modulemap' - s.framework = 'Foundation' - s.library = 'sqlite3' - - s.xcconfig = { - 'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5', - } -end diff --git a/Makefile b/Makefile index 8173db078..7752555fd 100644 --- a/Makefile +++ b/Makefile @@ -49,13 +49,27 @@ endif TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with `instruments -s devices` -ifeq ($(XCODEVERSION),10.3) +ifeq ($(XCODEVERSION),11.1) + MAX_SWIFT_VERSION = 5.1 + MIN_SWIFT_VERSION = 4.2 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.1" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1" + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.0" + MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" +else ifeq ($(XCODEVERSION),11.0) + MAX_SWIFT_VERSION = 5.1 + MIN_SWIFT_VERSION = 4.2 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.0" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1" + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.0" + MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" +else ifeq ($(XCODEVERSION),10.3) MAX_SWIFT_VERSION = 5 MIN_SWIFT_VERSION = 4.2 MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone X,OS=12.4" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=12.4" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.0" + MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" else ifeq ($(XCODEVERSION),10.2) MAX_SWIFT_VERSION = 5 MIN_SWIFT_VERSION = 4.2 @@ -116,29 +130,29 @@ test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framew test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBWatchOS test_framework_GRDBiOS test_framework_GRDBtvOS test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher4 -test_install: test_install_manual test_install_SPM test_install_GRDB_CocoaPods test_CocoaPodsLint +test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint test_CocoaPodsLint: test_CocoaPodsLint_GRDB test_framework_GRDBOSX: test_framework_GRDBOSX_maxSwift test_framework_GRDBOSX_minSwift test_framework_GRDBOSX_maxSwift: - # SQLITE_ENABLE_FTS5 requires macOS 10.13+ $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBOSX \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5' \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) test_framework_GRDBOSX_minSwift: ifdef MIN_SWIFT_VERSION - # SQLITE_ENABLE_FTS5 requires macOS 10.13+ $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBOSX \ SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5' \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) endif @@ -156,25 +170,25 @@ test_framework_GRDBiOS: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_ test_framework_GRDBiOS_maxTarget: test_framework_GRDBiOS_maxTarget_maxSwift test_framework_GRDBiOS_maxTarget_minSwift test_framework_GRDBiOS_maxTarget_maxSwift: - # SQLITE_ENABLE_FTS5 requires iOS 11.4+ $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBiOS \ -destination $(MAX_IOS_DESTINATION) \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5' \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) test_framework_GRDBiOS_maxTarget_minSwift: ifdef MIN_SWIFT_VERSION - # SQLITE_ENABLE_FTS5 requires iOS 11.4+ $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBiOS \ -destination $(MAX_IOS_DESTINATION) \ SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5' \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) endif @@ -192,25 +206,25 @@ test_framework_GRDBtvOS: test_framework_GRDBtvOS_maxTarget test_framework_GRDBtv test_framework_GRDBtvOS_maxTarget: test_framework_GRDBtvOS_maxTarget_maxSwift test_framework_GRDBtvOS_maxTarget_minSwift test_framework_GRDBtvOS_maxTarget_maxSwift: - # SQLITE_ENABLE_FTS5 requires iOS 11.4+ $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBtvOS \ -destination $(MAX_TVOS_DESTINATION) \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5' \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) test_framework_GRDBtvOS_maxTarget_minSwift: ifdef MIN_SWIFT_VERSION - # SQLITE_ENABLE_FTS5 requires iOS 11.4+ $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBtvOS \ -destination $(MAX_TVOS_DESTINATION) \ SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5' \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ $(TEST_ACTIONS) \ $(XCPRETTY) endif @@ -303,24 +317,42 @@ test_SPM: test_install_manual: $(XCODEBUILD) \ - -project DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ + -project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ -scheme GRDBDemoiOS \ -configuration Release \ -destination $(MAX_IOS_DESTINATION) \ clean build \ $(XCPRETTY) -test_install_SPM: - cd Tests/SPM && \ +test_install_SPM: test_install_SPM_Package test_install_SPM_Project + +test_install_SPM_Package: + cd Tests/SPM/PlainPackage && \ ( if [ -a .build ] && [ -a Package.resolved ]; then $(SWIFT) package reset; fi ) && \ rm -rf Packages/GRDB && \ $(SWIFT) package edit GRDB --revision master && \ rm -rf Packages/GRDB && \ - ln -s ../../.. Packages/GRDB && \ + ln -s ../../../.. Packages/GRDB && \ $(SWIFT) build && \ ./.build/debug/SPM && \ $(SWIFT) package unedit --force GRDB +test_install_SPM_Project: + $(XCODEBUILD) \ + -project Tests/SPM/PlainProject/Plain.xcodeproj \ + -scheme Plain \ + -configuration Release \ + clean build \ + $(XCPRETTY) + +test_install_customSQLite: SQLiteCustom + $(XCODEBUILD) \ + -project Tests/CustomSQLite/CustomSQLite.xcodeproj \ + -scheme CustomSQLite \ + -configuration Release \ + clean build \ + $(XCPRETTY) + test_install_GRDB_CocoaPods: test_install_GRDB_CocoaPods_framework test_install_GRDB_CocoaPods_static test_install_GRDB_CocoaPods_framework: @@ -388,8 +420,7 @@ SQLite.swift: Tests/Performance/SQLite.swift/SQLite.xcodeproj Tests/Performance/SQLite.swift/SQLite.xcodeproj: $(GIT) submodule update --init Tests/Performance/SQLite.swift -# Target that setups SQLite custom builds with SQLITE_ENABLE_PREUPDATE_HOOK and -# SQLITE_ENABLE_FTS5 extra compilation options. +# Target that setups SQLite custom builds with extra compilation options. SQLiteCustom: SQLiteCustom/src/sqlite3.h echo '/* Makefile generated */' > SQLiteCustom/GRDBCustomSQLite-USER.h echo '#define SQLITE_ENABLE_PREUPDATE_HOOK' >> SQLiteCustom/GRDBCustomSQLite-USER.h @@ -414,10 +445,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.4.0 \ - --module-version 4.4.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.5.0 \ + --module-version 4.5.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/4.4/ \ + --root-url http://groue.github.io/GRDB.swift/docs/4.5/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/Package.swift b/Package.swift index a7589da8d..059db4753 100644 --- a/Package.swift +++ b/Package.swift @@ -9,19 +9,25 @@ let package = Package( .library(name: "GRDB", targets: ["GRDB"]), ], dependencies: [ - .package(url: "https://github.com/groue/CSQLite.git", from: "0.2.0"), ], targets: [ - .target(name: "GRDB", path: "GRDB"), + .systemLibrary( + name: "sqlite3", + providers: [.apt(["libsqlite3-dev"])]), + .target( + name: "GRDB", + dependencies: ["sqlite3"], + path: "GRDB"), .testTarget( name: "GRDBTests", dependencies: ["GRDB"], path: "Tests", exclude: [ "CocoaPods", + "CustomSQLite", "Crash", "Performance", - "SPM" + "SPM", ]) ], swiftLanguageVersions: [.v4_2, .version("5")] diff --git a/README.md b/README.md index 732313930..1709340b3 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,14 @@ GRDB 4 [![Swift 4.2](https://img.shields.io/badge/swift-4.2-orange.svg?style=fla --- -**Latest release**: September 6, 2019 • version 4.4.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) +**Latest release**: October 15, 2019 • version 4.5.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) **Requirements**: iOS 9.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+ • Swift 4.2+ / Xcode 10.0+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 5** | **v4.4.0** | -| **Swift 4.2** | **v4.4.0** | +| **Swift 5** | **v4.5.0** | +| **Swift 4.2** | **v4.5.0** | | Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) | | Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | @@ -256,7 +256,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -338,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.4.0")) + .package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.5.0")) ] ) ``` @@ -353,7 +353,7 @@ Note that Linux is not currently supported. ## Manually -1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.4.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.4.0` command. +1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.5.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.5.0` command. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -361,17 +361,17 @@ Note that Linux is not currently supported. 4. Add the `GRDB.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your application target (extension target for WatchOS). -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an example of such integration. +> :bulb: **Tip**: see the [Demo Application] for an example of such integration. Demo Application ================ -The repository comes with a [demo application](DemoApps/GRDBDemoiOS/README.md) that shows you: +The repository comes with a [Demo Application] that shows you: - how to setup a database in an iOS app - how to define a simple [Codable Record](#codable-records) -- how to track database changes with [ValueObservation] and [FetchedRecordsController]. +- how to track database changes with [ValueObservation]. Database Connections @@ -451,7 +451,7 @@ let newPlaceCount = try dbQueue.write { db -> Int in **A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample code that sets up a database queue on iOS. +> :bulb: **Tip**: see the [Demo Application] for a sample code that sets up a database queue on iOS. ### DatabaseQueue Configuration @@ -468,7 +468,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.4/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.5/Structs/Configuration.html) for more details. ## Database Pools @@ -531,7 +531,7 @@ let newPlaceCount = try dbPool.write { db -> Int in **A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency](#concurrency) chapter for more details about database pools, how they differ from database queues, and advanced use cases. -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool. +> :bulb: **Tip**: see the [Demo Application] for a sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool. ### DatabasePool Configuration @@ -549,7 +549,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.4/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.5/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -609,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.4/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.5/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. @@ -810,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.4/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.5/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 @@ -892,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.4/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.5/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: @@ -1175,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.4/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1476,7 +1476,7 @@ GRDB generally opens transactions for you, as a way to enforce its [concurrency // INSERT INTO debit ... // COMMIT try dbQueue.write { db in - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } @@ -1485,7 +1485,7 @@ try dbQueue.write { db in // INSERT INTO debit ... // COMMIT try dbPool.write { db in - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } ``` @@ -1501,14 +1501,14 @@ Yet you may need to exactly control when transactions take place: // INSERT INTO credit ... // INSERT INTO debit ... try dbQueue.inDatabase { db in - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } // INSERT INTO credit ... // INSERT INTO debit ... try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } ``` @@ -1520,7 +1520,7 @@ try dbPool.writeWithoutTransaction { db in ```swift // UNSAFE DATABASE INTEGRITY try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try Credit(destinationAccout, amount).insert(db) // may succeed + try Credit(destinationAccount, amount).insert(db) // may succeed try Debit(sourceAccount, amount).insert(db) // may fail } ``` @@ -1532,7 +1532,7 @@ try dbPool.writeWithoutTransaction { db in ```swift // UNSAFE CONCURRENCY try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) // <- Concurrent dbPool.read sees a partial db update here try Debit(sourceAccount, amount).insert(db) } @@ -1549,7 +1549,7 @@ To open explicit transactions, use one of the `Database.inTransaction`, `Databas // COMMIT try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction try db.inTransaction { - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) return .commit } @@ -1560,7 +1560,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction // INSERT INTO debit ... // COMMIT try dbQueue.inTransaction { db in // or dbPool.writeInTransaction - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) return .commit } @@ -1582,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.4/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.5/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1621,7 +1621,7 @@ func myCriticalMethod(_ db: Database) throws { try dbQueue.write { db in // Makes sure both inserts succeed, or none: try db.inSavepoint { - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) return .commit } @@ -1696,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.4/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.5/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1955,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.4/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.5/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). @@ -2121,7 +2121,7 @@ Extending structs with record protocols is more "swifty". Subclassing the Record > > :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. > -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses records. +> :bulb: **Tip**: see the [Demo Application] for a sample app that uses records. **Overview** @@ -2413,7 +2413,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.4/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.5/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()`. @@ -2720,7 +2720,7 @@ For more information about Codable records, see: - [The userInfo Dictionary] - [Tip: Derive Columns from Coding Keys](#tip-derive-columns-from-coding-keys) -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses Codable records. +> :bulb: **Tip**: see the [Demo Application] for a sample app that uses Codable records. ### JSON Columns @@ -2791,7 +2791,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.4/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.4/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.4/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.5/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). @@ -3066,7 +3066,7 @@ player.hasDatabaseChanges // true player.databaseChanges // ["score": 750] ``` -For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift). +For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [JSONSynchronization.playground](Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift). ## Record Customization Options @@ -3292,7 +3292,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu Since those use cases are not well handled by FetchableRecord, don't try to implement them on top of this protocol: you'll just fight the framework. -Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of [query interface requests](#requests) and generally all SQL generation features of the [TableRecord] and [PersistableRecord] protocols. +Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of [query interface requests](#requests) and generally all SQL generation features of the [TableRecord] and [PersistableRecord] protocols. ## Examples of Record Definitions @@ -3780,7 +3780,7 @@ SQLite itself has many reference documents about table creation: [CREATE TABLE]( try db.create(table: "example") { t in ... } // CREATE TEMPORARY TABLE example IF NOT EXISTS ( -try db.create(table: "example", temporary: true, ifNotExists: true) { t in +try db.create(table: "example", temporary: true, ifNotExists: true) { t in ... } ``` > :bulb: **Tip**: database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'. @@ -4134,7 +4134,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.4/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4667,7 +4667,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.4/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.5/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4711,7 +4711,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.4/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.5/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests @@ -5141,7 +5141,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.4/Structs/StatementArguments.html): +FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -5390,7 +5390,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.4/Structs/StatementArguments.html): +FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -5954,7 +5954,6 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas - [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. - [ValueObservation and DatabaseRegionObservation]: Automated tracking of database requests. -- [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [GRDBCombine]: Automated tracking of database changes, with [Combine](https://developer.apple.com/documentation/combine). - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). @@ -6132,7 +6131,7 @@ By default, an initial fetch is performed as soon as the observation starts: the The observer returned by the `start` method is stored in a property of the view controller. This allows the view controller to control the duration of the observation. When the observer is deallocated, the observation stops. Meanwhile, all transactions that modify the observed player are notified, and the `nameLabel` is kept up-to-date. -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses ValueObservation. +> :bulb: **Tip**: see the [Demo Application] for a sample app that uses ValueObservation. > > :bulb: **Tip**: When fetching values is slow, and should never ever block the main queue, opt in for async notifications: > @@ -6685,346 +6684,6 @@ dbQueue.remove(transactionObserver: observer) ``` -## FetchedRecordsController - -**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.** - -It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). - -Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. - -> :point_up: **Note**: when you don't need to animate a table or a collection view, use [ValueObservation], [GRDBCombine], or [RxGRDB] instead. -> -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses FetchedRecordsController. - -- [Creating the Fetched Records Controller](#creating-the-fetched-records-controller) -- [Responding to Changes](#responding-to-changes) -- [The Changes Notifications](#the-changes-notifications) -- [Modifying the Fetch Request](#modifying-the-fetch-request) -- [Table and Collection Views](#table-and-collection-views) - - [Implementing the Table View Datasource Methods](#implementing-the-table-view-datasource-methods) - - [Implementing Table View Updates](#implementing-table-view-updates) -- [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) - - -### Creating the Fetched Records Controller - -When you initialize a fetched records controller, you provide the following mandatory information: - -- A [database connection](#database-connections) -- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class -- A fetch request - -```swift -class Player : Record { ... } -let dbQueue = DatabaseQueue(...) // or DatabasePool - -// Using a Request from the Query Interface: -let controller = FetchedRecordsController( - dbQueue, - request: Player.order(Column("name"))) - -// Using SQL, and eventual arguments: -let controller = FetchedRecordsController( - dbQueue, - sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?", - arguments: ["FR"]) -``` - -The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request. - -```swift -let controller = FetchedRecordsController( - dbQueue, - sql: """ - SELECT author.name, COUNT(book.id) AS bookCount - FROM author - LEFT JOIN book ON book.authorId = author.id - GROUP BY author.id - ORDER BY author.name - """) -``` - - -After creating an instance, you invoke `performFetch()` to actually execute -the fetch. - -```swift -try controller.performFetch() -``` - - -### Responding to Changes - -In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values. - -Changes are not reflected until they are applied in the database by a successful [transaction](#transactions-and-savepoints): - -```swift -// One transaction -try dbQueue.write { db in // or dbPool.write - try player1.insert(db) - try player2.insert(db) -} - -// One transaction -try dbQueue.inTransaction { db in // or dbPool.writeInTransaction - try player1.insert(db) - try player2.insert(db) - return .commit -} - -// Two transactions -try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try player1.insert(db) - try player2.insert(db) -} -``` - -When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together. - - -### The Changes Notifications - -An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of *callbacks*: - -```swift -let controller = try FetchedRecordsController(...) - -controller.trackChanges( - // controller's records are about to change: - willChange: { controller in ... }, - - // notification of individual record changes: - onChange: { (controller, record, change) in ... }, - - // controller's records have changed: - didChange: { controller in ... }) - -try controller.performFetch() -``` - -See [Implementing Table View Updates](#implementing-table-view-updates) for more detail on table view updates. - -**All callbacks are optional.** When you only need to grab the latest results, you can omit the `didChange` argument name: - -```swift -controller.trackChanges { controller in - let newPlayers = controller.fetchedRecords // [Player] -} -``` - -> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. - -Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks: - -```swift -// BAD: memory leak -controller.trackChanges { _ in - let newPlayers = controller.fetchedRecords -} - -// GOOD -controller.trackChanges { controller in - let newPlayers = controller.fetchedRecords -} -``` - -**Callbacks are invoked asynchronously.** See [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) for more information. - -**Values fetched from inside callbacks may be inconsistent with the controller's records.** This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen. - -To avoid inconsistencies, provide a `fetchAlongside` argument to the `trackChanges` method, as below: - -```swift -controller.trackChanges( - fetchAlongside: { db in - // Fetch any extra value, for example the number of fetched records: - return try Player.fetchCount(db) - }, - didChange: { (controller, count) in - // The extra value is the second argument. - let recordsCount = controller.fetchedRecords.count - assert(count == recordsCount) // guaranteed - }) -``` - -Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch. - -```swift -controller.trackErrors { (controller, error) in - print("Missed a transaction because \(error)") -} -``` - - -### Modifying the Fetch Request - -You can change a fetched records controller's fetch request or SQL query. - -```swift -controller.setRequest(Player.order(Column("name"))) -controller.setRequest(sql: "SELECT ...", arguments: ...) -``` - -The [notification callbacks](#the-changes-notifications) are notified of eventual changes if the new request fetches a different set of records. - -> :point_up: **Note**: This behavior differs from Core Data's NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced. - -**Change callbacks are invoked asynchronously.** This means that modifying the request from the main thread does *not* immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called: - -```swift -// Change request on the main thread: -controller.setRequest(Player.order(Column("name"))) -// Here callbacks have not been called yet. -// You can cancel them, and refresh records immediately: -try controller.performFetch() -``` - -### Table and Collection Views - -FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content. - -For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key: - -```swift -class Player : TableRecord { ... } -let controller = FetchedRecordsController( - dbQueue, - request: Player.all()) -``` - -For other types, the fetched records controller needs you to be more explicit: - -```swift -let controller = FetchedRecordsController( - dbQueue, - request: ..., - isSameRecord: { (player1, player2) in player1.id == player2.id }) -``` - - -#### Implementing the Table View Datasource Methods - -The table view data source asks the fetched records controller to provide relevant information: - -```swift -func numberOfSections(in tableView: UITableView) -> Int { - return fetchedRecordsController.sections.count -} - -func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return fetchedRecordsController.sections[section].numberOfRecords -} - -func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = ... - let record = fetchedRecordsController.record(at: indexPath) - // Configure the cell - return cell -} -``` - -> :point_up: **Note**: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section. - - -#### Implementing Table View Updates - -When changes in the fetched records should reload the whole table view, you can simply tell so: - -```swift -controller.trackChanges { [unowned self] _ in - self.tableView.reloadData() -} -``` - -Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView. - - -##### Typical Table View Updates - -For animated table view updates, use the `willChange` and `didChange` callbacks to bracket events provided by the fetched records controller, as illustrated in the following example: - -```swift -// Assume self has a tableView property, and a cell configuration -// method named configure(_:at:). - -controller.trackChanges( - // controller's records are about to change: - willChange: { [unowned self] _ in - self.tableView.beginUpdates() - }, - - // notification of individual record changes: - onChange: { [unowned self] (controller, record, change) in - switch change { - case .insertion(let indexPath): - self.tableView.insertRows(at: [indexPath], with: .fade) - - case .deletion(let indexPath): - self.tableView.deleteRows(at: [indexPath], with: .fade) - - case .update(let indexPath, _): - if let cell = self.tableView.cellForRow(at: indexPath) { - self.configure(cell, at: indexPath) - } - - case .move(let indexPath, let newIndexPath, _): - self.tableView.deleteRows(at: [indexPath], with: .fade) - self.tableView.insertRows(at: [newIndexPath], with: .fade) - - // // Alternate technique which actually moves cells around: - // let cell = self.tableView.cellForRow(at: indexPath) - // self.tableView.moveRow(at: indexPath, to: newIndexPath) - // if let cell = cell { - // self.configure(cell, at: newIndexPath) - // } - } - }, - - // controller's records have changed: - didChange: { [unowned self] _ in - self.tableView.endUpdates() - }) -``` - -> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. -> -> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references. -> -> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses FetchedRecordsController to animate a table view. - - -### FetchedRecordsController Concurrency - -**A fetched records controller *can not* be used from any thread.** - -When the database itself can be read and modified from [any thread](#database-connections), fetched records controllers **must** be used from the main thread. Record changes are also [notified](#the-changes-notifications) on the main thread. - -**Change callbacks are invoked asynchronously.** This means that changes made from the main thread are *not* immediately notified. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called: - -```swift -// Change database on the main thread: -try dbQueue.write { db in - try Player(...).insert(db) -} -// Here callbacks have not been called yet. -// You can cancel them, and refresh records immediately: -try controller.performFetch() -``` - -> :point_up: **Note**: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well. -> -> ```swift -> let queue = DispatchQueue() -> queue.async { -> let controller = try FetchedRecordsController(..., queue: queue) -> controller.trackChanges { /* in queue */ } -> try controller.performFetch() -> } -> ``` - - ## TransactionObserver Protocol The `TransactionObserver` protocol lets you **observe individual database changes and transactions**: @@ -7149,7 +6808,7 @@ do { > :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. -[DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController], [GRDBCombine], and [RxGRDB] are all based on the TransactionObserver protocol. +[DatabaseRegionObservation], [ValueObservation], [GRDBCombine], and [RxGRDB] are all based on the TransactionObserver protocol. See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. @@ -7274,7 +6933,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.4/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.5/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. @@ -7284,7 +6943,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.4/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7304,7 +6963,7 @@ Use this protocol when you want to encapsulate your complex requests in a dedica ### Support for SQLite Pre-Update Hooks -A [custom SQLite build] can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: +When SQLite is built with the SQLITE_ENABLE_PREUPDATE_HOOK option, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: ```swift protocol TransactionObserverType : class { @@ -7320,6 +6979,32 @@ protocol TransactionObserverType : class { } ``` +This extra API can be activated in two ways: + +1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with SQLITE_ENABLE_PREUPDATE_HOOK support, but only on iOS 11.0+ (we don't know the minimum version of macOS, tvOS, watchOS): + + ```ruby + pod 'GRDB.swift' + platform :ios, '11.0' # or above + + post_install do |installer| + installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| + target.build_configurations.each do |config| + # Enable extra GRDB APIs + config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" + # Enable extra SQLite APIs + config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" + end + end + end + ``` + + > :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. + + > :point_up: **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that are lacking from the system `` header. When Xcode eventually ships with an SDK that includes a complete header, you may get a compiler error about duplicate function definitions. When this happens, just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option. + +2. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option. + Encryption ========== @@ -8025,7 +7710,7 @@ GRDB ships with three concurrency modes: > Database writes always happen in a unique serial dispatch queue, named the *writer protected dispatch queue*. -- :bowtie: **Guarantee 2: reads are always isolated**. This means that they are guaranteed an immutable view of the last committed state of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic: +- :bowtie: **Guarantee 2: reads are always isolated**. This means that they are guaranteed an immutable view of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic: ```swift try dbPool.read { db in // or dbQueue.read @@ -8047,7 +7732,7 @@ Those guarantees hold as long as you follow three rules: This means that opening a new connection each time you access the database is a bad idea. Do share a single connection instead. - See the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that sets up a single database queue that is available throughout the application. + See the [Demo Application] for a sample app that sets up a single database queue that is available throughout the application. If there are several instances of database queues or pools that write in the same database, a multi-threaded application will eventually face "database is locked" errors. See [Dealing with External Connections](#dealing-with-external-connections). @@ -8116,20 +7801,20 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY try dbPool.write { db in // or dbQueue.write - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } // SAFE CONCURRENCY try dbPool.writeInTransaction { db in // or dbQueue.inTransaction - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) try Debit(sourceAccount, amount).insert(db) return .commit } // UNSAFE CONCURRENCY try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccout, amount).insert(db) + try Credit(destinationAccount, amount).insert(db) // <- Concurrent dbPool.read sees a partial db update here try Debit(sourceAccount, amount).insert(db) } @@ -8253,7 +7938,7 @@ There is a known limitation: reads performed by [database snapshots](#database-s ### Database Snapshots -**A database snapshot sees an unchanging database content, as it existed at the moment it was created.** +**[Database pool](#database-pools) can take snapshots.** A database snapshot sees an unchanging database content, as it existed at the moment it was created. "Unchanging" means that a snapshot never sees any database modifications during all its lifetime. And yet it doesn't prevent database updates. This "magic" is made possible by SQLite's WAL mode (see [Isolation In SQLite](https://sqlite.org/isolation.html)). @@ -8280,7 +7965,7 @@ let playerCount = try snapshot.read { db in } ``` -When you want to control the latest committed changes seen by a snapshot, create it from the pool's writer protected dispatch queue, outside of any transaction: +When you want to control the latest committed changes seen by a snapshot, create the snapshot from the pool's writer protected dispatch queue, outside of any transaction: ```swift let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in @@ -8312,14 +7997,13 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.4/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.5/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: - [Migrations](#migrations) - [DatabaseRegionObservation] - [ValueObservation] -- [FetchedRecordsController] - [GRDBCombine] - [RxGRDB] @@ -8566,7 +8250,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.4/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.5/Structs/Configuration.html) - [Ask questions](https://github.com/groue/GRDB.swift/issues) @@ -9004,10 +8688,10 @@ Sample Code =========== - The [Documentation](#documentation) is full of GRDB snippets. -- [Demo Application](DemoApps/GRDBDemoiOS/README.md): A sample iOS application. +- [Demo Application]: A sample iOS application. - [WWDC Companion](https://github.com/groue/WWDCCompanion): A sample iOS application. - Check `GRDB.xcworkspace`: it contains GRDB-enabled playgrounds to play with. -- How to synchronize a database table with a JSON payload: [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift) +- How to synchronize a database table with a JSON payload: [JSONSynchronization.playground](Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift) --- @@ -9015,7 +8699,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), [@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. +- [@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), [@runhum](https://github.com/runhum), [@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. @@ -9026,6 +8710,10 @@ Legacy This chapter has been renamed [Record Comparison]. +#### FetchedRecordsController + +This chapter has [moved](Documentation/FetchedRecordsController.md). + #### Persistable Protocol This protocol has been renamed [PersistableRecord] in GRDB 3.0. @@ -9061,7 +8749,6 @@ This chapter has been renamed [Beyond FetchableRecord]. [TableRecord]: #tablerecord-protocol [ValueObservation]: #valueobservation [DatabaseRegionObservation]: #databaseregionobservation -[FetchedRecordsController]: #fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [GRDBCombine]: http://github.com/groue/GRDBCombine [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol @@ -9070,3 +8757,4 @@ This chapter has been renamed [Beyond FetchableRecord]. [SQL Interpolation]: Documentation/SQLInterpolation.md [custom SQLite build]: Documentation/CustomSQLiteBuilds.md [Combine]: https://developer.apple.com/documentation/combine +[Demo Application]: Documentation/DemoApps/GRDBDemoiOS/README.md diff --git a/SQLiteCustom/GRDB.xcconfig b/SQLiteCustom/GRDB.xcconfig index f4b7149a8..85a00ddb0 100755 --- a/SQLiteCustom/GRDB.xcconfig +++ b/SQLiteCustom/GRDB.xcconfig @@ -10,5 +10,6 @@ PRODUCT_NAME = GRDBCustomSQLite PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.$(PRODUCT_NAME:rfc1034identifier) MODULEMAP_FILE = $(SRCROOT)/SQLiteCustom/module.modulemap OTHER_CFLAGS = -DUSING_BUILTIN_SQLITE -DGRDBCUSTOMSQLITE $(CUSTOM_SQLLIBRARY_CFLAGS) +GCC_PREPROCESSOR_DEFINITIONS = "GRDBCUSTOMSQLITE=1" OTHER_SWIFT_FLAGS = -D USING_BUILTIN_SQLITE -D GRDBCUSTOMSQLITE $(CUSTOM_OTHER_SWIFT_FLAGS) HEADER_SEARCH_PATHS = $(SRCROOT)/SQLiteCustom/src diff --git a/Sources/sqlite3/module.modulemap b/Sources/sqlite3/module.modulemap new file mode 100644 index 000000000..3631b172b --- /dev/null +++ b/Sources/sqlite3/module.modulemap @@ -0,0 +1,5 @@ +module CSQLite { + header "shim.h" + link "sqlite3" + export * +} diff --git a/Sources/sqlite3/shim.h b/Sources/sqlite3/shim.h new file mode 100644 index 000000000..d018d2fce --- /dev/null +++ b/Sources/sqlite3/shim.h @@ -0,0 +1,9 @@ +#include + +typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); + +// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic +// function that can't be used from Swift. +static inline void registerErrorLogCallback(errorLogCallback callback) { + sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); +} diff --git a/Support/Info.plist b/Support/Info.plist index e60763efb..d3b05cd7f 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.4.0 + 4.5.0 CFBundleSignature ???? CFBundleVersion diff --git a/Support/grdb_config.h b/Support/grdb_config.h index 641560fe6..90e83eb5e 100644 --- a/Support/grdb_config.h +++ b/Support/grdb_config.h @@ -8,9 +8,7 @@ #include #endif #else - #if defined(GRDBCUSTOMSQLITE) - #include - #else + #if !defined(GRDBCUSTOMSQLITE) #include #endif #endif @@ -23,4 +21,25 @@ static inline void registerErrorLogCallback(errorLogCallback callback) { sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); } +// Expose APIs that are missing from system +#ifdef GRDB_SQLITE_ENABLE_PREUPDATE_HOOK +SQLITE_API void *sqlite3_preupdate_hook( + sqlite3 *db, + void(*xPreUpdate)( + void *pCtx, /* Copy of third arg to preupdate_hook() */ + sqlite3 *db, /* Database handle */ + int op, /* SQLITE_UPDATE, DELETE or INSERT */ + char const *zDb, /* Database name */ + char const *zName, /* Table name */ + sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ + ), + void* +); +SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); +SQLITE_API int sqlite3_preupdate_count(sqlite3 *); +SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); +SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); +#endif /* GRDB_SQLITE_ENABLE_PREUPDATE_HOOK */ + #endif /* grdb_config_h */ diff --git a/TODO.md b/TODO.md index 0e03453df..115af7b62 100644 --- a/TODO.md +++ b/TODO.md @@ -8,6 +8,19 @@ - [ ] https://github.com/groue/GRDB.swift/issues/514 - [ ] Test NOT TESTED methods - [ ] Cancellation of a started ValueObservation. Context: https://github.com/groue/GRDB.swift/issues/601#issuecomment-524733140 +- [ ] Test that one can force a JOIN with association aggregates: + + ```swift + // SELECT author.*, MAX(book.publishDate) AS maxBookPublishDate + // FROM author + // JOIN book ON book.authorId = author.id + // GROUP BY author.id + Author + .annotated(with: Author.books.max(Column("publishDate"))) + .joining(required: Author.books) + ``` + + It is important to have an explicit test for this technique because it is the only currently available that forces a JOIN, and we don't want to break it in the future, even if association aggregates change implementation eventually. ## Documentation @@ -17,6 +30,7 @@ ## Features +- [ ] Xcode 10.3 and Xcode 11 Travis tests - [ ] Alternative technique for custom SQLite builds: see the Podfile at https://github.com/CocoaPods/CocoaPods/issues/9104, and https://github.com/clemensg/sqlite3pod - [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool? - [ ] SQL Generation diff --git a/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift b/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift new file mode 100644 index 000000000..0ecb34814 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift @@ -0,0 +1,18 @@ +import GRDB +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { + // Test GRDB + _ = DatabaseQueue() + + // test SQLITE_ENABLE_FTS5 + _ = FTS5.self + + // test_SQLITE_ENABLE_PREUPDATE_HOOK + _ = DatabasePreUpdateEvent.self + + return true + } +} diff --git a/Tests/CocoaPods/GRDBiOS-framework/Default-568h@2x.png b/Tests/CocoaPods/GRDBiOS-framework/Default-568h@2x.png new file mode 100644 index 000000000..0891b7aab Binary files /dev/null and b/Tests/CocoaPods/GRDBiOS-framework/Default-568h@2x.png differ diff --git a/Tests/CocoaPods/GRDBiOS-framework/Info.plist b/Tests/CocoaPods/GRDBiOS-framework/Info.plist new file mode 100644 index 000000000..fb4115c84 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-framework/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Tests/CocoaPods/GRDBiOS-framework/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile index 55aeffee7..39c9cbf52 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -3,3 +3,14 @@ target 'iOS' platform :ios, '9.0' supports_swift_versions '4.2' pod 'GRDB.swift', :path => '../../..' + +post_install do |installer| + installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| + target.build_configurations.each do |config| + # Enable extra GRDB APIs + config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK" + # Enable extra SQLite APIs + config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" + end + end +end diff --git a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj index 458f4e78e..00a2476ac 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj @@ -7,14 +7,8 @@ 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 */; }; + 56606CF02353353600185962 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56606CEF2353353600185962 /* AppDelegate.swift */; }; + 56606CF32353368800185962 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 56606CF22353368800185962 /* Default-568h@2x.png */; }; 905ECD161513DA7089DC0E4F /* Pods_iOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44319992BE6EA64810E8982A /* Pods_iOS.framework */; }; /* End PBXBuildFile section */ @@ -33,16 +27,10 @@ /* 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 = ""; }; - 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 = ""; }; + 56606CEF2353353600185962 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 56606CF12353357300185962 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 56606CF22353368800185962 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; 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 = ""; }; /* End PBXFileReference section */ @@ -62,7 +50,9 @@ 5673742F1B4D46600089DE44 = { isa = PBXGroup; children = ( - 5673743A1B4D46600089DE44 /* GRDBDemoiOS */, + 56606CEF2353353600185962 /* AppDelegate.swift */, + 56606CF22353368800185962 /* Default-568h@2x.png */, + 56606CF12353357300185962 /* Info.plist */, 567374391B4D46600089DE44 /* Products */, 9ABB37395508D35C98A292E7 /* Pods */, 8D9BFC4007F760CC8E01ACC6 /* Frameworks */, @@ -77,23 +67,6 @@ 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 = ( @@ -141,19 +114,19 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 0940; + LastUpgradeCheck = 1110; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 567374371B4D46600089DE44 = { CreatedOnToolsVersion = 7.0; DevelopmentTeam = AMD8W895CT; - LastSwiftMigration = 0940; + LastSwiftMigration = 1110; }; }; }; buildConfigurationList = 567374331B4D46600089DE44 /* Build configuration list for PBXProject "iOS" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, @@ -174,9 +147,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */, - 567374451B4D46600089DE44 /* Assets.xcassets in Resources */, - 567374431B4D46600089DE44 /* Main.storyboard in Resources */, + 56606CF32353368800185962 /* Default-568h@2x.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -226,40 +197,18 @@ 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 */, + 56606CF02353353600185962 /* AppDelegate.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_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -314,6 +263,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -362,13 +312,12 @@ 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; + INFOPLIST_FILE = Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -380,13 +329,12 @@ 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; + INFOPLIST_FILE = Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SWIFT_VERSION = 4.2; diff --git a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift b/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift new file mode 100644 index 000000000..0ecb34814 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift @@ -0,0 +1,18 @@ +import GRDB +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { + // Test GRDB + _ = DatabaseQueue() + + // test SQLITE_ENABLE_FTS5 + _ = FTS5.self + + // test_SQLITE_ENABLE_PREUPDATE_HOOK + _ = DatabasePreUpdateEvent.self + + return true + } +} diff --git a/Tests/CocoaPods/GRDBiOS-static/Default-568h@2x.png b/Tests/CocoaPods/GRDBiOS-static/Default-568h@2x.png new file mode 100644 index 000000000..0891b7aab Binary files /dev/null and b/Tests/CocoaPods/GRDBiOS-static/Default-568h@2x.png differ diff --git a/Tests/CocoaPods/GRDBiOS-static/Info.plist b/Tests/CocoaPods/GRDBiOS-static/Info.plist new file mode 100644 index 000000000..fb4115c84 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile index c20cb2f16..90f313d59 100644 --- a/Tests/CocoaPods/GRDBiOS-static/Podfile +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -2,3 +2,14 @@ target 'iOS' platform :ios, '9.0' supports_swift_versions '4.2' pod 'GRDB.swift', :path => '../../..' + +post_install do |installer| + installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| + target.build_configurations.each do |config| + # Enable extra GRDB APIs + config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK" + # Enable extra SQLite APIs + config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" + end + end +end diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj index a4c9947c5..295fbcddd 100644 --- a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj @@ -7,15 +7,9 @@ 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 */; }; + 33D0B66EF0B896F9E8391C5D /* libPods-iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D9232D362032D81EAFF2102C /* libPods-iOS.a */; }; + 56606CF02353353600185962 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56606CEF2353353600185962 /* AppDelegate.swift */; }; + 56606CF32353368800185962 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 56606CF22353368800185962 /* Default-568h@2x.png */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -32,19 +26,13 @@ /* 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 = ""; }; + 56606CEF2353353600185962 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 56606CF12353357300185962 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 56606CF22353368800185962 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; 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; }; + D9232D362032D81EAFF2102C /* libPods-iOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-iOS.a"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -52,7 +40,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - D246CFB4904D46E7D400E2CE /* libPods-iOS.a in Frameworks */, + 33D0B66EF0B896F9E8391C5D /* libPods-iOS.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -62,7 +50,9 @@ 5673742F1B4D46600089DE44 = { isa = PBXGroup; children = ( - 5673743A1B4D46600089DE44 /* GRDBDemoiOS */, + 56606CEF2353353600185962 /* AppDelegate.swift */, + 56606CF22353368800185962 /* Default-568h@2x.png */, + 56606CF12353357300185962 /* Info.plist */, 567374391B4D46600089DE44 /* Products */, 9ABB37395508D35C98A292E7 /* Pods */, 8D9BFC4007F760CC8E01ACC6 /* Frameworks */, @@ -77,27 +67,10 @@ 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 */, + D9232D362032D81EAFF2102C /* libPods-iOS.a */, ); name = Frameworks; sourceTree = ""; @@ -140,19 +113,19 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 0940; + LastUpgradeCheck = 1110; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 567374371B4D46600089DE44 = { CreatedOnToolsVersion = 7.0; DevelopmentTeam = AMD8W895CT; - LastSwiftMigration = 0940; + LastSwiftMigration = 1110; }; }; }; buildConfigurationList = 567374331B4D46600089DE44 /* Build configuration list for PBXProject "iOS" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, @@ -173,9 +146,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */, - 567374451B4D46600089DE44 /* Assets.xcassets in Resources */, - 567374431B4D46600089DE44 /* Main.storyboard in Resources */, + 56606CF32353368800185962 /* Default-568h@2x.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -207,40 +178,18 @@ 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 */, + 56606CF02353353600185962 /* AppDelegate.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_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -295,6 +244,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -343,13 +293,12 @@ 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; + INFOPLIST_FILE = Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -361,13 +310,12 @@ 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; + INFOPLIST_FILE = Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SWIFT_VERSION = 4.2; diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index f6bcec17c..5b6273c47 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -1560,10 +1560,11 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; - DEVELOPMENT_TEAM = AMD8W895CT; + DEVELOPMENT_TEAM = ""; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; @@ -1591,6 +1592,7 @@ ONLY_ACTIVE_ARCH = YES; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -1630,10 +1632,11 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEVELOPMENT_TEAM = AMD8W895CT; + DEVELOPMENT_TEAM = ""; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; @@ -1654,6 +1657,7 @@ MTL_FAST_MATH = YES; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; @@ -1693,10 +1697,11 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; - DEVELOPMENT_TEAM = AMD8W895CT; + DEVELOPMENT_TEAM = ""; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; @@ -1725,6 +1730,7 @@ OTHER_SWIFT_FLAGS = "$(inherited) -D GRDBCIPHER_USE_ENCRYPTION"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -1764,10 +1770,11 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEVELOPMENT_TEAM = AMD8W895CT; + DEVELOPMENT_TEAM = ""; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; @@ -1789,6 +1796,7 @@ OTHER_SWIFT_FLAGS = "$(inherited) -D GRDBCIPHER_USE_ENCRYPTION"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTests; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; diff --git a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj new file mode 100644 index 000000000..22267b748 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj @@ -0,0 +1,454 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 56F5F6C62349F11E00C4D9F7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F5F6C52349F11E00C4D9F7 /* AppDelegate.swift */; }; + 56F5F6C82349F11E00C4D9F7 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F5F6C72349F11E00C4D9F7 /* ViewController.swift */; }; + 56F5F6CA2349F11F00C4D9F7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56F5F6C92349F11F00C4D9F7 /* Assets.xcassets */; }; + 56F5F6CD2349F11F00C4D9F7 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56F5F6CB2349F11F00C4D9F7 /* Main.storyboard */; }; + 56F5F6E82349F26400C4D9F7 /* GRDBCustomSQLite.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56F5F6DE2349F22A00C4D9F7 /* GRDBCustomSQLite.framework */; }; + 56F5F6E92349F26500C4D9F7 /* GRDBCustomSQLite.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56F5F6DE2349F22A00C4D9F7 /* GRDBCustomSQLite.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 56F5F6DD2349F22A00C4D9F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA; + remoteInfo = GRDBCustomSQLiteOSX; + }; + 56F5F6DF2349F22A00C4D9F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA; + remoteInfo = GRDBCustomSQLiteOSXTests; + }; + 56F5F6E12349F22A00C4D9F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA; + remoteInfo = GRDBCustomSQLiteiOS; + }; + 56F5F6E32349F22A00C4D9F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA; + remoteInfo = GRDBCustomSQLiteiOSTests; + }; + 56F5F6E52349F24D00C4D9F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = F3BA80591CFB2BB2003DC1BA; + remoteInfo = GRDBCustomSQLiteOSX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 56F5F6EA2349F26500C4D9F7 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 56F5F6E92349F26500C4D9F7 /* GRDBCustomSQLite.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 56F5F6C22349F11E00C4D9F7 /* CustomSQLite.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CustomSQLite.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 56F5F6C52349F11E00C4D9F7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 56F5F6C72349F11E00C4D9F7 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 56F5F6C92349F11F00C4D9F7 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 56F5F6CC2349F11F00C4D9F7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 56F5F6CE2349F11F00C4D9F7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 56F5F6CF2349F11F00C4D9F7 /* CustomSQLite.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = CustomSQLite.entitlements; sourceTree = ""; }; + 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDBCustom.xcodeproj; path = ../../GRDBCustom.xcodeproj; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 56F5F6BF2349F11E00C4D9F7 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 56F5F6E82349F26400C4D9F7 /* GRDBCustomSQLite.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 56F5F6B92349F11E00C4D9F7 = { + isa = PBXGroup; + children = ( + 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */, + 56F5F6C42349F11E00C4D9F7 /* CustomSQLite */, + 56F5F6C32349F11E00C4D9F7 /* Products */, + 56F5F6E72349F26400C4D9F7 /* Frameworks */, + ); + sourceTree = ""; + }; + 56F5F6C32349F11E00C4D9F7 /* Products */ = { + isa = PBXGroup; + children = ( + 56F5F6C22349F11E00C4D9F7 /* CustomSQLite.app */, + ); + name = Products; + sourceTree = ""; + }; + 56F5F6C42349F11E00C4D9F7 /* CustomSQLite */ = { + isa = PBXGroup; + children = ( + 56F5F6C52349F11E00C4D9F7 /* AppDelegate.swift */, + 56F5F6C72349F11E00C4D9F7 /* ViewController.swift */, + 56F5F6C92349F11F00C4D9F7 /* Assets.xcassets */, + 56F5F6CB2349F11F00C4D9F7 /* Main.storyboard */, + 56F5F6CE2349F11F00C4D9F7 /* Info.plist */, + 56F5F6CF2349F11F00C4D9F7 /* CustomSQLite.entitlements */, + ); + path = CustomSQLite; + sourceTree = ""; + }; + 56F5F6D62349F22A00C4D9F7 /* Products */ = { + isa = PBXGroup; + children = ( + 56F5F6DE2349F22A00C4D9F7 /* GRDBCustomSQLite.framework */, + 56F5F6E02349F22A00C4D9F7 /* GRDBCustomSQLiteOSXTests.xctest */, + 56F5F6E22349F22A00C4D9F7 /* GRDBCustomSQLite.framework */, + 56F5F6E42349F22A00C4D9F7 /* GRDBCustomSQLiteiOSTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 56F5F6E72349F26400C4D9F7 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 56F5F6C12349F11E00C4D9F7 /* CustomSQLite */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56F5F6D22349F11F00C4D9F7 /* Build configuration list for PBXNativeTarget "CustomSQLite" */; + buildPhases = ( + 56F5F6BE2349F11E00C4D9F7 /* Sources */, + 56F5F6BF2349F11E00C4D9F7 /* Frameworks */, + 56F5F6C02349F11E00C4D9F7 /* Resources */, + 56F5F6EA2349F26500C4D9F7 /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 56F5F6E62349F24D00C4D9F7 /* PBXTargetDependency */, + ); + name = CustomSQLite; + productName = CustomSQLite; + productReference = 56F5F6C22349F11E00C4D9F7 /* CustomSQLite.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 56F5F6BA2349F11E00C4D9F7 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1110; + LastUpgradeCheck = 1110; + ORGANIZATIONNAME = "Gwendal Roué"; + TargetAttributes = { + 56F5F6C12349F11E00C4D9F7 = { + CreatedOnToolsVersion = 11.1; + LastSwiftMigration = 1110; + }; + }; + }; + buildConfigurationList = 56F5F6BD2349F11E00C4D9F7 /* Build configuration list for PBXProject "CustomSQLite" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 56F5F6B92349F11E00C4D9F7; + productRefGroup = 56F5F6C32349F11E00C4D9F7 /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 56F5F6D62349F22A00C4D9F7 /* Products */; + ProjectRef = 56F5F6D52349F22A00C4D9F7 /* GRDBCustom.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 56F5F6C12349F11E00C4D9F7 /* CustomSQLite */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 56F5F6DE2349F22A00C4D9F7 /* GRDBCustomSQLite.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = GRDBCustomSQLite.framework; + remoteRef = 56F5F6DD2349F22A00C4D9F7 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56F5F6E02349F22A00C4D9F7 /* GRDBCustomSQLiteOSXTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBCustomSQLiteOSXTests.xctest; + remoteRef = 56F5F6DF2349F22A00C4D9F7 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56F5F6E22349F22A00C4D9F7 /* GRDBCustomSQLite.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = GRDBCustomSQLite.framework; + remoteRef = 56F5F6E12349F22A00C4D9F7 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56F5F6E42349F22A00C4D9F7 /* GRDBCustomSQLiteiOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBCustomSQLiteiOSTests.xctest; + remoteRef = 56F5F6E32349F22A00C4D9F7 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 56F5F6C02349F11E00C4D9F7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 56F5F6CA2349F11F00C4D9F7 /* Assets.xcassets in Resources */, + 56F5F6CD2349F11F00C4D9F7 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 56F5F6BE2349F11E00C4D9F7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 56F5F6C82349F11E00C4D9F7 /* ViewController.swift in Sources */, + 56F5F6C62349F11E00C4D9F7 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 56F5F6E62349F24D00C4D9F7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GRDBCustomSQLiteOSX; + targetProxy = 56F5F6E52349F24D00C4D9F7 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 56F5F6CB2349F11F00C4D9F7 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 56F5F6CC2349F11F00C4D9F7 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 56F5F6D02349F11F00C4D9F7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = 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_DOCUMENTATION_COMMENTS = YES; + 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_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + 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; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 56F5F6D12349F11F00C4D9F7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = 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_DOCUMENTATION_COMMENTS = YES; + 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_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + 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; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 56F5F6D32349F11F00C4D9F7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = CustomSQLite/CustomSQLite.entitlements; + CODE_SIGN_IDENTITY = "-"; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = CustomSQLite/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.CustomSQLite; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + }; + name = Debug; + }; + 56F5F6D42349F11F00C4D9F7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = CustomSQLite/CustomSQLite.entitlements; + CODE_SIGN_IDENTITY = "-"; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = CustomSQLite/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.CustomSQLite; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 56F5F6BD2349F11E00C4D9F7 /* Build configuration list for PBXProject "CustomSQLite" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56F5F6D02349F11F00C4D9F7 /* Debug */, + 56F5F6D12349F11F00C4D9F7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 56F5F6D22349F11F00C4D9F7 /* Build configuration list for PBXNativeTarget "CustomSQLite" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56F5F6D32349F11F00C4D9F7 /* Debug */, + 56F5F6D42349F11F00C4D9F7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 56F5F6BA2349F11E00C4D9F7 /* Project object */; +} diff --git a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..8e5a412b4 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Tests/CustomSQLite/CustomSQLite.xcodeproj/xcshareddata/xcschemes/CustomSQLite.xcscheme b/Tests/CustomSQLite/CustomSQLite.xcodeproj/xcshareddata/xcschemes/CustomSQLite.xcscheme new file mode 100644 index 000000000..440df0bfc --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite.xcodeproj/xcshareddata/xcschemes/CustomSQLite.xcscheme @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift b/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift new file mode 100644 index 000000000..cf46e39ad --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift @@ -0,0 +1,11 @@ +import Cocoa +import GRDBCustomSQLite + +@NSApplicationMain +class AppDelegate: NSObject, NSApplicationDelegate { + func applicationDidFinishLaunching(_ aNotification: Notification) { + _ = DatabaseQueue() + _ = FTS5() + _ = sqlite3_preupdate_new(nil, 0, nil) + } +} diff --git a/Tests/CustomSQLite/CustomSQLite/Assets.xcassets/AppIcon.appiconset/Contents.json b/Tests/CustomSQLite/CustomSQLite/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..2db2b1c7c --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,58 @@ +{ + "images" : [ + { + "idiom" : "mac", + "size" : "16x16", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "16x16", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "32x32", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "32x32", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "128x128", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "128x128", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "256x256", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "256x256", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "512x512", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "512x512", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Tests/CustomSQLite/CustomSQLite/Assets.xcassets/Contents.json b/Tests/CustomSQLite/CustomSQLite/Assets.xcassets/Contents.json new file mode 100644 index 000000000..da4a164c9 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Tests/CustomSQLite/CustomSQLite/Base.lproj/Main.storyboard b/Tests/CustomSQLite/CustomSQLite/Base.lproj/Main.storyboard new file mode 100644 index 000000000..0876e47c1 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/Base.lproj/Main.storyboard @@ -0,0 +1,717 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Default + + + + + + + Left to Right + + + + + + + Right to Left + + + + + + + + + + + Default + + + + + + + Left to Right + + + + + + + Right to Left + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Tests/CustomSQLite/CustomSQLite/CustomSQLite.entitlements b/Tests/CustomSQLite/CustomSQLite/CustomSQLite.entitlements new file mode 100644 index 000000000..f2ef3ae02 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/CustomSQLite.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-only + + + diff --git a/Tests/CustomSQLite/CustomSQLite/Info.plist b/Tests/CustomSQLite/CustomSQLite/Info.plist new file mode 100644 index 000000000..6f85d07ad --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + Copyright © 2019 Gwendal Roué. All rights reserved. + NSMainStoryboardFile + Main + NSPrincipalClass + NSApplication + NSSupportsAutomaticTermination + + NSSupportsSuddenTermination + + + diff --git a/Tests/CustomSQLite/CustomSQLite/ViewController.swift b/Tests/CustomSQLite/CustomSQLite/ViewController.swift new file mode 100644 index 000000000..d44c61bd1 --- /dev/null +++ b/Tests/CustomSQLite/CustomSQLite/ViewController.swift @@ -0,0 +1,3 @@ +import Cocoa + +class ViewController: NSViewController { } diff --git a/Tests/CustomSQLite/GRDB b/Tests/CustomSQLite/GRDB new file mode 120000 index 000000000..c25bddb6d --- /dev/null +++ b/Tests/CustomSQLite/GRDB @@ -0,0 +1 @@ +../.. \ No newline at end of file diff --git a/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh b/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh new file mode 100644 index 000000000..eee74614a --- /dev/null +++ b/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh @@ -0,0 +1,43 @@ +# The path to the folder containing GRDBCustom.xcodeproj: +GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB" + +# The path to your custom "SQLiteLib-USER.xcconfig": +SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig" + +# The path to your custom "GRDBCustomSQLite-USER.xcconfig": +CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig" + +# The path to your custom "GRDBCustomSQLite-USER.h": +CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h" + +####################################################### +# +####################################################### + + +if [ ! -d "$GRDB_SOURCE_PATH" ]; +then +echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH" +exit 1 +fi + +SyncFileChanges () { + SOURCE=$1 + DESTINATIONPATH=$2 + DESTINATIONFILENAME=$3 + DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}" + + if [ ! -f "$SOURCE" ]; + then + echo "error: Source file missing: $SOURCE" + exit 1 + fi + + rsync -a "$SOURCE" "$DESTINATION" +} + +SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig" +SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig" +SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h" + +echo "Finished syncing" diff --git a/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-USER.h b/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-USER.h new file mode 100644 index 000000000..65fbe42c3 --- /dev/null +++ b/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-USER.h @@ -0,0 +1,2 @@ +#define SQLITE_ENABLE_FTS5 +#define SQLITE_ENABLE_PREUPDATE_HOOK diff --git a/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig b/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig new file mode 100644 index 000000000..3b5c52ca3 --- /dev/null +++ b/Tests/CustomSQLite/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig @@ -0,0 +1 @@ +CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK diff --git a/Tests/CustomSQLite/GRDBCustomSQLite/SQLiteLib-USER.xcconfig b/Tests/CustomSQLite/GRDBCustomSQLite/SQLiteLib-USER.xcconfig new file mode 100644 index 000000000..dfcfb0f11 --- /dev/null +++ b/Tests/CustomSQLite/GRDBCustomSQLite/SQLiteLib-USER.xcconfig @@ -0,0 +1 @@ +CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK diff --git a/Tests/GRDBTests/DatabaseLogErrorTests.swift b/Tests/GRDBTests/DatabaseLogErrorTests.swift index 1dfb7d00b..a3de93a20 100644 --- a/Tests/GRDBTests/DatabaseLogErrorTests.swift +++ b/Tests/GRDBTests/DatabaseLogErrorTests.swift @@ -8,6 +8,8 @@ import XCTest class DatabaseLogErrorTests: GRDBTestCase { func testErrorLog() throws { + // TODO: understand why this test fails on iOS 13 with system SQLite + #if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC let dbQueue = try makeDatabaseQueue() dbQueue.inDatabase { db in _ = try? db.execute(sql: "Abracadabra") @@ -16,5 +18,6 @@ class DatabaseLogErrorTests: GRDBTestCase { // Don't check for exact error message because it depends on SQLite version XCTAssert(lastMessage!.contains("syntax error")) XCTAssert(lastMessage!.contains("Abracadabra")) + #endif } } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 4c0b00059..30ca488a1 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -280,6 +280,55 @@ class DatabaseMigratorTests : GRDBTestCase { try XCTAssertEqual(migrator2.appliedMigrations(in: dbQueue), ["1", "2"]) } + func testEraseDatabaseOnSchemaChangeWithConfiguration() throws { + // 1st version of the migrator + var migrator1 = DatabaseMigrator() + migrator1.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player (id, name) VALUES (NULL, testFunction())") + } + + // 2nd version of the migrator + var migrator2 = DatabaseMigrator() + migrator2.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) // <- schema change, because reasons (development) + } + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, testFunction(), 1000)") + } + migrator2.registerMigration("2") { db in + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, testFunction(), 2000)") + } + + // Apply 1st migrator + dbConfiguration.prepareDatabase = { db in + let function = DatabaseFunction("testFunction", argumentCount: 0, pure: true) { _ in "Arthur" } + db.add(function: function) + } + let dbQueue = try makeDatabaseQueue() + try migrator1.migrate(dbQueue) + + // Test than 2nd migrator can't run... + do { + try migrator2.migrate(dbQueue) + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "table player has no column named score") + } + try XCTAssertEqual(migrator2.appliedMigrations(in: dbQueue), ["1"]) + + // ... unless databaase gets erased + migrator2.eraseDatabaseOnSchemaChange = true + try migrator2.migrate(dbQueue) + try XCTAssertEqual(migrator2.appliedMigrations(in: dbQueue), ["1", "2"]) + } + func testEraseDatabaseOnSchemaChangeDoesNotEraseDatabaseOnAddedMigration() throws { var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index c8fdd1850..34f02c91d 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -1,78 +1,116 @@ import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite +import GRDBCustomSQLite #else - import GRDB +import GRDB #endif class DatabaseReaderTests : GRDBTestCase { - func testDatabaseQueueReadPreventsDatabaseModification() throws { - // 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) - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 8.2, OSX 10.10, *) else { - return - } - #endif - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - } - do { - try dbQueue.read { try $0.execute(sql: "INSERT INTO table1 DEFAULT VALUES") } - XCTFail() - } catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY { - } - } - - func testDatabasePoolReadPreventsDatabaseModification() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - } - do { - try dbPool.read { try $0.execute(sql: "INSERT INTO table1 DEFAULT VALUES") } - XCTFail() - } catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY { - } - } - - func testDatabaseQueueUnsafeReentrantRead() throws { - let dbQueue = try makeDatabaseQueue() - dbQueue.unsafeReentrantRead { db1 in - dbQueue.unsafeReentrantRead { db2 in - dbQueue.unsafeReentrantRead { db3 in - XCTAssertTrue(db1 === db2) - XCTAssertTrue(db2 === db3) - } - } - } - } - - func testDatabasePoolUnsafeReentrantRead() throws { - let dbPool = try makeDatabasePool() - try dbPool.unsafeReentrantRead { db1 in - try dbPool.unsafeReentrantRead { db2 in - try dbPool.unsafeReentrantRead { db3 in - XCTAssertTrue(db1 === db2) - XCTAssertTrue(db2 === db3) - } - } - } - } - func testAnyDatabaseReader() { // This test passes if this code compiles. let reader: DatabaseReader = DatabaseQueue() let _: DatabaseReader = AnyDatabaseReader(reader) } + // MARK: - Read + + func testReadCanRead() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") + } + return dbWriter + } + func test(_ dbReader: DatabaseReader) throws { + let count = try dbReader.read { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") + } + XCTAssertEqual(count, 0) + } + + try test(setup(makeDatabaseQueue())) + try test(setup(makeDatabasePool())) + try test(setup(makeDatabasePool()).makeSnapshot()) + } + + func testReadPreventsDatabaseModification() throws { + func test(_ dbReader: DatabaseReader) throws { + do { + try dbReader.read { db in + try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") + } + XCTFail("Expected error") + } catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY { + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + try test(makeDatabasePool().makeSnapshot()) + } + + // MARK: - UnsafeRead + + func testUnsafeReadCanRead() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") + } + return dbWriter + } + func test(_ dbReader: DatabaseReader) throws { + let count = try dbReader.unsafeRead { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") + } + XCTAssertEqual(count, 0) + } + + try test(setup(makeDatabaseQueue())) + try test(setup(makeDatabasePool())) + try test(setup(makeDatabasePool()).makeSnapshot()) + } + + // MARK: - UnsafeReentrantRead + + func testUnsafeReentrantReadCanRead() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") + } + return dbWriter + } + func test(_ dbReader: DatabaseReader) throws { + let count = try dbReader.unsafeReentrantRead { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") + } + XCTAssertEqual(count, 0) + } + + try test(setup(makeDatabaseQueue())) + try test(setup(makeDatabasePool())) + try test(setup(makeDatabasePool()).makeSnapshot()) + } + + func testUnsafeReentrantReadIsReentrant() throws { + func test(_ dbReader: DatabaseReader) throws { + try dbReader.unsafeReentrantRead { db1 in + try dbReader.unsafeReentrantRead { db2 in + try dbReader.unsafeReentrantRead { db3 in + XCTAssertTrue(db1 === db2) + XCTAssertTrue(db2 === db3) + } + } + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + try test(makeDatabasePool().makeSnapshot()) + } + + // MARK: - AsyncRead + #if compiler(>=5.0) func testAsyncRead() throws { func test(_ dbReader: DatabaseReader) throws { @@ -128,4 +166,62 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabasePool().makeSnapshot()) } #endif + + // MARK: - Function + + func testAddFunction() throws { + func test(_ dbReader: DatabaseReader) throws { + let f = DatabaseFunction("f", argumentCount: 0, pure: true) { _ in 0 } + dbReader.add(function: f) + let value = try dbReader.read { db in + try Int.fetchOne(db, sql: "SELECT f()") + } + XCTAssertEqual(value, 0) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + try test(makeDatabasePool().makeSnapshot()) + } + + // MARK: - Collation + + func testAddCollation() throws { + func test(_ dbReader: DatabaseReader) throws { + let collation = DatabaseCollation("c") { _, _ in .orderedSame } + dbReader.add(collation: collation) + let value = try dbReader.read { db in + try Int.fetchOne(db, sql: "SELECT 'foo' AS str ORDER BY str COLLATE c") + } + XCTAssertEqual(value, 0) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + try test(makeDatabasePool().makeSnapshot()) + } + + // MARK: - Backup + + func testBackup() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") + } + return dbWriter + } + func test(_ source: DatabaseReader) throws { + let dest = try makeDatabaseQueue(configuration: Configuration()) + try source.backup(to: dest) + let count = try dest.read { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") + } + XCTAssertEqual(count, 0) + } + + // SQLCipher can't backup encrypted databases: use a pristine Configuration + try test(setup(makeDatabaseQueue(configuration: Configuration()))) + try test(setup(makeDatabasePool(configuration: Configuration()))) + try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) + } } diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index d5b3bbd57..03ac26cd0 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -1,62 +1,139 @@ import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite +@testable import GRDBCustomSQLite #else - import GRDB +@testable import GRDB #endif class DatabaseSnapshotTests: GRDBTestCase { + /// A helper class + private class Counter { + let dbPool: DatabasePool + init(dbPool: DatabasePool) throws { + self.dbPool = dbPool + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)") + } + } + + func increment(_ db: Database) throws { + try db.execute(sql: "INSERT INTO counter DEFAULT VALUES") + } + + func value(_ db: Database) throws -> Int { + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! + } + } + + // MARK: - Creation + + func testSnapshotCanReadBeforeDatabaseModification() throws { + let dbPool = try makeDatabasePool() + let snapshot = try dbPool.makeSnapshot() + try XCTAssertEqual(snapshot.read { try $0.tableExists("foo") }, false) + } + + func testSnapshotCreatedFromMainQueueCanRead() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + let snapshot = try dbPool.makeSnapshot() + try XCTAssertEqual(snapshot.read(counter.value), 0) + } + + func testSnapshotCreatedFromWriterOutsideOfTransactionCanRead() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in + XCTAssertFalse(db.isInsideTransaction) + let snapshot = try dbPool.makeSnapshot() + try counter.increment(db) + return snapshot + } + try XCTAssertEqual(snapshot.read(counter.value), 0) + } + + func testSnapshotCreatedFromReaderTransactionCanRead() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + let snapshot = try dbPool.read { db -> DatabaseSnapshot in + XCTAssertTrue(db.isInsideTransaction) + return try dbPool.makeSnapshot() + } + try XCTAssertEqual(snapshot.read(counter.value), 0) + } + + func testSnapshotCreatedFromReaderOutsideOfTransactionCanRead() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + let snapshot = try dbPool.unsafeRead { db -> DatabaseSnapshot in + XCTAssertFalse(db.isInsideTransaction) + return try dbPool.makeSnapshot() + } + try XCTAssertEqual(snapshot.read(counter.value), 0) + } + + func testSnapshotCreatedFromTransactionObserver() throws { + // Creating a snapshot from a didCommit callback is an important use + // case. But we know SQLite snapshots created with + // sqlite3_snapshot_get() require a transaction. This means that + // creating a snapshot will open a transaction. We must make sure this + // transaction does not create any deadlock of reentrancy issue with + // transaction observers. + class Observer: TransactionObserver { + let dbPool: DatabasePool + var snapshot: DatabaseSnapshot + init(dbPool: DatabasePool, snapshot: DatabaseSnapshot) { + self.dbPool = dbPool + self.snapshot = snapshot + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func databaseDidChange(with event: DatabaseEvent) { } + func databaseDidCommit(_ db: Database) { + snapshot = try! dbPool.makeSnapshot() + } + func databaseDidRollback(_ db: Database) { } + } + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + let observer = try Observer(dbPool: dbPool, snapshot: dbPool.makeSnapshot()) + dbPool.add(transactionObserver: observer) + try XCTAssertEqual(observer.snapshot.read(counter.value), 0) + try dbPool.write(counter.increment) + try XCTAssertEqual(observer.snapshot.read(counter.value), 1) + } + + // MARK: - Behavior + func testSnapshotIsReadOnly() throws { let dbPool = try makeDatabasePool() let snapshot = try dbPool.makeSnapshot() do { try snapshot.read { db in - try db.create(table: "t") { $0.column("id", .integer).primaryKey() } + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY") } XCTFail("Expected error") - } catch is DatabaseError { - } catch { - XCTFail("Unexpected error: \(error)") - } + } catch is DatabaseError { } } - func testSnapshotSeesLatestTransaction() throws { + func testSnapshotIsImmutable() throws { let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) try dbPool.writeWithoutTransaction { db in - try db.create(table: "t") { $0.column("id", .integer).primaryKey() } - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try counter.increment(db) let snapshot = try dbPool.makeSnapshot() - try snapshot.read { db in - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 1) - } - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 2) - try snapshot.read { db in - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 1) - } + try counter.increment(db) + try XCTAssertEqual(counter.value(db), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + try XCTAssertEqual(counter.value(db), 2) + try XCTAssertEqual(dbPool.read(counter.value), 2) } } - func testSnapshotCreatedOutsideOfWriterQueue() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.create(table: "t") { $0.column("id", .integer).primaryKey() } - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - let snapshot = try dbPool.makeSnapshot() - try snapshot.read { db in - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 1) - } - try dbPool.write { db in - try db.execute(sql: "INSERT INTO t DEFAULT VALUES") - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 2) - } - try snapshot.read { db in - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 1) - } - } + // MARK: - Functions func testSnapshotInheritPoolFunctions() throws { let dbPool = try makeDatabasePool() @@ -78,7 +155,9 @@ class DatabaseSnapshotTests: GRDBTestCase { try XCTAssertEqual(String.fetchOne(db, sql: "SELECT foo()")!, "foo") } } - + + // MARK: - Collations + func testSnapshotInheritPoolCollations() throws { let dbPool = try makeDatabasePool() let collation = DatabaseCollation("reverse") { (string1, string2) in @@ -98,7 +177,7 @@ class DatabaseSnapshotTests: GRDBTestCase { XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE reverse"), ["c", "b", "a"]) } } - + func testSnapshotCollations() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in @@ -118,6 +197,8 @@ class DatabaseSnapshotTests: GRDBTestCase { } } + // MARK: - Concurrency + func testDefaultLabel() throws { let dbPool = try makeDatabasePool() @@ -166,4 +247,85 @@ class DatabaseSnapshotTests: GRDBTestCase { XCTAssertEqual(label, "Toreador.snapshot.2") } } + + // MARK: - Checkpoints + + func testAutomaticCheckpointDoesNotInvalidateSnapshot() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshot() + try XCTAssertEqual(snapshot.read(counter.value), 1) + try dbPool.writeWithoutTransaction { db in + // 1000 is enough to trigger automatic snapshot + for _ in 0..<1000 { + try counter.increment(db) + } + } + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + + func testPassiveCheckpointDoesNotInvalidateSnapshot() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshot() + try? dbPool.checkpoint(.passive) // ignore if error or not, that's not the point + try XCTAssertEqual(snapshot.read(counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + + func testFullCheckpointDoesNotInvalidateSnapshot() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshot() + try? dbPool.checkpoint(.full) // ignore if error or not, that's not the point + try XCTAssertEqual(snapshot.read(counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + + func testRestartCheckpointDoesNotInvalidateSnapshot() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshot() + try? dbPool.checkpoint(.restart) // ignore if error or not, that's not the point + try XCTAssertEqual(snapshot.read(counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + + func testTruncateCheckpointDoesNotInvalidateSnapshot() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let snapshot = try dbPool.makeSnapshot() + try? dbPool.checkpoint(.truncate) // ignore if error or not, that's not the point + try XCTAssertEqual(snapshot.read(counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(snapshot.read(counter.value), 1) + } + + // MARK: - Schema Cache + + func testSnapshotSchemaCache() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY)") + } + let snapshot = try dbPool.makeSnapshot() + try snapshot.read { db in + // Schema cache is updated + XCTAssertNil(db.schemaCache.primaryKey("t")) + _ = try db.primaryKey("t") + XCTAssertNotNil(db.schemaCache.primaryKey("t")) + } + snapshot.read { db in + // Schema cache is not cleared between reads + XCTAssertNotNil(db.schemaCache.primaryKey("t")) + } + } } diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index 7cb9f6680..a6e8eeacd 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -8,7 +8,7 @@ import XCTest class PoolTests: XCTestCase { /// Returns a Pool whose elements are incremented integers: 1, 2, 3... private func makeCounterPool(maximumCount: Int) -> Pool { - let count = ReadWriteBox(0) + let count = ReadWriteBox(value: 0) return Pool(maximumCount: maximumCount, makeElement: count.increment) } diff --git a/Tests/GRDBTests/SQLInterpolationTests.swift b/Tests/GRDBTests/SQLInterpolationTests.swift index 100a1f555..8f51b3bbb 100644 --- a/Tests/GRDBTests/SQLInterpolationTests.swift +++ b/Tests/GRDBTests/SQLInterpolationTests.swift @@ -117,8 +117,8 @@ class SQLInterpolationTests: GRDBTestCase { func testQualifiedExpressionInterpolation() { var sql = SQLInterpolation(literalCapacity: 0, interpolationCount: 1) - sql.appendInterpolation(Column("name").aliased("foo")); sql.appendLiteral("\n") - sql.appendInterpolation(1.databaseValue.aliased("bar")) + sql.appendInterpolation(Column("name").forKey("foo")); sql.appendLiteral("\n") + sql.appendInterpolation(1.databaseValue.forKey("bar")) XCTAssertEqual(sql.sql, """ "name" AS "foo" diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index bae20c007..7c38a676a 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -112,6 +112,18 @@ class SQLLiteralTests: GRDBTestCase { #if swift(>=5.0) extension SQLLiteralTests { + func testLiteralInitializer() { + let query = SQLLiteral(""" + SELECT * FROM player + WHERE id = \(1) + """) + XCTAssertEqual(query.sql, """ + SELECT * FROM player + WHERE id = ? + """) + XCTAssertEqual(query.arguments, [1]) + } + func testRawSQLInterpolation() { let query: SQLLiteral = """ SELECT * @@ -245,7 +257,7 @@ extension SQLLiteralTests { func testQualifiedExpressionInterpolation() { let query: SQLLiteral = """ - SELECT \(Column("name").aliased("foo")) + SELECT \(Column("name").forKey("foo")) FROM player """ XCTAssertEqual(query.sql, """ diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index d918dbc24..3b4e81d91 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -100,6 +100,20 @@ class SQLRequestTests: GRDBTestCase { } #if swift(>=5.0) + func testLiteralInitializer() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = SQLRequest(""" + SELECT \("O'Brien") + """) + XCTAssertEqual(request.sql, """ + SELECT ? + """) + let string = try request.fetchOne(db)! + XCTAssertEqual(string, "O'Brien") + } + } + func testSQLLiteralInitializerWithInterpolation() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index be03c5d80..4e3c8dc58 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -154,4 +154,114 @@ class ValueObservationRowTests: GRDBTestCase { ["id":2, "name":"bar"], nil]) } + + func testFTS4Observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(virtualTable: "ft_documents", using: FTS4()) + } + + var rows: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let request = SQLRequest(sql: "SELECT * FROM ft_documents") + let observation = ValueObservation.tracking(value: request.fetchAll) + let observer = observation.start( + in: dbQueue, + onError: { error in + XCTFail("unexpected error: \(error)") + }, + onChange: { + rows.append($0) + notificationExpectation.fulfill() + }) + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"]) + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(rows, [[], [["content":"foo"]]]) + } + } + + func testSynchronizedFTS4Observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "documents") { t in + t.column("id", .integer).primaryKey() + t.column("content", .text) + } + try db.create(virtualTable: "ft_documents", using: FTS4()) { t in + t.synchronize(withTable: "documents") + t.column("content") + } + } + + var rows: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let request = SQLRequest(sql: "SELECT * FROM ft_documents") + let observation = ValueObservation.tracking(value: request.fetchAll) + let observer = observation.start( + in: dbQueue, + onError: { error in + XCTFail("unexpected error: \(error)") + }, + onChange: { + rows.append($0) + notificationExpectation.fulfill() + }) + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(rows, [[], [["content":"foo"]]]) + } + } + + func testJoinedFTS4Observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "document") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(virtualTable: "ft_document", using: FTS4()) { t in + t.column("content") + } + } + + var rows: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let request = SQLRequest(sql: """ + SELECT document.* FROM document + JOIN ft_document ON ft_document.rowid = document.id + WHERE ft_document MATCH 'foo' + """) + let observation = ValueObservation.tracking(value: request.fetchAll) + let observer = observation.start( + in: dbQueue, + onError: { error in + XCTFail("unexpected error: \(error)") + }, + onChange: { + rows.append($0) + notificationExpectation.fulfill() + }) + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1]) + try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"]) + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(rows, [[], [["id":1]]]) + } + } } diff --git a/Tests/SPM/Package.swift b/Tests/SPM/PlainPackage/Package.swift similarity index 100% rename from Tests/SPM/Package.swift rename to Tests/SPM/PlainPackage/Package.swift diff --git a/Tests/SPM/Sources/SPM/main.swift b/Tests/SPM/PlainPackage/Sources/SPM/main.swift similarity index 100% rename from Tests/SPM/Sources/SPM/main.swift rename to Tests/SPM/PlainPackage/Sources/SPM/main.swift diff --git a/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj b/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj new file mode 100644 index 000000000..5b75e5ba6 --- /dev/null +++ b/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj @@ -0,0 +1,320 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 52; + objects = { + +/* Begin PBXBuildFile section */ + 56C0D3B42344F90100DD47F3 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0D3B32344F90100DD47F3 /* main.swift */; }; + 56C0D3BC2344F96900DD47F3 /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56C0D3BB2344F96900DD47F3 /* GRDB */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 56C0D3AE2344F90100DD47F3 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + ); + runOnlyForDeploymentPostprocessing = 1; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 56C0D3B02344F90100DD47F3 /* Plain */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = Plain; sourceTree = BUILT_PRODUCTS_DIR; }; + 56C0D3B32344F90100DD47F3 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + 56C0D3BD2344F97C00DD47F3 /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 56C0D3AD2344F90100DD47F3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 56C0D3BC2344F96900DD47F3 /* GRDB in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 56C0D3A72344F90100DD47F3 = { + isa = PBXGroup; + children = ( + 56C0D3B22344F90100DD47F3 /* Plain */, + 56C0D3BD2344F97C00DD47F3 /* GRDB.swift */, + 56C0D3B12344F90100DD47F3 /* Products */, + ); + sourceTree = ""; + }; + 56C0D3B12344F90100DD47F3 /* Products */ = { + isa = PBXGroup; + children = ( + 56C0D3B02344F90100DD47F3 /* Plain */, + ); + name = Products; + sourceTree = ""; + }; + 56C0D3B22344F90100DD47F3 /* Plain */ = { + isa = PBXGroup; + children = ( + 56C0D3B32344F90100DD47F3 /* main.swift */, + ); + path = Plain; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 56C0D3AF2344F90100DD47F3 /* Plain */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56C0D3B72344F90100DD47F3 /* Build configuration list for PBXNativeTarget "Plain" */; + buildPhases = ( + 56C0D3AC2344F90100DD47F3 /* Sources */, + 56C0D3AD2344F90100DD47F3 /* Frameworks */, + 56C0D3AE2344F90100DD47F3 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Plain; + packageProductDependencies = ( + 56C0D3BB2344F96900DD47F3 /* GRDB */, + ); + productName = Plain; + productReference = 56C0D3B02344F90100DD47F3 /* Plain */; + productType = "com.apple.product-type.tool"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 56C0D3A82344F90100DD47F3 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1110; + LastUpgradeCheck = 1110; + ORGANIZATIONNAME = "Gwendal Roué"; + TargetAttributes = { + 56C0D3AF2344F90100DD47F3 = { + CreatedOnToolsVersion = 11.1; + }; + }; + }; + buildConfigurationList = 56C0D3AB2344F90100DD47F3 /* Build configuration list for PBXProject "Plain" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 56C0D3A72344F90100DD47F3; + packageReferences = ( + 56C0D3BA2344F96900DD47F3 /* XCRemoteSwiftPackageReference "GRDB" */, + ); + productRefGroup = 56C0D3B12344F90100DD47F3 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 56C0D3AF2344F90100DD47F3 /* Plain */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 56C0D3AC2344F90100DD47F3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 56C0D3B42344F90100DD47F3 /* main.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 56C0D3B52344F90100DD47F3 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = 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_DOCUMENTATION_COMMENTS = YES; + 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_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + 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; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 56C0D3B62344F90100DD47F3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = 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_DOCUMENTATION_COMMENTS = YES; + 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_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + 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; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 56C0D3B82344F90100DD47F3 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 56C0D3B92344F90100DD47F3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 56C0D3AB2344F90100DD47F3 /* Build configuration list for PBXProject "Plain" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56C0D3B52344F90100DD47F3 /* Debug */, + 56C0D3B62344F90100DD47F3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 56C0D3B72344F90100DD47F3 /* Build configuration list for PBXNativeTarget "Plain" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56C0D3B82344F90100DD47F3 /* Debug */, + 56C0D3B92344F90100DD47F3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 56C0D3BA2344F96900DD47F3 /* XCRemoteSwiftPackageReference "GRDB" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/groue/GRDB.swift"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 4.4.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 56C0D3BB2344F96900DD47F3 /* GRDB */ = { + isa = XCSwiftPackageProductDependency; + package = 56C0D3BA2344F96900DD47F3 /* XCRemoteSwiftPackageReference "GRDB" */; + productName = GRDB; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 56C0D3A82344F90100DD47F3 /* Project object */; +} diff --git a/Tests/SPM/PlainProject/Plain.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/SPM/PlainProject/Plain.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..6f56eb538 --- /dev/null +++ b/Tests/SPM/PlainProject/Plain.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Tests/SPM/PlainProject/Plain.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Tests/SPM/PlainProject/Plain.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Tests/SPM/PlainProject/Plain.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Tests/SPM/PlainProject/Plain/main.swift b/Tests/SPM/PlainProject/Plain/main.swift new file mode 100644 index 000000000..3c6ac9e86 --- /dev/null +++ b/Tests/SPM/PlainProject/Plain/main.swift @@ -0,0 +1,3 @@ +import GRDB + +try! print(DatabaseQueue().read { try String.fetchOne($0, sql: "SELECT 'Hello world!'")! })