Compare commits

...
Author SHA1 Message Date
Gwendal Roué a88067a815 Merge branch 'GRDB5' into dev/hasMany-first 2020-04-25 13:31:58 +02:00
Gwendal Roué 6fd3a7b225 Merge branch 'development' into GRDB5
# Conflicts:
#	CHANGELOG.md
#	README.md
2020-04-25 13:21:20 +02:00
Gwendal Roué 6b1910fce7 [skip travis] fix typo in CHANGELOG 2020-04-23 09:08:27 +02:00
Gwendal Roué 5ee47c3c27 Merge branch 'development' 2020-04-23 08:56:55 +02:00
Gwendal Roué 5652a01366 v4.14.0 2020-04-23 08:55:38 +02:00
Gwendal Roué 132d01f9f7 Complete #766: use json objects in DatabaseDateComponents tests 2020-04-22 19:33:31 +02:00
Gwendal Roué 1d760ff9ce Extend congrats list 2020-04-22 18:45:34 +02:00
Gwendal Roué dc4d516493 Merge pull request #766 from DiligentRobot/development
Add Codable support to DatabaseDateComponents
2020-04-20 19:17:07 +02:00
Matt Tancock 62c6187ad4 Remove Format's Codable conformance. Use a singleValueContainer 2020-04-20 14:42:02 +01:00
Matt Tancock 18154f29be Simplify encoding format and add tests 2020-04-20 13:36:23 +01:00
Gwendal Roué df4d5b8603 Back to basics, round 2: keep all children of firstOnly relations 2020-04-19 17:44:50 +02:00
Gwendal Roué a7b8a73dba Cleanup
After failed experiment:

SELECT ...
FROM parent
JOIN (SELECT * FROM child LIMIT 1) child ON child.parentId = child.id

The problem is that the join condition can't go inside the subquery, because SQLite complains about unknown table "parent". And when the join condition is outside the subquery, the LIMIT clause has been applied too early.

So we're still stuck with:

SELECT ...
FROM parent
JOIN child ON child.id = (SELECT id FROM child WHERE child.parentId = child.id LIMIT 1)

For some reason SQLite accepts the reference to the parent table in this case.
2020-04-19 14:14:13 +02:00
Gwendal Roué 278c18adfc Cleanup 2020-04-18 20:21:14 +02:00
Gwendal Roué cbd494e3b9 Documentation 2020-04-18 20:19:47 +02:00
Gwendal Roué c73fb0dd9b Back to basics 2020-04-18 20:14:27 +02:00
Gwendal Roué c966eb3ecf Cleanup 2020-04-18 19:09:02 +02:00
Gwendal Roué 217b0a3f3e More failing HasManyThrough.first tests 2020-04-18 17:52:50 +02:00
Gwendal Roué e604a10860 TODO 2020-04-18 17:06:29 +02:00
Gwendal Roué ac4f4c6611 Improve HasMany.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 162da80e4f Attempt at expressing some todos 2020-04-18 17:06:29 +02:00
Gwendal Roué 315496928b More failing HasManyThrough.first 2020-04-18 17:06:29 +02:00
Gwendal Roué d82cbb6853 Improve HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 5fed231856 Simplify SQLAssociationCondition.filteringExpression 2020-04-18 17:06:29 +02:00
Gwendal Roué 45dfe7d7f1 More HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué c7d1cca023 Ease testing SQL by ignoring white space 2020-04-18 17:06:29 +02:00
Gwendal Roué 615f4159d6 Rename firstInMany to firstOnly 2020-04-18 17:06:29 +02:00
Gwendal Roué 8057572357 Move firstInMany flag in SQLRelation 2020-04-18 17:06:29 +02:00
Gwendal Roué da63037948 Fix documentation 2020-04-18 17:06:29 +02:00
Gwendal Roué 2d3dafad7d Document first and last properties, set their association key 2020-04-18 17:06:29 +02:00
Gwendal Roué 7ed967b502 Cleanup SQLAssociationCardinality and SQLAssociationStep 2020-04-18 17:06:29 +02:00
Gwendal Roué f545789205 Avoid using the rowid column when we can use the regular primary key 2020-04-18 17:06:23 +02:00
Gwendal Roué 79373d5b74 Cleanup some old tests 2020-04-18 16:40:22 +02:00
Gwendal Roué f97088d63a Failing tests for HasManyThrough.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 860faf19f7 HasManyThrough.first and last 2020-04-18 16:40:22 +02:00
Gwendal Roué 0f54779386 Isolate tests for hasMany.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 6f125bd3d7 SQLAssociation.associationForFirst() 2020-04-18 16:40:22 +02:00
Gwendal Roué 4483f037a4 Cleanup 2020-04-18 16:40:22 +02:00
Gwendal Roué 20296652dd More test for hasMany.first including nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d80922954a Let hasMany.first include nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d67814ef61 Make sure hasMany.first doesn't lose information 2020-04-18 16:40:22 +02:00
Gwendal Roué fb550d30a0 HasManyAssociation.first and last 2020-04-18 16:40:22 +02:00
Gwendal Roué a715c6328d Merge branch 'master' into GRDB5
# Conflicts:
#	CHANGELOG.md
#	GRDB/QueryInterface/Request/QueryInterfaceRequest.swift
#	Makefile
#	README.md
#	Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj
2020-04-18 16:36:26 +02:00
Matt Tancock bffe4d32f5 Add Codable support to DatabaseDateComponents 2020-04-17 16:16:34 +01:00
Gwendal Roué 3fd00012d1 Update obsolete observation usage in README 2020-04-17 09:03:03 +02:00
Gwendal Roué 6d901b06e9 TODO 2020-04-16 19:27:09 +02:00
Gwendal Roué f677310703 Merge branch 'development' 2020-04-15 08:27:35 +02:00
Gwendal Roué 0200f64e6c v4.13.0 2020-04-14 19:14:15 +02:00
Gwendal Roué c6b5c935bb Merge pull request #761 from groue/dev/deprecate-assignment-operator
Deprecate the batch update `<-` operator
2020-04-14 19:03:43 +02:00
Gwendal Roué 2d30f06f54 Update regression test introduced after commit cherry-picked from #750 2020-04-14 19:01:42 +02:00
Gwendal Roué a98350d206 CHANGELOG 2020-04-14 18:55:40 +02:00
Gwendal Roué 6918bda82d CHANGELOG 2020-04-14 18:51:21 +02:00
Gwendal Roué a065926fb1 Update documentation 2020-04-14 18:51:21 +02:00
Gwendal Roué 0569b95a5a Operator <- was ill-advised
# Conflicts:
#	GRDB/QueryInterface/Request/QueryInterfaceRequest.swift
2020-04-14 18:51:21 +02:00
Gwendal Roué d17866d3fd Update Realm path 2020-04-14 18:50:51 +02:00
Gwendal Roué 6c0f1dc389 Merge pull request #759 from groue/dev/fix-758
Fix batch updates of complex requests
2020-04-14 18:50:26 +02:00
Gwendal Roué e7750e6fe0 Merge pull request #760 from andreasschmitz/development
README Typo Fixes
2020-04-14 17:33:01 +02:00
Andreas Schmitz e4addc4243 Fixes typos 2020-04-14 17:18:27 +02:00
Gwendal Roué d35ad59f9c Fix failing test for #758 2020-04-14 12:51:24 +02:00
Gwendal Roué 07609e8a3f Failing test for #758 2020-04-14 12:51:24 +02:00
Gwendal Roué f4e2645e13 CHANGELOG 2020-04-14 12:47:00 +02:00
Gwendal Roué c352ca70b2 A new kind tweet :-) 2020-04-14 12:17:38 +02:00
Gwendal Roué b182a26759 Fix compilation error with Xcode 10.1 2020-04-14 12:14:25 +02:00
Gwendal Roué 5760b9c0cc Migration Guide 2020-04-12 20:10:03 +02:00
Gwendal Roué 75525bdb56 Migration Guide 2020-04-12 17:33:04 +02:00
Gwendal Roué 2fa57cdafa Make CSQLite a system module
Attempt at fixing this GRDBCombine error:

$ swift build
...
'CSQLite' /.../GRDBCombine/.build/checkouts/CSQLite: error: configuration of package 'CSQLite' is invalid; the 'providers' property can only be used with a System Module Package
2020-04-12 15:07:39 +02:00
Gwendal Roué 2319572552 Remove unused file 2020-04-12 13:04:45 +02:00
Gwendal Roué 5f26a71c5b Migration Guide 2020-04-12 10:24:44 +02:00
Gwendal Roué d0558ee2f0 Migration Guide 2020-04-12 10:15:09 +02:00
Gwendal Roué fc09fd6654 Merge pull request #756 from groue/dev/export-SQLite
Export the underlying SQLite library
2020-04-12 10:05:19 +02:00
Gwendal Roué 1ea5d1713a Cleanup 2020-04-12 10:04:09 +02:00
Gwendal Roué aa0ae00c56 CHANGELOG 2020-04-12 09:44:11 +02:00
Gwendal Roué 0372c1dd63 Complete #747: export the underlying SQLite library 2020-04-12 07:27:50 +02:00
Gwendal Roué c052b44999 Cleanup 2020-04-11 20:56:36 +02:00
Gwendal Roué f27d6b07c0 Cleanup 2020-04-11 20:45:00 +02:00
Gwendal Roué 4f8b681737 Documentation 2020-04-11 18:26:42 +02:00
Gwendal Roué 5b9ae9371b Documentation 2020-04-11 17:37:12 +02:00
Gwendal Roué 68f4db468a Documentation 2020-04-11 17:25:16 +02:00
Gwendal Roué 62dbc78090 More migration guide 2020-04-11 13:57:19 +02:00
Gwendal Roué bd7bec22a1 More migration guide 2020-04-11 13:52:36 +02:00
Gwendal Roué 722e74db6a More migration guide 2020-04-11 13:49:26 +02:00
Gwendal Roué e9439a1d58 Fix typo 2020-04-11 13:39:02 +02:00
Gwendal Roué 3c70814cdc More ValueObservation migration doc 2020-04-11 13:38:01 +02:00
Gwendal Roué fea89100d9 Improve ValueObservation.trackingVaryingRegion example 2020-04-11 13:10:15 +02:00
Gwendal Roué 2c3d0b1e17 Organize migration guide 2020-04-11 13:05:11 +02:00
Gwendal Roué 478ae7bc24 Improve migration guide 2020-04-11 12:43:28 +02:00
Gwendal Roué da81c8b87c Fix typo 2020-04-11 10:33:12 +02:00
Gwendal Roué 4088a477ec Improve migration guide 2020-04-10 20:07:19 +02:00
Gwendal Roué 85dcd32c8d Improve the description of ValueObservation change 2020-04-10 18:52:24 +02:00
Gwendal Roué 62c72c20e9 CHANGELOG 2020-04-10 18:38:16 +02:00
Gwendal Roué 1b4e26f61c Cleanup 2020-04-10 12:35:33 +02:00
Gwendal Roué 474310e00b More inspiration from CocoaError 2020-04-10 09:30:34 +02:00
Gwendal Roué 7a475ad476 Cleanup 2020-04-10 08:58:29 +02:00
Gwendal Roué 65ac210dfb Merge pull request #754 from groue/dev/ResultCode-match
Match DatabaseError on ResultCode
2020-04-09 20:42:23 +02:00
Gwendal Roué f19e5bf67c CHANGELOG 2020-04-09 19:56:12 +02:00
Gwendal Roué 419bedd73b Update documentation for DatabaseError catching 2020-04-09 19:53:21 +02:00
Gwendal Roué 8eb58926a4 Test for ResultCode error matching 2020-04-09 19:53:02 +02:00
Gwendal Roué ccacbc9706 ResultCode match errors 2020-04-09 19:52:39 +02:00
Gwendal Roué 7db59867cb Documentation 2020-04-09 19:08:53 +02:00
Gwendal Roué 37aa7feee9 Rename KeyPathRefining to Refinable 2020-04-09 18:50:36 +02:00
Gwendal Roué e49800d21d Fix build warnings 2020-04-09 17:55:49 +02:00
Gwendal Roué 078aa83e3b Rename count(where:) to countElements(where:) 2020-04-09 17:47:07 +02:00
Gwendal Roué 8ef4c9b241 Remove convenience Result.tryMap 2020-04-09 17:45:12 +02:00
Gwendal Roué f9157da590 TODO 2020-04-09 17:44:41 +02:00
Gwendal Roué 27120643b9 SE-0255: Implicit returns from single-expression functions 2020-04-09 17:16:23 +02:00
Gwendal Roué 306033b63b Update Migration Guide 2020-04-09 13:43:56 +02:00
Gwendal Roué d988be49a6 Revert #748 2020-04-09 13:42:37 +02:00
Gwendal Roué 1a5661c890 Lift resolved attention point about custom SQLite builds 2020-04-09 08:55:40 +02:00
Gwendal Roué ccaad8d860 Restore backward compatibility for setup of custom SQLite builds
User only has to rename the `import` Swift statement
2020-04-09 08:50:24 +02:00
Gwendal Roué c9d95af646 Merge pull request #752 from groue/dev/drop-observation-combination
Remove ValueObservation.combine
2020-04-08 19:55:18 +02:00
Gwendal Roué 3e081f0dd6 Remove GRDBPerformance project from workspace
This avoids painful Xcode management of SPM packages
2020-04-08 19:13:08 +02:00
Gwendal Roué 444525d748 CHANGELOG 2020-04-08 18:54:08 +02:00
Gwendal Roué c778e1ac0c Add fixits 2020-04-08 18:53:08 +02:00
Gwendal Roué bfe037c61d Update documentation 2020-04-08 18:33:56 +02:00
Gwendal Roué e2790c863f Remove ValueObservation combine operator 2020-04-08 18:16:05 +02:00
Gwendal Roué 3c3df9ad24 Miigration Guide WIP 2020-04-08 08:40:54 +02:00
Gwendal Roué 3c30e6d0c1 Miigration Guide WIP 2020-04-08 08:30:10 +02:00
Gwendal Roué a5ad4dd23d Miigration Guide WIP 2020-04-07 22:24:25 +02:00
Gwendal Roué 0505b1cef9 Miigration Guide WIP 2020-04-07 22:20:35 +02:00
Gwendal Roué 2ac6f9766a Miigration Guide WIP 2020-04-07 22:16:44 +02:00
Gwendal Roué 10fcd1092f Miigration Guide WIP 2020-04-07 22:08:17 +02:00
Gwendal Roué cbcbbe9c8f Miigration Guide WIP 2020-04-07 22:04:47 +02:00
Gwendal Roué 2b7b03846e Miigration Guide WIP 2020-04-07 22:00:00 +02:00
Gwendal Roué 05f9854cea Miigration Guide WIP 2020-04-07 20:59:34 +02:00
Gwendal Roué 8cb67f1c22 Miigration Guide WIP 2020-04-07 20:47:56 +02:00
Gwendal Roué 48987f39c3 Miigration Guide WIP 2020-04-07 20:17:11 +02:00
Gwendal Roué e5f711f68c Miigration Guide WIP 2020-04-07 20:01:55 +02:00
Gwendal Roué ac92fc95e3 Merge branch 'development' into GRDB5 2020-04-06 20:16:53 +02:00
Gwendal Roué bf07c49171 Merge pull request #750 from groue/dev/assignment-without-operator
Batch updates do not need any operator
2020-04-05 17:24:09 +02:00
Gwendal Roué c59d42dfca CHANGELOG 2020-04-05 16:43:00 +02:00
Gwendal Roué 80b15f7f07 Ignore GRDB.xcworkspace spm stuff 2020-04-05 16:28:04 +02:00
Gwendal Roué 9647a78ed6 Update documentation 2020-04-05 16:26:29 +02:00
Gwendal Roué 2c743531d0 Operator <- was ill-advised 2020-04-05 16:25:18 +02:00
Gwendal Roué 9e967ccc93 Merge pull request #749 from groue/dev/submodules
Drop submodules used by performance tests
2020-04-05 14:07:49 +02:00
Gwendal Roué 86330000db CHANGELOG 2020-04-05 13:36:41 +02:00
Gwendal Roué af597736f6 Wait before we look into the Xcode checkouts 2020-04-05 13:14:09 +02:00
Gwendal Roué 119ce30ad1 Pin versions GRDBPerformance of dependencies 2020-04-05 12:29:03 +02:00
Gwendal Roué 85c3f12b86 Extract versions of GRDBPerformance dependencies from Xcode SPM checkouts 2020-04-05 11:57:55 +02:00
Gwendal Roué f95e01cbd5 Remove submodule dependencies from Makefile 2020-04-05 10:34:21 +02:00
Gwendal Roué 21eb87fa49 Use SPM for GRDBPerformance dependencies 2020-04-05 10:25:54 +02:00
Gwendal Roué 4614cfda06 Removed test submodules 2020-04-05 09:58:53 +02:00
Gwendal Roué a4bda6da96 Merge pull request #748 from groue/dev/Request
Rename QueryInterfaceRequest to Request
2020-04-04 20:55:18 +02:00
Gwendal Roué 2d2b8494d0 CHANGELOG 2020-04-04 20:13:50 +02:00
Gwendal Roué 7ce6a8a094 Rename QueryInterfaceRequest to Request 2020-04-04 20:12:03 +02:00
Gwendal Roué 3756c43691 Merge pull request #747 from groue/dev/fix-743
Rename GRDBCustomSQLite to GRDB
2020-04-04 18:52:14 +02:00
Gwendal Roué bfc4738097 CHANGELOG 2020-04-04 18:48:35 +02:00
Gwendal Roué afcb9183ad Rename GRDBCustom schemes 2020-04-04 18:37:36 +02:00
Gwendal Roué c3474471f7 Don't include <sqlite3.h> for custom SQLite builds 2020-04-04 18:03:29 +02:00
Gwendal Roué 65c009a018 Rename GRDBCustomSQLite module to GRDB 2020-04-04 17:42:00 +02:00
Gwendal Roué d60fe3c22f Replace import GRDBCustomSQLite with import GRDB 2020-04-04 16:44:01 +02:00
Gwendal Roué 5727163966 SPM: export CSQLite package 2020-04-04 14:20:07 +02:00
Gwendal Roué d72000c6a3 Use scheduling paramater name for consistency with GRDBCombine and RxGRDB 2020-03-31 20:25:36 +02:00
Gwendal Roué 381f716e4b AnyDatabaseCancellable is public
This helps GRDBCombine defaulting to a default cancellable when database connection has been closed before the ValueObservation publisher has been subscribed to.
2020-03-29 20:31:02 +02:00
Gwendal Roué eee2c65c14 Merge branch 'development' into GRDB5
# Conflicts:
#	CHANGELOG.md
#	README.md
2020-03-29 18:55:06 +02:00
Gwendal Roué 73aada9194 Merge pull request #745 from groue/dev/ValueObservation-cancellation
Explicit ValueObservation cancellation
2020-03-29 17:30:09 +02:00
Gwendal Roué 5665a2428a CHANGELOG 2020-03-29 16:49:21 +02:00
Gwendal Roué 66dc482b02 Don't pretend database deallocation is a cancel event 2020-03-29 16:30:29 +02:00
Gwendal Roué 3c20adb0c6 Add test for explicit cancellation 2020-03-29 16:11:54 +02:00
Gwendal Roué 1bffc4f628 ValueObservation is cancellable 2020-03-29 16:06:24 +02:00
Gwendal Roué ccd73bf63d Don't parallelize SQLCipher tests 2020-03-29 11:45:52 +02:00
Gwendal Roué d4327faf0a Merge pull request #742 from groue/dev/ValueObservation-scheduling
ValueObservation scheduling is no longer an attribute of the observation
2020-03-29 11:14:48 +02:00
Gwendal Roué 87b54f5da2 Protect ValueObserver state behind a lock 2020-03-29 10:28:37 +02:00
Gwendal Roué a28ae9a523 Stronger tests 2020-03-28 20:50:40 +01:00
Gwendal Roué 055a4882f8 Fix compilation error 2020-03-28 20:14:30 +01:00
Gwendal Roué 90d5316781 Hide ValueObservationScheduler implementation 2020-03-28 19:53:18 +01:00
Gwendal Roué 303a0cc150 immediateInitialValue is a better name 2020-03-28 19:49:07 +01:00
Gwendal Roué 08ef740002 Optimize ValueObservation tests 2020-03-28 19:31:27 +01:00
Gwendal Roué 5d196c449d Value Observation does no longer retain DatabaseWriter 2020-03-28 17:11:57 +01:00
Gwendal Roué fdb2f63e60 Add missing file to iOS/tvOS/watchOS compilation 2020-03-28 14:26:08 +01:00
Gwendal Roué c83d390e60 More test rationalization 2020-03-28 14:07:36 +01:00
Gwendal Roué a6ac69eded Move view optimization test 2020-03-28 13:54:18 +01:00
Gwendal Roué 1914ace5f9 Test as much as possible value observations 2020-03-28 13:43:18 +01:00
Gwendal Roué 88ddce5fac Make sure the observer is cancelled on error 2020-03-28 11:42:53 +01:00
Gwendal Roué 23d428290b Assume that error ends the observation, and have database pool always perform a concurrent initial fetch 2020-03-28 10:30:36 +01:00
Gwendal Roué ff104686f6 Read-only observation: support for cancellation 2020-03-28 07:45:55 +01:00
Gwendal Roué a9ea6dd8bf CHANGELOG 2020-03-27 21:06:13 +01:00
Gwendal Roué 9866ed1dfc Remove useless change 2020-03-27 21:04:23 +01:00
Gwendal Roué 65a347fd98 Fix obsolete comment 2020-03-27 21:03:01 +01:00
Gwendal Roué 7e50869d39 Remove useless change 2020-03-27 21:01:34 +01:00
Gwendal Roué 703ce643b5 Remove useless change 2020-03-27 20:59:38 +01:00
Gwendal Roué 42d2891df8 Fix typo 2020-03-27 20:53:16 +01:00
Gwendal Roué f0effaa4fa Fix typo 2020-03-27 20:51:42 +01:00
Gwendal Roué 022fee8788 Remove dead code 2020-03-27 20:48:12 +01:00
Gwendal Roué 25a2bd653c Fix compiler warning 2020-03-27 20:48:03 +01:00
Gwendal Roué c03de9cc16 Fix documentation 2020-03-27 20:45:24 +01:00
Gwendal Roué 97d06a0fae Fix typo 2020-03-27 20:36:29 +01:00
Gwendal Roué 154125d3ae Update documentation 2020-03-27 20:19:55 +01:00
Gwendal Roué c4b7e0017b The main thread is enough 2020-03-27 20:19:44 +01:00
Gwendal Roué 469814985e Decrease nesting 2020-03-27 19:55:36 +01:00
Gwendal Roué f16105ad03 Add missing cancellation checks 2020-03-27 19:53:01 +01:00
Gwendal Roué 4309eaba64 Scheduling of fresh values is no longer an attribute of ValueObservation 2020-03-27 19:49:11 +01:00
Gwendal Roué 1580be3883 Update tests 2020-03-27 08:27:46 +01:00
Gwendal Roué b4b5d9b602 Simplify ValueObservation scheduling 2020-03-27 08:27:30 +01:00
Gwendal Roué 27dd08f945 Merge pull request #738 from groue/dev/drop-ObservationFor
Remove all observationForCount/All/First methods
2020-03-25 22:53:08 +01:00
Gwendal Roué b9c4d26731 Documentation 2020-03-25 22:36:33 +01:00
Gwendal Roué 7217f696b6 More row comparison technique 2020-03-25 22:23:12 +01:00
Gwendal Roué 880f8c8bdd More row comparison technique 2020-03-25 22:21:52 +01:00
Gwendal Roué 6f7efa2b9a CHANGELOG 2020-03-25 22:08:03 +01:00
Gwendal Roué 3a11d94bee Document the row comparison technique 2020-03-25 22:07:12 +01:00
Gwendal Roué e68bd077ee Remove all observationForCount/All/First methods 2020-03-25 21:44:10 +01:00
Gwendal Roué e84e984c23 Merge pull request #737 from groue/dev/ValueObservation-recording
Force implicit database region for ValueObservation
2020-03-25 19:41:12 +01:00
Gwendal Roué 12de05dc9b ValueObservation.trackingVaryingRegion documentation 2020-03-25 19:19:22 +01:00
Gwendal Roué ea8110110c Remove obsolete documentation 2020-03-25 14:04:42 +01:00
Gwendal Roué 79d6b02a2f Cleanup 2020-03-25 13:57:49 +01:00
Gwendal Roué 1195439226 Cleanup 2020-03-25 13:53:22 +01:00
Gwendal Roué ff2629a31c Cleanup 2020-03-25 13:05:39 +01:00
Gwendal Roué 61e74f9ad4 ValueObservation.trackingVaryingRegion documentation 2020-03-25 08:48:34 +01:00
Gwendal Roué f711978145 Documentation 2020-03-25 08:25:05 +01:00
Gwendal Roué a647e200d9 Replace Never with ValueReducers.Auto 2020-03-25 08:19:47 +01:00
Gwendal Roué 294a04e9f6 Rename tracking(value:) to tracking(_:) 2020-03-25 08:11:43 +01:00
Gwendal Roué 9792edc008 Rename trackingVolatile to trackingVaryingRegion 2020-03-25 00:13:51 +01:00
Gwendal Roué 143f3d1673 CHANGELOG 2020-03-25 00:03:09 +01:00
Gwendal Roué 121f7be847 ValueObservation is now fully based on region recording
And we introduce ValueObservation.trackingVolatile
2020-03-24 23:52:05 +01:00
Gwendal Roué 4af7fda4f2 Fix outdated documentation 2020-03-24 23:49:24 +01:00
Gwendal Roué 56f332122d The observed region is always recorded 2020-03-24 22:59:07 +01:00
Gwendal Roué d494d12293 Fix typo 2020-03-24 22:59:07 +01:00
Gwendal Roué ce6afd680d Merge pull request #736 from groue/dev/relax-ValueObservation
Relax ValueObservation Guarantees
2020-03-24 22:56:16 +01:00
Gwendal Roué dfd5dd2478 Add missing import for SPM 2020-03-24 22:55:18 +01:00
Gwendal Roué 327f07422f Add missing FailableTestCase.swift to custom SQLite tests 2020-03-24 22:35:32 +01:00
Gwendal Roué 6b33e656be CHANGELOG 2020-03-24 17:01:14 +01:00
Gwendal Roué 97a7117564 Rewrite ValueObservation documentation 2020-03-24 16:58:59 +01:00
Gwendal Roué e8fefc82a1 Drop obsolete warning against DatabaseRegionObservation 2020-03-24 16:29:56 +01:00
Gwendal Roué 0963b162e7 Rewrite ValueObservation documentation 2020-03-24 14:57:23 +01:00
Gwendal Roué 5210ae8385 Rewrite ValueObservation documentation 2020-03-24 14:36:29 +01:00
Gwendal Roué 78dc7aee15 Rewrite ValueObservation documentation 2020-03-24 14:35:43 +01:00
Gwendal Roué cf1360701c Rewrite ValueObservation documentation 2020-03-24 14:09:45 +01:00
Gwendal Roué b3fb61858a Rewrite ValueObservation documentation 2020-03-24 13:52:43 +01:00
Gwendal Roué 8d6708a12e Rewrite ValueObservation documentation 2020-03-24 13:49:09 +01:00
Gwendal Roué 06f6b31368 Rewrite ValueObservation documentation 2020-03-24 13:04:25 +01:00
Gwendal Roué 9562e8eac4 Rewrite ValueObservation documentation 2020-03-24 13:01:58 +01:00
Gwendal Roué 1325a3a6a2 Rewrite ValueObservation documentation 2020-03-24 11:47:55 +01:00
Gwendal Roué 89058f4447 Rewrite ValueObservation documentation 2020-03-24 11:39:21 +01:00
Gwendal Roué f6da862145 Rewrite ValueObservation documentation 2020-03-24 08:54:46 +01:00
Gwendal Roué 0c464def7f Fix documentation 2020-03-23 18:00:45 +01:00
Gwendal Roué e824c70e7d Fix SQLCipher tests 2020-03-22 13:46:34 +01:00
Gwendal Roué 7a583e02e8 Refactor ValueObservation tests around a common pattern 2020-03-22 13:31:05 +01:00
Gwendal Roué 98d381ed67 Cleanup 2020-03-22 10:27:10 +01:00
Gwendal Roué e16d29f277 More test refactoring with assertValueObservationRecordingMatch 2020-03-21 18:44:02 +01:00
Gwendal Roué 6bf322f79e More test refactoring with assertValueObservationRecordingMatch 2020-03-21 18:16:35 +01:00
Gwendal Roué c42aab26e3 Remove redundant test 2020-03-21 17:48:24 +01:00
Gwendal Roué e16b320cda More test refactoring with assertValueObservationRecordingMatch 2020-03-21 17:42:22 +01:00
Gwendal Roué 9d4bef1c9a More test refactoring with assertValueObservationRecordingMatch 2020-03-21 17:04:18 +01:00
Gwendal Roué b392458c1c More test refactoring with assertValueObservationRecordingMatch 2020-03-21 16:23:41 +01:00
Gwendal Roué 031b55eca6 More test refactoring with assertValueObservationRecordingMatch 2020-03-21 15:50:36 +01:00
Gwendal Roué 3e0486743b More test refactoring with assertValueObservationRecordingMatch 2020-03-21 15:21:24 +01:00
Gwendal Roué 7ab9a8b29a More test refactoring with assertValueObservationRecordingMatch 2020-03-21 14:36:48 +01:00
Gwendal Roué 22086c088f More test refactoring with assertValueObservationRecordingMatch 2020-03-21 14:36:48 +01:00
Gwendal Roué 3ee231afd3 Cleanup _OptionalProtocol 2020-03-21 14:36:48 +01:00
Gwendal Roué 4ffced0b7b assertValueObservationRecordingMatch 2020-03-21 14:36:48 +01:00
Gwendal Roué ed6673f2f5 ValueObservation test refactoring WIP 2020-03-21 14:36:48 +01:00
Gwendal Roué 7935168379 ValueObservation test refactoring WIP 2020-03-21 14:36:48 +01:00
Gwendal Roué 3c891b7ebd ValueObservationRecorder cleanup 2020-03-21 14:36:48 +01:00
Gwendal Roué 8f5c7985e5 ValueObservationRecorder 2020-03-21 14:36:48 +01:00
Gwendal Roué 2150b6688a Fix ValueObserver cancellation 2020-03-21 14:36:48 +01:00
Gwendal Roué 65b8fbb361 Remove useless print() statements 2020-03-21 14:36:48 +01:00
Gwendal Roué 2bb894108c Use the prependingConcurrentFetch flag 2020-03-21 14:36:48 +01:00
Gwendal Roué 26d2245ae8 Asynchronouslu remove observer when it is cancelled 2020-03-21 14:36:48 +01:00
Gwendal Roué 2b78a646ed Mor preparation for initiial concurrent fetch of ValueObservation in a DatabasePool 2020-03-21 14:36:48 +01:00
Gwendal Roué 1c59278115 Prefer dbResult argument name for async read closures 2020-03-21 14:36:48 +01:00
Gwendal Roué 2824636650 Prepare for initiial concurrent fetch of ValueObservation in a DatabasePool 2020-03-21 14:36:48 +01:00
Gwendal Roué 5a884ad93d Common ValueObservation code for all read-only database accessors 2020-03-21 14:36:48 +01:00
Gwendal Roué dab8e28f6d Merge branch 'master' into GRDB5
# Conflicts:
#	GRDB/Migration/DatabaseMigrator.swift
#	GRDB/QueryInterface/Request/QueryInterfaceRequest.swift
#	README.md
2020-03-21 14:35:57 +01:00
Gwendal Roué c6db8962b3 Merge pull request #732 from groue/dev/ValueObservation-mandatory-first-element
Remove ValueObservation.compactMap
2020-03-12 08:37:16 +01:00
Gwendal Roué 5a9085c34d CHANGELOG 2020-03-12 07:46:04 +01:00
Gwendal Roué c698b30c0a Add fixits 2020-03-12 07:43:57 +01:00
Gwendal Roué dfa40ea18f Rename ValueObservation.fetchFirst to fetchValue
"First", in Swift, hints that the result is optional. But the result of this function is no longer optional.
2020-03-12 07:34:43 +01:00
Gwendal Roué 936c92eba6 All value reducers must emit an initial value
This disqualifies compactMap as a valid ValueObservation transformation: it has been removed.

This simplifies implementation as well.
2020-03-12 07:18:40 +01:00
Gwendal Roué b0155b8aca Merge branch 'development' into GRDB5 2020-03-11 22:44:20 +01:00
Gwendal Roué 46fba47efb Merge pull request #731 from groue/dev/private-ValueReducer
Hide ValueObservation implementation details
2020-03-11 22:43:10 +01:00
Gwendal Roué bf3f97b64d Fix compiler warning 2020-03-11 22:42:48 +01:00
Gwendal Roué b605076bd0 Remove value reducers from README 2020-03-11 22:15:04 +01:00
Gwendal Roué 329b034423 CHANGELOG 2020-03-11 22:13:51 +01:00
Gwendal Roué 5e0535d511 ValueReducer creation does not need database access 2020-03-11 22:00:07 +01:00
Gwendal Roué b96d71d937 Remove public ValueObservation factory methods that accept a _ValueReducer 2020-03-11 21:38:48 +01:00
Gwendal Roué 28c32c6af8 _ValueReducer is the only protocol accepted by ValueObservation
Also, we now use Never as the bottom reducer which helps us define the ValueObservation factory methods.
2020-03-11 21:38:41 +01:00
Gwendal Roué f80c5ce348 Make the ValueReducer protocol unavailable
# Conflicts:
#	GRDB/ValueObservation/ValueReducer/ValueReducer.swift
2020-03-11 21:38:20 +01:00
Gwendal Roué cc16a00f5a Merge pull request #729 from groue/dev/ValueObservation-initial-value
ValueObservation always emits an initial value
2020-03-10 23:03:39 +01:00
Gwendal Roué 4f74997235 Restore old disabled tests for cancelled ValueObservation 2020-03-10 22:06:41 +01:00
Gwendal Roué 2f4187b084 DatabaseWriter.remove(transactionObserver:) can run from the writer queue 2020-03-10 22:06:08 +01:00
Gwendal Roué 9a6d6cf9c0 Update documentation for ValueObservation scheduling 2020-03-10 22:04:58 +01:00
Gwendal Roué 26e2db02aa CHANGELOG 2020-03-10 21:04:38 +01:00
Gwendal Roué d66f2c8cfd Simplify ValueObservation starting process 2020-03-10 20:50:06 +01:00
Gwendal Roué 6f239a5ad3 All ValueObservationScheduling cases now trigger an initial fetch 2020-03-10 19:42:58 +01:00
Gwendal Roué 2224042114 Rename ValueScheduling to ValueObservationScheduling 2020-03-10 19:10:38 +01:00
Gwendal Roué 4fe201f8aa Merge branch 'development' into GRDB5 2020-03-10 19:05:29 +01:00
Gwendal Roué e48b654ad6 Merge pull request #728 from groue/dev/ValueObservation-error-handling
Make ValueObservation error handling mandatory
2020-03-10 08:26:09 +01:00
Gwendal Roué 3467376d7a Remove unused ErrorCatcher 2020-03-10 08:19:27 +01:00
Gwendal Roué 1b6f9f9971 CHANGELOG 2020-03-10 08:12:17 +01:00
Gwendal Roué c70b627f92 ValueObservation.start(in:onChange:) is unavailable
Hiding errors from user's sight was not a good idea
2020-03-10 08:09:53 +01:00
Gwendal Roué 0b34ad55b6 Merge pull request #724 from groue/dev/SE-0242
SE-0242: Synthesize default values for the memberwise initializer
2020-03-09 09:02:03 +01:00
Gwendal Roué 262cdc5b9a CHANGELOG 2020-03-09 08:50:43 +01:00
Gwendal Roué 19061934ce SE-0242: Synthesize default values for the memberwise initializer
...and more initializers cleanup
2020-03-09 08:49:06 +01:00
Gwendal Roué 7614f36bbd Merge pull request #723 from groue/dev/SE-0255
SE-0255: Implicit returns from single-expression functions
2020-03-09 08:17:24 +01:00
Gwendal Roué f48180549d make smokeTest
For "quick" sanity checks
2020-03-09 08:03:26 +01:00
Gwendal Roué 93aa9bf3e5 Comment out debugging configuration 2020-03-09 07:56:02 +01:00
Gwendal Roué 4d60dc6cbb Remove more redundant return keywords 2020-03-09 07:52:35 +01:00
Gwendal Roué 1698afadb9 CHANGELOG 2020-03-09 07:33:30 +01:00
Gwendal Roué 9aa67f9db9 SE-0255: Implicit returns from single-expression functions 2020-03-08 23:12:46 +01:00
Gwendal Roué 57d12e6c47 Merge pull request #722 from groue/dev/SE-0253
SE-0253: Callable values of user-defined nominal types
2020-03-08 20:40:17 +01:00
Gwendal Roué cc9fbed07e CHANGELOG 2020-03-08 20:39:54 +01:00
Gwendal Roué 8718d525d4 SE-0253: Callable values of user-defined nominal types 2020-03-08 20:36:49 +01:00
Gwendal Roué 3beba2b578 Merge pull request #721 from groue/dev/SE-0249
SE-0249: Key Path Expressions as Functions
2020-03-08 20:10:27 +01:00
Gwendal Roué 1b08a822ee CHANGELOG 2020-03-08 20:09:15 +01:00
Gwendal Roué 7865b0a2ee SE-0249: Key Path Expressions as Functions 2020-03-08 19:58:51 +01:00
Gwendal Roué a31984724e Merge pull request #720 from groue/dev/GRDB5-removeDeprecated
Turn deprecated APIs into unavailable ones
2020-03-08 19:15:41 +01:00
Gwendal Roué a504452846 CHANGELOG 2020-03-08 19:10:48 +01:00
Gwendal Roué 00b0dc2a04 Remove availability checks for macOS 10.10 (forgotten in #719) 2020-03-08 19:08:15 +01:00
Gwendal Roué 41e0885bce Fix deprecation warning 2020-03-08 18:10:02 +01:00
Gwendal Roué 694adcec64 Remove other deprecated methods 2020-03-08 18:03:11 +01:00
Gwendal Roué 5dd86d2453 Remove deprecated ValueObservation methods 2020-03-08 17:53:39 +01:00
Gwendal Roué b9d4a5215a Remove deprecated DatabaseMigrator methods 2020-03-08 17:13:31 +01:00
Gwendal Roué 456d2aee75 Remove deprecated SQLExpressionLiteral 2020-03-08 16:57:29 +01:00
Gwendal Roué 02890a6d3a Remove deprecated SQLLiteral.mapSQL(_:) 2020-03-08 16:28:44 +01:00
Gwendal Roué 0f503fe0db Remove deprecated FetchRequest.prepare(_: forSingleResult:) 2020-03-08 16:18:55 +01:00
Gwendal Roué bfdd0696da Remove deprecated setupMemoryManagement methods 2020-03-08 16:08:12 +01:00
Gwendal Roué 130e510f8c Remove deprecated passphrase methods 2020-03-08 16:00:19 +01:00
Gwendal Roué 512764403f Prepare for fixits for removed deprecated methods 2020-03-08 15:39:40 +01:00
Gwendal Roué b85eca3260 Merge pull request #719 from groue/dev/swift5.2
Bump required Swift version to 5.2
2020-03-08 14:59:53 +01:00
Gwendal Roué 73975e4462 CHANGELOG 2020-03-08 14:53:35 +01:00
Gwendal Roué 816887b811 Fix typo in README 2020-03-08 14:53:27 +01:00
Gwendal Roué 20baaf9a7f Update README for the new requirements 2020-03-08 13:54:00 +01:00
Gwendal Roué 9578f984ec Remove useless #if compiler/swift checks 2020-03-08 13:42:44 +01:00
Gwendal Roué 3b7f232aef WIP 2020-03-08 13:01:15 +01:00
Gwendal Roué df1ed3cf2f Apply requirements to .travis.yml
osx_image xcode11.4 is not yet shipped, according to https://docs.travis-ci.com/user/reference/osx/#xcode-version
2020-03-08 12:59:33 +01:00
Gwendal Roué 59eceb9af1 Apply requirements to Makefile 2020-03-08 12:57:09 +01:00
Gwendal Roué d7e821785d Fix podfiles of CocoaPods tests 2020-03-08 12:35:59 +01:00
Gwendal Roué b264087a3b Fixes for GRDBDemoWatchOS
Hide WKRefreshBackgroundTask use behind an availability check

Bump IPHONEOS_DEPLOYMENT_TARGET = 13.0, so that we can use CollectionDifference
2020-03-08 12:22:09 +01:00
Gwendal Roué 759bb8cd25 Fix dependencies of GRDBtvOSTests
It used to depend on the iOS version of GRDB - WTF
2020-03-08 11:28:04 +01:00
Gwendal Roué 4486f73432 Apply requirements to podspec and podfiles 2020-03-08 10:55:48 +01:00
Gwendal Roué 224e0b7d58 Apply requirements to Xcode projects
Update:
SWIFT_VERSION
IPHONEOS_DEPLOYMENT_TARGET
MACOSX_DEPLOYMENT_TARGET
TVOS_DEPLOYMENT_TARGET
WATCHOS_DEPLOYMENT_TARGET
2020-03-08 10:55:26 +01:00
Gwendal Roué 9db86ff2d6 Apply Swift version requirement to Tests/SPM/PlainPackage 2020-03-08 10:45:40 +01:00
Gwendal Roué f3af89cb6a Apply requirements to Package.swift 2020-03-08 10:26:01 +01:00
Gwendal Roué 98e9cc7861 Bump required macOS version to 10.10
This guarantees SQLite 3.7.16+, so that all migrations can recreate tables when needed
2020-03-08 10:24:27 +01:00
Gwendal Roué 30f7b39a42 Update requirements for Swift 5.2 2020-03-08 09:54:13 +01:00
Gwendal Roué 6b9e7e7eb3 Kick off GRDB5 2020-03-08 09:50:08 +01:00
415 changed files with 9556 additions and 14084 deletions

No files matched your search

+2 -1
View File
@@ -106,7 +106,8 @@ Podfile.lock
# SPM
.build
Package.resolved
GRDB.xcworkspace/xcshareddata/swiftpm
#Package.resolved
Tests/SPM/Packages
# Ruby
-9
View File
@@ -1,12 +1,3 @@
[submodule "Tests/Performance/fmdb"]
path = Tests/Performance/fmdb
url = https://github.com/ccgus/fmdb.git
[submodule "Tests/Performance/SQLite.swift"]
path = Tests/Performance/SQLite.swift
url = https://github.com/stephencelis/SQLite.swift.git
[submodule "Tests/Performance/Realm"]
path = Tests/Performance/Realm
url = https://github.com/realm/realm-cocoa.git
[submodule "SQLiteCustom/src"]
path = SQLiteCustom/src
url = https://github.com/swiftlyfalling/SQLiteLib.git
+64 -296
View File
@@ -28,413 +28,181 @@ jobs:
include:
###########################################
## Test GRDB Xcode 11
## Test GRDB Xcode 11.4
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_minSwift
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
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 <MIN>)
# script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
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 <MIN>)
# script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 11
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 11
## Test GRDBCustom Xcode 11.4
- stage: Test GRDBCustom Xcode 11
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
- stage: Test GRDBCustom Xcode 11
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- stage: Test GRDBCustom Xcode 11
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
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 <MIN>)
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 11
## Test SQLCipher Xcode 11.4
- stage: Test SQLCipher Xcode 11
- stage: Test SQLCipher Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=SQLCipher 3
script: make test_framework_SQLCipher3
- stage: Test SQLCipher Xcode 11
- stage: Test SQLCipher Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=SQLCipher 4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 11
## Test Installation Xcode 11.4
# Manual Install
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=Manual Install
script: make test_install_manual
# CocoaPods Lint
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=CocoaPods Lint
script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=SPM Package
script: make test_install_SPM_Package
# SPM Install
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11
osx_image: xcode11.4
env:
- TID=SPM Package in Xcode Project
script: make test_install_SPM_Project
# Custom SQLite Install
- stage: Test Installation Xcode 11
- stage: Test Installation Xcode 11.4
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 <MAX>)
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 <MIN>)
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 <MAX>)
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 <MIN>)
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
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- 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=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=GRDBiOS (Swift 5, iOS <MAX>)
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 5, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=GRDBtvOS (Swift 5, tvOS <MAX>)
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 5, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDB Xcode 10.1
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDB Xcode 10
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
# CocoaPods Install GRDB
- stage: Test Installation Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# Custom SQLite Install
- stage: Test Installation Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=Custom SQLite
script: make test_install_customSQLite
+6
View File
@@ -4,6 +4,12 @@ Here is a list of people who were happy to meet GRDB :-)
---
https://twitter.com/layoutsubviews/status/1249940744929816582
> Mixing SQLite / GRDB with Combine is my whole world right now, and it is delightful.
---
https://twitter.com/steipete/status/1231105339954802694
> It [Core Data] gets the job done, but folks made some really amazing Swift native sqlite wrappers.
+65
View File
@@ -11,8 +11,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
-->
#### 5.x Releases
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
#### 4.x Releases
- `4.14.x` Releases - [4.14.0](#4140)
- `4.13.x` Releases - [4.13.0](#4130)
- `4.12.x` Releases - [4.12.0](#4120) | [4.12.1](#4121) | [4.12.2](#4122)
- `4.11.x` Releases - [4.11.0](#4110)
- `4.10.x` Releases - [4.10.0](#4100)
@@ -69,6 +76,63 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
-->
## GRDB5 Branch
### Documentation Diff
- The [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) Guide helps migrating your apps and turn your attention where it needs to focus during the upgrade.
- The [ValueObservation](README.md#valueobservation) chapter has been fully rewritten and describes the new ValueObservation behaviors.
- The [DatabaseError](README.md#databaseerror) chapter demonstrates the new way to catch and match DatabaseError on their codes, in a fashion similar to CocoaError et al.
- The [Batch Updates](README.md#update-requests) chapter has been updated for the new `set(to:)` method.
### New
- [#749](https://github.com/groue/GRDB.swift/pull/749): Drop submodules used by performance tests
- [#754](https://github.com/groue/GRDB.swift/pull/754): Match DatabaseError on ResultCode
- [#756](https://github.com/groue/GRDB.swift/pull/756): Export the underlying SQLite library
### Breaking Changes
- [#719](https://github.com/groue/GRDB.swift/pull/719): Bump required Swift version to 5.2
- [#720](https://github.com/groue/GRDB.swift/pull/720): Turn deprecated APIs into unavailable ones
- [#722](https://github.com/groue/GRDB.swift/pull/722): SE-0253: Callable values of user-defined nominal types
- [#728](https://github.com/groue/GRDB.swift/pull/728): Make ValueObservation error handling mandatory
- [#729](https://github.com/groue/GRDB.swift/pull/729): ValueObservation always emits an initial value
- [#731](https://github.com/groue/GRDB.swift/pull/731): Hide ValueObservation implementation details
- [#732](https://github.com/groue/GRDB.swift/pull/732): Remove ValueObservation.compactMap
- [#736](https://github.com/groue/GRDB.swift/pull/736): Relax ValueObservation Guarantees
- [#737](https://github.com/groue/GRDB.swift/pull/737): Force implicit database region for ValueObservation
- [#738](https://github.com/groue/GRDB.swift/pull/738): Remove all observationForCount/All/First methods
- [#742](https://github.com/groue/GRDB.swift/pull/742): ValueObservation scheduling is no longer an attribute of the observation
- [#745](https://github.com/groue/GRDB.swift/pull/745): Explicit ValueObservation cancellation
- [#747](https://github.com/groue/GRDB.swift/pull/747): Rename GRDBCustomSQLite to GRDB
- [#750](https://github.com/groue/GRDB.swift/pull/750): Batch updates do not need any operator
- [#752](https://github.com/groue/GRDB.swift/pull/752): Remove ValueObservation.combine
## 4.14.0
Released April 23, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.13.0...v4.14.0)
**New**
- [#766](https://github.com/groue/GRDB.swift/pull/766) by [@mtancock](https://github.com/mtancock): Add Codable support to DatabaseDateComponents
## 4.13.0
Released April 15, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.12.2...v4.13.0)
**Fixed**
- Restored support for Xcode 10.0 and Xcode 10.1, broken in 4.12.2
- [#759](https://github.com/groue/GRDB.swift/pull/759): Fix batch updates of complex requests
**New**
- [#761](https://github.com/groue/GRDB.swift/pull/761): Deprecate the batch update `<-` operator
## 4.12.2
Released April 13, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.12.1...v4.12.2)
@@ -118,6 +182,7 @@ Released March 21, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compar
migrator.appliedMigrations(in: dbQueue)
```
## 4.11.0
Released March 2, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.10.0...v4.11.0)
+15 -16
View File
@@ -91,14 +91,14 @@ With GRDB associations, we can streamline these operations (and others), by decl
extension Author {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
request(for: Author.books)
}
}
extension Book {
static let author = belongsTo(Author.self)
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
request(for: Book.author)
}
}
```
@@ -165,7 +165,7 @@ Generally speaking, associations use the [TableRecord], [FetchableRecord], and [
extension Book: EncodableRecord {
// The request for the author of a book.
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
request(for: Book.author)
}
}
@@ -327,7 +327,7 @@ As in the examples above, **HasManyThrough** association is always built from tw
```swift
struct Document: TableRecord {
static let paragraphs = hasMany(
Paragraph.self,
Paragraph.self,
through: Document.hasMany(Section.self),
using: Section.hasMany(Paragraph.self))
...
@@ -785,7 +785,7 @@ struct Book: TableRecord, EncodableRecord {
/// The request for the author of a book
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
request(for: Book.author)
}
}
```
@@ -806,7 +806,7 @@ struct Author: TableRecord, EncodableRecord {
/// The request for the books of an author
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
request(for: Author.books)
}
}
@@ -1140,7 +1140,7 @@ extension Team {
static let players = hasMany(Player.self).order(Column("position"))
var players: QueryInterfaceRequest<Player> {
return request(for: Team.players)
request(for: Team.players)
}
}
```
@@ -1174,7 +1174,7 @@ extension Team {
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
var players: QueryInterfaceRequest<Player> {
return request(for: Team.players)
request(for: Team.players)
}
}
@@ -1383,7 +1383,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
extension DerivableRequest where RowDecoder == Author {
/// Filters authors by country
func filter(country: String) -> Self {
return filter(Column("country") == country)
filter(Column("country") == country)
}
}
@@ -1391,7 +1391,7 @@ extension DerivableRequest where RowDecoder == Author {
extension DerivableRequest where RowDecoder == Book {
/// Filters books by author country
func filter(authorCountry: String) -> Self {
return joining(required: Book.author.filter(country: country))
joining(required: Book.author.filter(country: country))
}
/// Order books by author name and then book title
@@ -1610,8 +1610,7 @@ And who is the most able to know those coding keys? BookInfo itself, thanks to i
```swift
extension BookInfo {
static func all() -> QueryInterfaceRequest<BookInfo> {
return Book
.including(optional: Book.coverImage)
Book.including(optional: Book.coverImage)
.including(required: Book.author
.forKey(CodingKeys.authorInfo) // (1)
.including(optional: Person.country))
@@ -1758,7 +1757,7 @@ When you need to compute aggregates **from a single record**, you use [regular a
struct Author: TableRecord, EncodableRecord {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
request(for: Author.books)
}
}
@@ -2306,17 +2305,17 @@ Those methods are defined on extensions to the `DerivableRequest` protocol:
```swift
extension DerivableRequest where RowDecoder == Author {
func filter(country: String) -> Self {
return filter(Column("country") == country)
filter(Column("country") == country)
}
func orderedByName() -> Self {
return order(Column("name").collating(.localizedCaseInsensitiveCompare))
order(Column("name").collating(.localizedCaseInsensitiveCompare))
}
}
extension DerivableRequest where RowDecoder == Book {
func filter(country: String) -> Self {
return joining(required: Book.author.filter(country: country))
joining(required: Book.author.filter(country: country))
}
}
```
+1 -1
View File
@@ -128,7 +128,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
Now you can use GRDB with your custom SQLite build:
```swift
import GRDBCustomSQLite
import GRDB
let dbQueue = try DatabaseQueue(...)
```
@@ -15,6 +15,7 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate {
// Use this method to pause ongoing tasks, disable timers, etc.
}
@available(watchOSApplicationExtension 3.0, *)
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
@@ -1,7 +1,6 @@
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@@ -43,20 +43,6 @@
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 */;
@@ -224,8 +210,6 @@
children = (
56606D0A2355931F00185962 /* GRDB.framework */,
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */,
56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */,
56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.xctest */,
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */,
56606D142355931F00185962 /* GRDB.framework */,
56606D162355931F00185962 /* GRDBiOSTests.xctest */,
@@ -432,20 +416,6 @@
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXPerformanceTests.xctest;
remoteRef = 56606D0D2355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
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;
@@ -608,7 +578,6 @@
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Debug;
};
@@ -625,7 +594,6 @@
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Release;
};
@@ -643,7 +611,6 @@
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Debug;
};
@@ -661,7 +628,6 @@
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Release;
};
@@ -715,12 +681,14 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
name = Debug;
};
@@ -768,11 +736,13 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
name = Release;
};
@@ -35,11 +35,11 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
extension Player {
static func orderedByName() -> QueryInterfaceRequest<Player> {
return Player.order(Columns.name)
Player.order(Columns.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
return Player.order(Columns.score.desc, Columns.name)
Player.order(Columns.score.desc, Columns.name)
}
}
@@ -57,10 +57,10 @@ extension Player {
"Zazie", "Zoé"]
static func randomName() -> String {
return names.randomElement()!
names.randomElement()!
}
static func randomScore() -> Int {
return 10 * Int.random(in: 0...100)
10 * Int.random(in: 0...100)
}
}
@@ -10,8 +10,8 @@ class PlayersViewController: UITableViewController {
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var players: [Player] = []
private var playersObserver: TransactionObserver?
private var playerCountObserver: TransactionObserver?
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
@@ -75,11 +75,10 @@ class PlayersViewController: UITableViewController {
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
playerCountObserver = observation.start(
playerCountCancellable = observation.start(
in: dbQueue,
onError: { error in
fatalError("Unexpected error: \(error)")
},
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
switch count {
@@ -96,45 +95,47 @@ class PlayersViewController: UITableViewController {
let observation = ValueObservation.tracking { db in
try request.fetchAll(db)
}
playersObserver = observation.start(
playersCancellable = observation.start(
in: dbQueue,
onError: { error in
fatalError("Unexpected error: \(error)")
},
scheduling: .immediate,
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)
}
}
}
}, completion: nil)
self.updateTableView(players)
})
}
private func updateTableView(_ players: [Player]) {
// Compute difference between current and new list of players
let difference = players
.difference(from: self.players)
.inferringMoves()
// Apply those changes to the table view
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)
}
}
}
}, completion: nil)
}
}
@@ -174,7 +175,7 @@ extension PlayersViewController {
extension PlayersViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players.count
players.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+1 -1
View File
@@ -313,7 +313,7 @@ final class SynonymsTokenizer : FTS5WrapperTokenizer {
}
func synonyms(for token: String) -> Set<String>? {
return synonyms.first { $0.contains(token) }
synonyms.first { $0.contains(token) }
}
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
+2 -2
View File
@@ -227,11 +227,11 @@ The table view data source asks the fetched records controller to provide releva
```swift
func numberOfSections(in tableView: UITableView) -> Int {
return fetchedRecordsController.sections.count
fetchedRecordsController.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedRecordsController.sections[section].numberOfRecords
fetchedRecordsController.sections[section].numberOfRecords
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
-522
View File
@@ -1,522 +0,0 @@
Migrating From GRDB 2 to GRDB 3
===============================
GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications.
**For all users**
- [Swift 4.1 Required]
- [iOS 8 Sunsetting]
- [Database Schema Recommendations]
- [Record Protocols Renaming]
- [Columns Definition]
**By topic**
- [If You Use Database Queues]
- [If You Use Database Pools]
- [If You Use Database Snapshots]
- [If You Use Record Types]
- [If You Use Custom Requests]
- [If You Use RxGRDB]
- [Notable Documentation Updates]
## Swift 4.1 Required
GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+.
## iOS 8 Sunsetting
GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
## Database Schema Recommendations
GRDB 2 was totally schema-agnostic, and would gladly accept any database.
GRDB 3 still accepts any database, but brings two schema recommendations:
- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused.
When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key:
```diff
try db.create(table: "author") { t in
- t.column("id", .integer).primaryKey() // GRDB 2
+ t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation
t.column("name", .text).notNull()
}
```
- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'.
This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below.
Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema:
```swift
var migrator = DatabaseMigrator()
// Existing GRDB 2 migration:
migrator.registerMigration("initial") { db in
try db.create(table: "authors") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text).notNull()
}
try db.create(table: "books") { t in
t.column("id", .integer).primaryKey()
t.column("authorId", .integer).notNull().references("authors")
t.column("title", .text).notNull()
}
}
// New GRDB 3 migration:
// - Rename tables so that they look like Swift identifiers (singular and camelCased)
// - Make integer primary keys auto-incremented
//
// Since several tables are recreated from scratch, referential integrity
// constraints may break during the process. The
// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign
// key checks are temporarily disabled, and checked at the end:
migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer).notNull().references("author")
t.column("title", .text).notNull()
}
try db.execute("""
INSERT INTO author SELECT * FROM authors;
INSERT INTO book SELECT * FROM books;
""")
try db.drop(table: "authors")
try db.drop(table: "books")
}
```
## Record Protocols Renaming
GRDB 3 has renamed the [record protocols]:
- `RowConvertible` -> `FetchableRecord`
- `TableMapping` -> `TableRecord`
- `Persistable` -> `PersistableRecord`
- `MutablePersistable` -> `MutablePersistableRecord`
After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits.
## Columns Definition
GRDB 2 has you define columns of the query interface with the Column type:
```swift
// GRDB 2
let nameColumn = Column("name")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
A recommended practice was to define enum namespaces in record types:
```swift
// GRDB 2
struct Player: RowConvertible, TableMapping {
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let score = Column("score")
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
score = row[Columns.score]
}
}
```
In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums:
```swift
// GRDB 3
struct Player: FetchableRecord, TableRecord {
enum Columns: String, ColumnExpression {
case id, name, score
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
score = row[Columns.score]
}
}
extension Player {
static func filter(name: String) -> QueryInterfaceRequest<Player> {
return filter(Columns.name == name)
}
static var maximumScore: QueryInterfaceRequest<Int> {
return select(max(Columns.score), as: Int.self)
}
}
```
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) to safely define database columns:
```swift
// GRDB 3
struct Player: Codable {
var id: Int64
var name: String
var score: Int
}
extension Player: FetchableRecord, PersistableRecord {
enum Columns {
static let id = Column(CodingKeys.id.stringValue)
static let name = Column(CodingKeys.name.stringValue)
static let score = Column(CodingKeys.score.stringValue)
}
static func filter(name: String) -> QueryInterfaceRequest<Player> {
return filter(Columns.name == name)
}
static var maximumScore: QueryInterfaceRequest<Int> {
return select(max(Columns.score), as: Int.self)
}
}
```
## If You Use Database Queues
With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods:
```swift
// GRDB 2
let players = try dbQueue.inDatabase { db in
try Player.fetchAll(db)
}
try dbQueue.inDatabase { db in
try player.updateChanges(db)
}
var balance: Amount! = nil
try dbQueue.inTransaction { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
balance = try sourceAccount.fetchBalance(db)
return .commit
}
```
The code above still runs, unchanged, in GRDB 3.
Yet it is now recommended that you use the `read` and `write` methods instead:
```swift
// GRDB 3
let players = try dbQueue.read { db in
try Player.fetchAll(db)
}
try dbQueue.write { db in
try player.updateChanges(db)
}
let balance = try dbQueue.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
return try sourceAccount.fetchBalance(db)
}
```
The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot.
With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen.
When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all.
Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter.
## If You Use Database Pools
With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods:
```swift
// GRDB 2
let players = try dbPool.read { db in
try Player.fetchAll(db)
}
try dbPool.write { db in
try player.updateChanges(db)
}
var balance: Amount! = nil
try dbPool.writeInTransaction { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
balance = try sourceAccount.fetchBalance(db)
return .commit
}
```
In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below:
```swift
// GRDB 3
let balance = try dbPool.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
return try sourceAccount.fetchBalance(db)
}
```
Side effect: you can no longer open explicit transactions inside a `write` block:
```swift
// GRDB 2: OK
// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`:
// cannot start a transaction within a transaction
try dbPool.write { db in
try db.inTransaction { ... }
}
```
When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter.
The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database:
```swift
// GRDB 2: unsafe
// GRDB 3: safe
try dbPool.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
}
```
Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk.
## If You Use Database Snapshots
With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example:
```swift
// GRDB 2
let snapshot: DatabaseSnapshot = try dbPool.write { db in
try Player.deleteAll()
return dbPool.makeSnapshot()
}
// Guaranteed to be zero
let count = try snapshot.read { db in
try Player.fetchCount(db)
}
```
GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction."
To avoid this error, you will need [precise transaction handling]:
```swift
// GRDB 3
let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in
try Player.deleteAll()
return dbPool.makeSnapshot()
}
```
## If You Use Record Types
Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name:
```swift
// GRDB 2
struct Place: TableMapping {
static let databaseTableName = "place"
}
print(Place.databaseTableName) // print "place"
```
With GRDB 3, the `databaseTableName` property gets a default implementation:
```swift
// GRDB 3
struct Place: TableRecord { }
print(Place.databaseTableName) // print "place"
```
That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier:
- Place: `place`
- Country: `country`
- PostalAddress: `postalAddress`
- HTTPRequest: `httpRequest`
- TOEFL: `toefl`
When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name:
```swift
// GRDB 2 and GRDB 3
class Place: Record {
override var databaseTableName: String {
return "place"
}
}
```
## If You Use Custom Requests
[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need.
You may, for example, use `SQLRequest`:
```swift
// GRDB 2
extension Player {
static func filter(color: Color) -> AnyTypedRequest<Player> {
let sql = "SELECT * FROM players WHERE color = ?"
let request = SQLRequest(sql, arguments: [color])
return request.asRequest(of: Player.self)
}
}
let players = try Player.filter(color: .red).fetchAll(db)
```
The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type:
```swift
// GRDB 3
extension Player {
static func filter(color: Color) -> SQLRequest<Player> {
let sql = "SELECT * FROM players WHERE color = ?"
return SQLRequest(sql, arguments: [color])
}
}
let players = try Player.filter(color: .red).fetchAll(db)
```
See the updated [Custom Requests](../README.md#custom-requests) chapter for more information.
## If You Use RxGRDB
Some RxGRDB APIs have slightly changed. Did you track multiple requests at the same time with "fetch tokens"?
```swift
// GRDB 2
dbQueue.rx
.fetchTokens(in: [request, ...])
.mapFetch { db in try fetchResult(db) }
.subscribe(...)
```
Now you'll write instead:
```swift
// GRDB 3
ValueObservation
.tracking([request, ...], fetch: { db in try fetchResult(db) })
.rx
.fetch(in: dbQueue)
.subscribe(...)
```
It's just a syntactic change, without any impact on the runtime.
GRDB 3.6 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
For example:
```swift
// GRDB 2: Track a team and its players
let teamId = 1
let teamRequest = Team.filter(key: teamId)
let playersRequest = Player.filter(teamId: teamId)
dbQueue.rx
.fetchTokens(in: [teamRequest, playersRequest])
.mapFetch { db -> TeamInfo? in
guard let team = try teamRequest.fetchOne(db) else {
return nil
}
let players = try playersRequest.fetchAll(db)
return TeamInfo(team: team, players: players)
}
.subscribe(onNext: { teamInfo: TeamInfo? in
...
})
// GRDB 3: Track a team and its players
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
let request = TeamInfoRequest(teamId: 1)
ValueObservation.tracking(request, fetch: { try request.fetchOne($0) })
.rx
.fetch(in: dbQueue)
.subscribe(onNext: { teamInfo: TeamInfo? in
...
})
```
## Notable Documentation Updates
If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter:
- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods.
- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look.
- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
[How To Upgrade]: #how-to-upgrade
[Database Schema Recommendations]: #database-schema-recommendations
[Record Protocols Renaming]: #record-protocols-renaming
[Columns Definition]: #columns-definition
[Swift 4.1 Required]: #swift-41-required
[iOS 8 Sunsetting]: #ios-8-sunsetting
[If You Use Database Queues]: #if-you-use-database-queues
[If You Use Database Pools]: #if-you-use-database-pools
[If You Use Database Snapshots]: #if-you-use-database-snapshots
[If You Use Record Types]: #if-you-use-record-types
[If You Use Custom Requests]: #if-you-use-custom-requests
[If You Use RxGRDB]: #if-you-use-rxgrdb
[Notable Documentation Updates]: #notable-documentation-updates
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[Associations]: AssociationsBasics.md
[DatabaseMigrator]: ../README.md#migrations
[database observation tools]: ../README.md#database-changes-observation
[Transactions and Savepoints]: ../README.md#transactions-and-savepoints
[precise transaction handling]: ../README.md#transactions-and-savepoints
[DatabaseQueue]: ../README.md#database-queues
[DatabasePool]: ../README.md#database-pools
[database snapshots]: ../README.md#database-snapshots
[FMDB]: http://github.com/ccgus/fmdb
[record protocols]: ../README.md#record-protocols-overview
[Custom requests]: ../README.md#custom-requests
[query interface]: ../README.md#the-query-interface
[DatabaseRegionConvertible]: https://github.com/groue/GRDB.swift#the-databaseregionconvertible-protocol
[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
-187
View File
@@ -1,187 +0,0 @@
Migrating From GRDB 3 to GRDB 4
===============================
GRDB 4 comes with new features, but also a few breaking changes. This guide aims at helping you upgrading your applications.
- [New requirements](#new-requirements)
- [Raw SQL](#raw-sql)
- [ValueObservation](#valueobservation)
- [Associations](#associations)
- [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md)
- [SQLCipher](#sqlcipher)
- [PersistenceError.recordNotFound](#persistenceerrorrecordnotfound)
### New requirements
GRDB now requires Swift 4.2+ and Xcode 10+. Swift 4.0 and 4.1 are no longer supported. Xcode 9 is no longer supported.
iOS 8 is no longer supported. The minimum iOS target is now iOS 9.
### Raw SQL
Whenever your application uses raw SQL queries or snippets, you will now always have to use the `sql` argument label:
```swift
// GRDB 3
try db.execute("INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
let playerCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")
// GRDB 4
try db.execute(sql: "INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
let playerCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")
```
This change was made necessary by the introduction of [SQL Interpolation].
### ValueObservation
[ValueObservation] has been refreshed in GRDB 4.
To guarantee asynchronous notifications, and never ever block your main thread, use the `.async(onQueue:startImmediately:)` scheduling:
```swift
// On main queue
var observation = Player.observationForAll()
observation.scheduling = .async(onQueue: .main, startImmediately: true)
let observer = try observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { (players: [Player]) in
// On main queue
print("fresh players: \(players)")s
})
// <- here "fresh players" is not printed yet.
```
In GRDB 3, this scheduling used to be named `.queue(_: startImmediately:)`.
The second breaking change is `ValueObservation.extent`, which was removed in GRDB 4. Now all observations last until the observer returned by the `start` method is deallocated.
### Associations
GRDB 4 brought a few new [associations] features:
- **Indirect associations** [HasOneThrough] and [HasManyThrough] let you define associations from a record to another through a third one. For example, they let you easily express many-to-many relations such as "a country has many citizens through its passports":
```swift
struct Country: TableRecord, EncodableRecord {
static let passports = hasMany(Passport.self)
// New!
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
var citizens: QueryInterfaceRequest<Citizen> {
return request(for: Country.citizens)
}
}
struct Passport: TableRecord {
static let citizen = belongsTo(Citizen.self)
}
struct Citizen: TableRecord {
}
let country: Country = ...
let citizens: [Citizen] = try dbQueue.read { db in
try country.citizens.fetchAll(db)
}
```
![HasManyThroughSchema](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/HasManyThroughSchema.svg)
- **Eager loading of HasMany associations**: The new `including(all:)` method lets you load arrays or sets of associated records in a single request:
```swift
// All authors with their respective books
let request = Author.including(all: Author.books)
// This request can feed the following record:
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var books: [Book] // all associated books
}
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
See [Joining And Prefetching Associated Records] for more information.
- **Automatic pluralization and singularization** of association identifiers.
GRDB will automatically **pluralize** or **singularize** names in order to help you easily associate records.
For example, the Book and Author records will automatically feed properties named `books`, `author`, or `bookCount` in your decoded records, without any explicit configuration, as long as the names of the backing database tables are "book" and "author".
The GRDB pluralization mechanisms are very powerful, being capable of pluralizing and singularizing both regular and irregular words (it's directly inspired from the battle-tested [Ruby on Rails inflections](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize)).
However, this change may have introduced some incompatibilities with GRDB 3 associations. Check [The Structure of a Joined Request] for more information.
### SQLCipher
The integration of GRDB with SQLCipher has changed.
1. With GRDB 3, it was possible to perform a manual installation, or to use CocoaPods and the GRDBCipher pod.
With GRDB 4, CocoaPods is the only supported installation method. And the GRDBCipher pod is discontinued, replaced with GRDB.swift/SQLCipher:
```diff
-pod 'GRDBCipher'
+pod 'GRDB.swift/SQLCipher'
```
In your Swift code, you no longer import the GRDBCipher module, but GRDB:
```diff
-import GRDBCipher
+import GRDB
```
2. The default SQLCipher version which comes with GRDB 4 is now SQLCipher 4, which is incompatible with SQLCipher 3. SQLCipher 3 is still supported, though. See [Encryption] for more details.
3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `prepareDatabase` property of the configuration:
```swift
var configuration = Configuration()
configuration.passphrase = "secret"
configuration.prepareDatabase = { db in
try db.execute(sql: "PRAGMA cipher_page_size = 4096")
try db.execute(sql: "PRAGMA kdf_iter = 128000")
}
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
```
### PersistenceError.recordNotFound
PersistenceError.recordNotFound is thrown whenever a record update method does not find any database row to update. It was refactored in GRDB 4:
```swift
public enum PersistenceError: Error {
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
}
do {
try player.updateChanges {
$0.score += 1000
}
} catch let error as PersistenceError.recordNotFound {
// Update failed because player does not exist in the database
print(error)
// prints "Key not found in table player: [id:42]"
}
```
[SQL Interpolation]: SQLInterpolation.md
[ValueObservation]: ../README.md#valueobservation
[Encryption]: ../README.md#encryption
[HasOneThrough]: AssociationsBasics.md#hasonethrough
[HasManyThrough]: AssociationsBasics.md#hasmanythrough
[PersistableRecord]: ../README.md#persistablerecord-protocol
[associations]: AssociationsBasics.md
[EncodableRecord]: ../README.md#persistablerecord-protocol
[The Structure of a Joined Request]: AssociationsBasics.md#the-structure-of-a-joined-request
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
+371
View File
@@ -0,0 +1,371 @@
Migrating From GRDB 4 to GRDB 5
===============================
**This guide aims at helping you upgrading your applications from GRDB 4 to GRDB 5.**
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
- [New requirements](#new-requirements)
- [ValueObservation](#valueobservation)
- [Other Changes](#other-changes)
## Preparing the Migration to GRDB 5
If you haven't made it yet, upgrade to the [latest GRDB 4 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 5 upgrade.
GRDB 5 ships with fix-its that will suggest simple syntactic changes, and won't require you to think much.
Your attention will be needed, though, in the area of database observation.
## New requirements
GRDB requirements have been bumped:
- **Swift 5.2+** (was Swift 4.2+)
- **Xcode 11.4+** (was Xcode 10.0+)
- iOS 9.0+ (unchanged)
- **macOS 10.10+** (was macOS 10.9+)
- tvOS 9.0+ (unchanged)
- watchOS 2.0+ (unchanged)
## ValueObservation
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
Those changes have the vanilla GRDB, [GRDBCombine], and [RxGRDB], offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
In the end, this migration step might require some work. But it's for the benefit of all!
- [Creating ValueObservation](#creating-valueobservation)
- [Starting ValueObservation](#starting-valueobservation)
- [Runtime Behavior of ValueObservation](#runtime-behavior-of-valueobservation)
- [Removed ValueObservation Methods](#removed-valueobservation-methods)
### Creating ValueObservation
In GRDB 5, you *always* create a ValueObservation by providing a function that fetches the observed value:
```swift
// GRDB 5
let observation = ValueObservation.tracking { db in
/* fetch and return the observed value */
}
// For example, an observation of [Player], which tracks all players:
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
// The same observation, using shorthand notation:
let observation = ValueObservation.tracking(Player.fetchAll)
```
If the tracked value is computed from several database requests that are not always the same, make sure you use the `trackingVaryingRegion` method, as below. See [Observing a Varying Database Region] for more information.
```swift
// An observation which does not always execute the same requests:
let observation = ValueObservation.trackingVaryingRegion { db -> Int in
let preference = try Preference.fetchOne(db) ?? .default
switch preference.selection {
case .food: return try Food.fetchCount(db)
case .beverage: return try Beverage.fetchCount(db)
}
}
```
Several methods that build observations were removed:
```swift
// BEFORE: GRDB 4
let observation = request.observationForCount()
let observation = request.observationForFirst()
let observation = request.observationForAll()
let observation = ValueObservation.tracking(value: someFetchFunction)
let observation = ValueObservation.tracking(..., fetch: { db in ... })
// NEW: GRDB 5
let observation = ValueObservation.tracking(request.fetchCount)
let observation = ValueObservation.tracking(request.fetchOne)
let observation = ValueObservation.tracking(request.fetchAll)
let observation = ValueObservation.tracking(someFetchFunction)
let observation = ValueObservation.tracking { db in ... }
```
Finally, ValueObservation used to let application define custom "reducers" based on a protocol name ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
<details>
<summary>RxGRDB impact</summary>
```swift
// BEFORE: GRDB 4
request.rx.observeCount(in: dbQueue)
request.rx.observeFirst(in: dbQueue)
request.rx.observeAll(in: dbQueue)
// NEW: GRDB 5
ValueObservation.tracking(request.fetchCount).rx.observe(in: dbQueue)
ValueObservation.tracking(request.fetchOne).rx.observe(in: dbQueue)
ValueObservation.tracking(request.fetchAll).rx.observe(in: dbQueue)
```
</details>
### Starting ValueObservation
The `start` method which starts observing the database has changed as well.
```swift
// Start observing the database
let cancellable = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in print("fresh value: \(value)") })
```
1. The result of the `start` method is now a DatabaseCancellable which allows you to explicitly stop an observation:
```swift
// BEFORE: GRDB 4
let observer: TransactionObserver?
observer = observation.start(...)
observer = nil // Stop the observation
// NEW: GRDB 5
let cancellable: DatabaseCancellable
cancellable = observation.start(...)
cancellable.cancel() // Stop the observation
```
The returned DatabaseCancellable cancels itself when it gets deinitialized.
2. The `onError` handler of the `start` method is now mandatory:
```swift
// BEFORE: GRDB 4
do {
try observation.start(in: dbQueue) { value in
print("fresh value: \(value)")
}
} catch { ... }
// NEW: GRDB 5
observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in print("fresh value: \(value)") })
```
### Runtime Behavior of ValueObservation
**The behavior of ValueObservation has changed**.
The changes can quite impact your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
1. ValueObservation used to notify its initial value *immediately* when the observation starts. Now, it notifies fresh values on the main thread, *asynchronously*, by default.
This means that the parts of your application that rely on this immediate value to, say, set up their user interface, have to be modified. Otherwise, they may suffer from a brief flash of missing data, during the short amount of time between the beginning of the observation, and the asynchronous delivery of the initial value.
To be granted with an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let cancellable = observation.start(
in: dbQueue,
// Opt in for immediate notification of the initial value
scheduling: .immediate,
onError: { error in ... },
onChange: { [weak self] (players: [Player]) in
guard let self = self else { return }
self.updateView(players)
})
// <- Here the view has already been updated.
```
Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise.
<details>
<summary>GRDBCombine impact</summary>
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let cancellable = observation
.publisher(in: dbQueue)
// Opt in for immediate notification of the initial value
.scheduling(.immediate)
.sink(...)
```
</details>
<details>
<summary>RxGRDB impact</summary>
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let disposable = observation
.rx.observe(in: dbQueue)
// Opt in for immediate notification of the initial value
.scheduling(.immediate)
.subscribe(...)
```
</details>
2. ValueObservation used to notify one fresh value for each and every database transaction that had an impact on the tracked value. Now, it may coalesce notifications. If your application relies on exactly one notification per transaction, use [DatabaseRegionObservation] instead.
3. Some value observations used to automatically remove duplicate values. This is no longer automatic. If your application relies on distinct consecutive values, use the [removeDuplicates] operator.
4. ValueObservation used to prevent a database connection (DatabaseQueue or DatabasePool) from closing. Now an observation just stops emitting any fresh value when the database connection closes.
5. ValueObservation used to be able to restart notifying fresh values after it has notified an error. Now an error marks the end of the observation.
6. ValueObservation used to have a `scheduling` property, which has been removed.
You can remove the explicit request to dispatch fresh values asynchronously on the main dispatch queue, because it is now the default behavior:
```swift
// BEFORE: GRDB 4
var observation = ValueObservation.tracking(...)
observation.scheduling = .async(onQueue: .main, startImmediately: true)
observation.start(in: dbQueue, onError: ..., onChange: ...)
// NEW: GRDB 5
let observation = ValueObservation.tracking(...)
observation.start(in: dbQueue, onError: ..., onChange: ...)
```
For other dispatch queues, use the `scheduling` parameter of the `start` method:
```swift
let queue: DispatchQueue = ...
// BEFORE: GRDB 4
var observation = ValueObservation.tracking(...)
observation.scheduling = .async(onQueue: queue, startImmediately: true)
observation.start(in: dbQueue, onError: ..., onChange: ...)
// NEW: GRDB 5
let observation = ValueObservation.tracking(...)
observation.start(in: dbQueue, scheduling: .async(onQueue: queue), onError: ..., onChange: ...)
```
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for eventual changes. It is up to your application to ignore this initial value if it wants to.
### Removed ValueObservation Methods
1. ValueObservation used to have a `compactMap` method. This method has been removed without any replacement.
If your application uses GRDBCombine or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
2. ValueObservation used to have a `combine` method. This method has been removed without any replacement.
In your application, replace combined observations with a single observation:
```swift
// BEFORE: GRDB 4
let playerCountObservation = ValueObservation.tracking(Player.fetchCount)
let bestPlayersObservation = ValueObservation.tracking(Player
.limit(10)
.order(Column("score").desc)
.fetchAll)
let observation = ValueObservation
.combine(playerCountObservation, bestPlayersObservation)
.map(HallOfFame.init)
// NEW: GRDB 5
let observation = ValueObservation.tracking { db -> HallOfFame in
let playerCount = try Player.fetchCount(db)
let bestPlayers = try Player
.limit(10)
.order(Column("score").desc)
.fetchAll(db)
return HallOfFame(playerCount: playerCount, bestPlayers: bestPlayers)
}
```
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
## Other Changes
1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
```swift
// BEFORE: GRDB 4
try Player.updateAll(db, Column("score") <- 0)
// NEW: GRDB 5
try Player.updateAll(db, Column("score").set(to: 0))
```
2. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
Player.select(myFunction.call(Column("name")))
// NEW: GRDB 5
Player.select(myFunction(Column("name")))
```
3. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
```swift
// BEFORE: GRDB 4
struct MyRequest: FetchRequest {
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement = ...
let adapter: RowAdapter? = ...
return (statement, adapter)
}
}
// NEW: GRDB 5
struct MyRequest: FetchRequest {
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
let statement: SelectStatement = ...
let adapter: RowAdapter? = ...
return PreparedRequest(statement: statement, adapter: adapter)
}
}
```
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
import GRDBCustomSQLite
// NEW: GRDB 5
import GRDB
```
5. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
```swift
// BEFORE: GRDB 4
import CSQLite // When GRDB is included with the Swift Package Manager
import SQLCipher // When GRDB is linked to SQLCipher
import SQLite3 // When GRDB is linked to System SQLite
let sqliteVersion = String(cString: sqlite3_libversion())
// NEW: GRDB 5
import GRDB
let sqliteVersion = String(cString: sqlite3_libversion())
```
[ValueObservation]: ../README.md#valueobservation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
[Custom SQL functions]: ../README.md#custom-sql-functions
[Batch updates]: ../README.md#update-requests
@@ -197,7 +197,7 @@ extension DerivableRequest where RowDecoder == Author {
/// Returns a request for all authors from a country
func filter(country: String) -> Self {
return filter(Author.Columns.country == country)
filter(Author.Columns.country == country)
}
}
```
@@ -230,8 +230,8 @@ extension DerivableRequest where RowDecoder == Book {
func filter(authorCountry: String) -> Self {
// A book is from a country if it can be
// joined with an author from that country:
// ---------------------------------v
return joining(required: Book.author.filter(country: authorCountry))
// ---------------------------v
joining(required: Book.author.filter(country: authorCountry))
}
}
@@ -249,7 +249,7 @@ Not *every requests* can be expressed on `DerivableRequest`. For example, [Assoc
extension QueryInterfaceRequest where RowDecoder == Author {
/// Returns a request for all authors with at least one book
func havingBooks() -> QueryInterfaceRequest<Author> {
return having(Author.books.isEmpty == false)
having(Author.books.isEmpty == false)
}
}
```
@@ -388,14 +388,14 @@ A last extension on your record types will further help navigation from records
extension Author {
/// The request for the author's books
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
request(for: Author.books)
}
}
extension Book {
/// The request for the author of the book
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
request(for: Book.author)
}
}
```
@@ -530,19 +530,19 @@ class ImprovedLibraryManager {
}
func author(id: Int64) throws -> Author? {
return try dbQueue.read { db in
try dbQueue.read { db in
try Author.fetchOne(db, key: id)
}
}
func book(id: Int64) throws -> Book? {
return try dbQueue.read { db in
try dbQueue.read { db in
try Book.fetchOne(db, key: id)
}
}
func books(writtenBy author: Author) throws -> [Book] {
return try dbQueue.read { db in
try dbQueue.read { db in
try author.books.fetchAll(db)
}
}
@@ -593,7 +593,7 @@ extension LibraryManager {
}
func authorList() throws -> [AuthorListItem] {
return try dbQueue.read { db in
try dbQueue.read { db in
let request = Author
.annotated(with: Author.books.count)
.orderByName()
@@ -610,7 +610,7 @@ extension LibraryManager {
}
func bookInfo(bookId: Int64) throws -> BookInfo? {
return try dbQueue.read { db in
try dbQueue.read { db in
guard let book = try Book.fetchOne(db, key: bookId) else {
return nil
}
@@ -630,7 +630,7 @@ extension LibraryManager {
}
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
return try dbQueue.read { db in
try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
@@ -61,16 +61,12 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord {
extension Author {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
}
var books: QueryInterfaceRequest<Book> { request(for: Author.books) }
}
extension Book {
static let author = belongsTo(Author.self)
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
}
var author: QueryInterfaceRequest<Author> { request(for: Book.author) }
}
//: Populate the database
@@ -47,13 +47,13 @@ import GRDB
//: Everything starts from our class hierarchy:
class Base {
var description: String { return "Base" }
var description: String { "Base" }
init() { }
}
class Foo: Base {
var name: String
override var description: String { return "Foo: \(name)" }
override var description: String { "Foo: \(name)" }
init(name: String) {
self.name = name
super.init()
@@ -62,7 +62,7 @@ class Foo: Base {
class Bar: Base {
var score: Int
override var description: String { return "Bar: \(score)" }
override var description: String { "Bar: \(score)" }
init(score: Int) {
self.score = score
super.init()
@@ -302,15 +302,15 @@ extension FetchRequest where RowDecoder: MyDatabaseDecoder {
// MARK: - FetchRequest fetching methods
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
return try RowDecoder.fetchCursor(db, self)
try RowDecoder.fetchCursor(db, self)
}
func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] {
return try RowDecoder.fetchAll(db, self)
try RowDecoder.fetchAll(db, self)
}
func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? {
return try RowDecoder.fetchOne(db, self)
try RowDecoder.fetchOne(db, self)
}
}
@@ -335,15 +335,15 @@ extension MyDatabaseDecoder where Self: TableRecord {
// MARK: - Static fetching methods
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
return try all().fetchCursor(db)
try all().fetchCursor(db)
}
static func fetchAll(_ db: Database) throws -> [DecodedType] {
return try all().fetchAll(db)
try all().fetchAll(db)
}
static func fetchOne(_ db: Database) throws -> DecodedType? {
return try all().fetchOne(db)
try all().fetchOne(db)
}
}
@@ -366,15 +366,15 @@ extension MyDatabaseDecoder {
// MARK: - Fetch from SQL
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -79,7 +79,7 @@ class TestDeleteAll: NSObject {
struct MyRecord: FetchableRecord, TableRecord, PersistableRecord {
static let MyColumn = Column("MyColumn")
static var databaseTableName: String { return String(describing: self) }
static var databaseTableName: String { String(describing: self) }
let myColumn: String
@@ -34,9 +34,7 @@ try! migrator.migrate(dbQueue)
class TableChangeObserver : NSObject, TransactionObserver {
private var changedTableNames: Set<String> = []
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return true
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
func databaseDidChange(with event: DatabaseEvent) {
changedTableNames.insert(event.tableName)
+14 -14
View File
@@ -184,25 +184,25 @@ extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
return """
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
"""
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
/// A complex request
@@ -247,7 +247,7 @@ Let's breakdown each one of those methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
}
```
@@ -271,7 +271,7 @@ Let's breakdown each one of those methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
}
```
@@ -293,7 +293,7 @@ Let's breakdown each one of those methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
}
```
@@ -315,10 +315,10 @@ Let's breakdown each one of those methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
return """
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
"""
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
}
```
+9 -8
View File
@@ -120,23 +120,24 @@ let players = try Player.fetchAll(db)
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change. The [GRDBCombine] and [RxGRDB] companion libraries provide support for [Combine] and [RxSwift].
```swift
let playersObservation = ValueObservation.tracking { db in
/// An observation of [Player]
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
// Vanilla GRDB
let observer = playersObservation.start(in: dbQueue,
let cancellable = observation.start(in: dbQueue,
onError: { error in ... },
onChange: { (players: [Player]) in print("Players have changed") })
onChange: { (players: [Player]) in print("Fresh players") })
// GRDBCombine
let cancellable = playersObservation.publisher(in: dbQueue).sink(
let cancellable = observation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Players have changed") })
receiveValue: { (players: [Player]) in print("Fresh players") })
// RxGRDB
let disposable = playersObservation.rx.observe(in: dbQueue).subscribe(
onNext: { (players: [Player]) in print("Players have changed") },
let disposable = observation.rx.observe(in: dbQueue).subscribe(
onNext: { (players: [Player]) in print("Fresh playerss") },
onError: { error in ... })
```
@@ -246,7 +247,7 @@ try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)")
extension Player {
static func filter(name: String) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.name) = \(name)"
"SELECT * FROM player WHERE name = \(name)"
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '4.12.2'
s.version = '4.14.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -9,9 +9,9 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.swift_versions = ['4.2', '5.0']
s.swift_versions = ['5.2']
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.9'
s.osx.deployment_target = '10.10'
s.watchos.deployment_target = '2.0'
s.tvos.deployment_target = '9.0'
s.default_subspec = 'standard'
File diff suppressed because it is too large. Load diff
-3
View File
@@ -47,9 +47,6 @@
<FileRef
location = "group:GRDBCustom.xcodeproj">
</FileRef>
<FileRef
location = "group:Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj">
</FileRef>
<FileRef
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
</FileRef>
+3 -33
View File
@@ -1,12 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Configuration for a DatabaseQueue or DatabasePool.
public struct Configuration {
@@ -111,22 +104,6 @@ public struct Configuration {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var observesSuspensionNotifications = false
// MARK: - Encryption
#if SQLITE_HAS_CODEC
// TODO: remove when the deprecated passphrase turns unavailable.
var _passphrase: String?
/// The passphrase for the encrypted database.
///
/// Default: nil
@available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
public var passphrase: String? {
get { return _passphrase }
set { _passphrase = newValue }
}
#endif
// MARK: - Managing SQLite Connections
/// A function that is run when an SQLite connection is opened, before the
@@ -197,8 +174,8 @@ public struct Configuration {
///
/// The quality of service is ignored if you supply a target queue.
///
/// Default: .default (.unspecified on macOS < 10.10)
public var qos: DispatchQoS
/// Default: .default
public var qos: DispatchQoS = .default
/// The target queue for all database accesses.
///
@@ -216,14 +193,7 @@ public struct Configuration {
// MARK: - Factory Configuration
/// Creates a factory configuration
public init() {
if #available(OSX 10.10, *) {
qos = .default
} else {
qos = .unspecified
}
}
public init() { }
// MARK: - Not Public
+19 -19
View File
@@ -33,7 +33,7 @@ extension Sequence {
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
{
return AnyCursor(self).flatMap(transform)
AnyCursor(self).flatMap(transform)
}
}
@@ -92,7 +92,7 @@ extension Cursor {
/// Returns a Boolean value indicating whether the cursor contains
/// an element.
public func isEmpty() throws -> Bool {
return try next() == nil
try next() == nil
}
/// Returns a Boolean value indicating whether the cursor contains an
@@ -123,12 +123,12 @@ extension Cursor {
/// // Prints: "0: foo"
/// // Prints: "1: bar"
public func enumerated() -> EnumeratedCursor<Self> {
return EnumeratedCursor(self)
EnumeratedCursor(self)
}
/// Returns the elements of the cursor that satisfy the given predicate.
public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self> {
return FilterCursor(self, isIncluded)
FilterCursor(self, isIncluded)
}
/// Returns the first element of the cursor that satisfies the given
@@ -147,7 +147,7 @@ extension Cursor {
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{
return map(transform).filter { $0 != nil }.map { $0! }
map(transform).filter { $0 != nil }.map { $0! }
}
/// Returns a cursor that skips any initial elements that satisfy
@@ -158,7 +158,7 @@ extension Cursor {
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self> {
return DropWhileCursor(self, predicate: predicate)
DropWhileCursor(self, predicate: predicate)
}
/// Returns a cursor containing all but the given number of initial
@@ -178,7 +178,7 @@ extension Cursor {
/// - Returns: A cursor starting after the specified number of
/// elements.
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
return DropFirstCursor(self, limit: n)
DropFirstCursor(self, limit: n)
}
/// Returns a cursor containing all but the first element of the cursor.
@@ -193,7 +193,7 @@ extension Cursor {
///
/// - Returns: A cursor starting after the first element of the cursor.
public func dropFirst() -> DropFirstCursor<Self> {
return dropFirst(1)
dropFirst(1)
}
/// Returns an array containing all but the given number of final
@@ -243,7 +243,7 @@ extension Cursor {
///
/// - Returns: An array leaving off the last element of the cursor.
public func dropLast() throws -> [Element] {
return try dropLast(1)
try dropLast(1)
}
/// Returns a cursor over the concatenated results of mapping transform
@@ -252,7 +252,7 @@ extension Cursor {
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
where SegmentOfResult: Sequence
{
return flatMap { try AnyCursor(transform($0)) }
flatMap { try AnyCursor(transform($0)) }
}
/// Returns a cursor over the concatenated results of mapping transform
@@ -261,7 +261,7 @@ extension Cursor {
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
where SegmentOfResult: Cursor
{
return map(transform).joined()
map(transform).joined()
}
/// Calls the given closure on each element in the cursor.
@@ -274,7 +274,7 @@ extension Cursor {
/// Returns a cursor over the results of the transform function applied to
/// this cursor's elements.
public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T> {
return MapCursor(self, transform)
MapCursor(self, transform)
}
/// Returns the maximum element in the cursor, using the given predicate as
@@ -334,7 +334,7 @@ extension Cursor {
/// - Returns: A cursor starting at the beginning of this cursor
/// with at most `maxLength` elements.
public func prefix(_ maxLength: Int) -> PrefixCursor<Self> {
return PrefixCursor(self, maxLength: maxLength)
PrefixCursor(self, maxLength: maxLength)
}
/// Returns a cursor of the initial consecutive elements that satisfy
@@ -345,7 +345,7 @@ extension Cursor {
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self> {
return PrefixWhileCursor(self, predicate: predicate)
PrefixWhileCursor(self, predicate: predicate)
}
/// Returns the result of calling the given combining closure with each
@@ -448,7 +448,7 @@ extension Cursor where Element: Comparable {
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func max() throws -> Element? {
return try max(by: <)
try max(by: <)
}
/// Returns the minimum element in the cursor.
@@ -460,7 +460,7 @@ extension Cursor where Element: Comparable {
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func min() throws -> Element? {
return try min(by: <)
try min(by: <)
}
}
@@ -469,7 +469,7 @@ extension Cursor where Element: Comparable {
extension Cursor where Element: Cursor {
/// Returns the elements of this cursor of cursors, concatenated.
public func joined() -> FlattenCursor<Self> {
return FlattenCursor(self)
FlattenCursor(self)
}
}
@@ -478,7 +478,7 @@ extension Cursor where Element: Cursor {
extension Cursor where Element: Sequence {
/// Returns the elements of this cursor of sequences, concatenated.
public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>> {
return flatMap { $0 }
flatMap { $0 }
}
}
@@ -545,7 +545,7 @@ public final class AnyCursor<Element>: Cursor {
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
return try element()
try element()
}
}
+12 -20
View File
@@ -1,11 +1,3 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Schema
@@ -28,7 +20,7 @@ extension Database {
/// Returns whether a table exists.
public func tableExists(_ name: String) throws -> Bool {
return try exists(type: .table, name: name)
try exists(type: .table, name: name)
}
/// Returns whether a table is an internal SQLite table.
@@ -50,17 +42,17 @@ extension Database {
///
/// Those are tables whose name begins with "grdb_".
public func isGRDBInternalTable(_ tableName: String) -> Bool {
return tableName.starts(with: "grdb_")
tableName.starts(with: "grdb_")
}
/// Returns whether a view exists.
public func viewExists(_ name: String) throws -> Bool {
return try exists(type: .view, name: name)
try exists(type: .view, name: name)
}
/// Returns whether a trigger exists.
public func triggerExists(_ name: String) throws -> Bool {
return try exists(type: .trigger, name: name)
try exists(type: .trigger, name: name)
}
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
@@ -152,7 +144,7 @@ extension Database {
}
default:
// Multi-columns primary key
primaryKey = .regular(pkColumns.map { $0.name })
primaryKey = .regular(pkColumns.map(\.name))
}
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
@@ -180,10 +172,10 @@ extension Database {
let unique: Bool = row[2]
let columns = try Row
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { row -> (Int, String) in
.map({ row -> (Int, String) in
// [seqno:0 cid:2 name:"column"]
(row[0] as Int, row[2] as String)
}
})
.sorted { $0.0 < $1.0 }
.map { $0.1 }
return IndexInfo(name: indexName, columns: columns, unique: unique)
@@ -209,7 +201,7 @@ extension Database {
throws -> Bool
where T.Iterator.Element == String
{
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
/// The foreign keys defined on table named `tableName`.
@@ -531,7 +523,7 @@ public struct PrimaryKeyInfo {
private let impl: Impl
static func rowID(_ column: String) -> PrimaryKeyInfo {
return PrimaryKeyInfo(impl: .rowID(column))
PrimaryKeyInfo(impl: .rowID(column))
}
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
@@ -589,12 +581,12 @@ public struct ForeignKeyInfo {
/// The origin columns
public var originColumns: [String] {
return mapping.map { $0.origin }
mapping.map(\.origin)
}
/// The destination columns
public var destinationColumns: [String] {
return mapping.map { $0.destination }
mapping.map(\.destination)
}
}
@@ -618,7 +610,7 @@ struct SchemaInfo: Equatable {
/// All names for a given type
func names(ofType type: SchemaObjectType) -> Set<String> {
return objects.reduce(into: []) { (set, key) in
objects.reduce(into: []) { (set, key) in
if key.type == type.rawValue {
set.insert(key.name)
}
+13 -31
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
@@ -21,7 +14,7 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(sql: String) throws -> SelectStatement {
return try makeSelectStatement(sql: sql, prepFlags: 0)
try makeSelectStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
@@ -36,7 +29,7 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -52,12 +45,12 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
return try publicStatementCache.selectStatement(sql)
try publicStatementCache.selectStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
return try internalStatementCache.selectStatement(sql)
try internalStatementCache.selectStatement(sql)
}
/// Returns a new prepared statement that can be reused.
@@ -70,7 +63,7 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
return try makeUpdateStatement(sql: sql, prepFlags: 0)
try makeUpdateStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
@@ -85,7 +78,7 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -101,12 +94,12 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
return try publicStatementCache.updateStatement(sql)
try publicStatementCache.updateStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
return try internalStatementCache.updateStatement(sql)
try internalStatementCache.updateStatement(sql)
}
/// Executes one or several SQL statements, separated by semi-colons.
@@ -228,6 +221,10 @@ extension Database {
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.selectedRegion)
}
let authorizer = observationBroker.updateStatementWillExecute(statement)
let sqliteStatement = statement.sqliteStatement
var code: Int32 = SQLITE_OK
@@ -302,22 +299,7 @@ extension Database {
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
// Don't record schema introspection queries, which may be
// run, or not, depending on the state of the schema cache.
//
// This gives us a quick way to make sure that the observation
// below, which runs schema introspection queries as a side effect,
// only tracks the "player" table:
//
// let observation = ValueObservation.tracking { db in
// try Player.fetchOne(db, key: 1)
// }
//
// Strictly speaking, this prevents the recording of all schema
// queries. But we assume, until proven wrong, that such recording
// isn't needed by anyone.
let region = statement.databaseRegion.ignoringInternalSQLiteTables()
_selectedRegion.formUnion(region)
_selectedRegion.formUnion(statement.selectedRegion)
}
}
+15 -92
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A raw SQLite connection, suitable for the SQLite C API.
public typealias SQLiteConnection = OpaquePointer
@@ -126,10 +119,10 @@ public final class Database {
lazy var publicStatementCache = StatementCache(database: self)
/// The last error code
public var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
public var lastErrorCode: ResultCode { ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
/// The last error message
public var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
public var lastErrorMessage: String? { String(cString: sqlite3_errmsg(sqliteConnection)) }
/// Statement authorizer. Use withAuthorizer(_:_:).
fileprivate var _authorizer: StatementAuthorizer?
@@ -220,9 +213,6 @@ public final class Database {
#if SQLITE_HAS_CODEC
try validateSQLCipher()
if let passphrase = configuration._passphrase {
try _usePassphrase(passphrase)
}
#endif
// Last step before we can start accessing the database.
@@ -426,48 +416,6 @@ public final class Database {
}
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
}
#endif
}
private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) {
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
// > statements or unfinished sqlite3_backup objects then
// > sqlite3_close() will leave the database connection open and
// > return SQLITE_BUSY.
let code = sqlite3_close(sqliteConnection)
if code != SQLITE_OK, let log = logError {
// A rare situation where GRDB doesn't fatalError on
// unprocessed errors.
let message = String(cString: sqlite3_errmsg(sqliteConnection))
log(ResultCode(rawValue: code), "could not close database: \(message)")
if code == SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
}
}
private static func closeConnection_v2(
_ sqliteConnection: SQLiteConnection,
_ sqlite3_close_v2: @convention(c) (OpaquePointer?) -> Int32)
{
// https://www.sqlite.org/c3ref/close.html
// > If sqlite3_close_v2() is called with unfinalized prepared
// > statements and/or unfinished sqlite3_backups, then the database
@@ -548,9 +496,6 @@ public final class Database {
func beginReadOnly() throws {
if configuration.readonly { return }
if _readOnlyDepth == 0 {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
}
_readOnlyDepth += 1
@@ -560,9 +505,6 @@ public final class Database {
if configuration.readonly { return }
_readOnlyDepth -= 1
if _readOnlyDepth == 0 {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
}
}
@@ -587,21 +529,25 @@ public final class Database {
// MARK: - Recording of the selected region
func recordingSelectedRegion<T>(_ block: () throws -> T) rethrows -> (T, DatabaseRegion) {
SchedulingWatchdog.preconditionValidQueue(self)
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
if region.isFullDatabase {
return try block()
}
let oldFlag = self._isRecordingSelectedRegion
let oldRegion = self._selectedRegion
self._isRecordingSelectedRegion = true
self._selectedRegion = DatabaseRegion()
_isRecordingSelectedRegion = true
_selectedRegion = DatabaseRegion()
defer {
self._isRecordingSelectedRegion = oldFlag
if self._isRecordingSelectedRegion {
self._selectedRegion = oldRegion.union(self._selectedRegion)
region.formUnion(_selectedRegion)
_isRecordingSelectedRegion = oldFlag
if _isRecordingSelectedRegion {
_selectedRegion = oldRegion.union(_selectedRegion)
} else {
self._selectedRegion = oldRegion
_selectedRegion = oldRegion
}
}
return try (block(), _selectedRegion)
return try block()
}
// MARK: - Checkpoints
@@ -1178,27 +1124,10 @@ extension Database {
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
// Support for the deprecated method change(passphrase:).
// After it has been called, the passphrase used for opening the
// database must be ignored.
if configuration._passphrase != nil {
return
}
try _usePassphrase(passphrase)
}
/// See usePassphrase(_:)
private func _usePassphrase(_ passphrase: String) throws {
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
@@ -1217,15 +1146,9 @@ extension Database {
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
// swiftlint:disable:previous line_length
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
-7
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A Collation is a string comparison function used by SQLite.
public final class DatabaseCollation {
+130 -33
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
@@ -20,12 +13,10 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
public var primaryResultCode: ResultCode {
return ResultCode(rawValue: rawValue & 0xFF)
ResultCode(rawValue: rawValue & 0xFF)
}
var isPrimary: Bool {
return self == primaryResultCode
}
var isPrimary: Bool { self == primaryResultCode }
/// Returns true if the code on the left matches the code on the right.
///
@@ -156,21 +147,31 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
// swiftlint:enable operator_usage_whitespace line_length
}
extension ResultCode {
/// Returns true if the code on the left matches the error on the right.
///
/// Primary result codes match themselves and their extended result codes,
/// while extended result codes match only themselves.
///
/// do {
/// try ...
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
/// // foreign key constraint error
/// } catch ResultCode.SQLITE_CONSTRAINT {
/// // any other constraint error
/// } catch {
/// // any other database error
/// }
public static func ~= (lhs: Self, rhs: Error) -> Bool {
guard let error = rhs as? DatabaseError else { return false }
return lhs ~= error.extendedResultCode
}
}
// CustomStringConvertible
extension ResultCode {
var errorString: String? {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return String(cString: sqlite3_errstr(rawValue))
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
#endif
String(cString: sqlite3_errstr(rawValue))
}
/// :nodoc:
@@ -201,7 +202,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
///
/// See also `extendedResultCode`.
public var resultCode: ResultCode {
return extendedResultCode.primaryResultCode
extendedResultCode.primaryResultCode
}
/// The SQLite extended error code (see
@@ -250,6 +251,108 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
let arguments: StatementArguments?
}
// Support for `catch DatabaseError.SQLITE_XXX`
extension DatabaseError {
public static let SQLITE_OK = ResultCode.SQLITE_OK
public static let SQLITE_ERROR = ResultCode.SQLITE_ERROR
public static let SQLITE_INTERNAL = ResultCode.SQLITE_INTERNAL
public static let SQLITE_PERM = ResultCode.SQLITE_PERM
public static let SQLITE_ABORT = ResultCode.SQLITE_ABORT
public static let SQLITE_BUSY = ResultCode.SQLITE_BUSY
public static let SQLITE_LOCKED = ResultCode.SQLITE_LOCKED
public static let SQLITE_NOMEM = ResultCode.SQLITE_NOMEM
public static let SQLITE_READONLY = ResultCode.SQLITE_READONLY
public static let SQLITE_INTERRUPT = ResultCode.SQLITE_INTERRUPT
public static let SQLITE_IOERR = ResultCode.SQLITE_IOERR
public static let SQLITE_CORRUPT = ResultCode.SQLITE_CORRUPT
public static let SQLITE_NOTFOUND = ResultCode.SQLITE_NOTFOUND
public static let SQLITE_FULL = ResultCode.SQLITE_FULL
public static let SQLITE_CANTOPEN = ResultCode.SQLITE_CANTOPEN
public static let SQLITE_PROTOCOL = ResultCode.SQLITE_PROTOCOL
public static let SQLITE_EMPTY = ResultCode.SQLITE_EMPTY
public static let SQLITE_SCHEMA = ResultCode.SQLITE_SCHEMA
public static let SQLITE_TOOBIG = ResultCode.SQLITE_TOOBIG
public static let SQLITE_CONSTRAINT = ResultCode.SQLITE_CONSTRAINT
public static let SQLITE_MISMATCH = ResultCode.SQLITE_MISMATCH
public static let SQLITE_MISUSE = ResultCode.SQLITE_MISUSE
public static let SQLITE_NOLFS = ResultCode.SQLITE_NOLFS
public static let SQLITE_AUTH = ResultCode.SQLITE_AUTH
public static let SQLITE_FORMAT = ResultCode.SQLITE_FORMAT
public static let SQLITE_RANGE = ResultCode.SQLITE_RANGE
public static let SQLITE_NOTADB = ResultCode.SQLITE_NOTADB
public static let SQLITE_NOTICE = ResultCode.SQLITE_NOTICE
public static let SQLITE_WARNING = ResultCode.SQLITE_WARNING
public static let SQLITE_ROW = ResultCode.SQLITE_ROW
public static let SQLITE_DONE = ResultCode.SQLITE_DONE
public static let SQLITE_ERROR_MISSING_COLLSEQ = ResultCode.SQLITE_ERROR_MISSING_COLLSEQ
public static let SQLITE_ERROR_RETRY = ResultCode.SQLITE_ERROR_RETRY
public static let SQLITE_ERROR_SNAPSHOT = ResultCode.SQLITE_ERROR_SNAPSHOT
public static let SQLITE_IOERR_READ = ResultCode.SQLITE_IOERR_READ
public static let SQLITE_IOERR_SHORT_READ = ResultCode.SQLITE_IOERR_SHORT_READ
public static let SQLITE_IOERR_WRITE = ResultCode.SQLITE_IOERR_WRITE
public static let SQLITE_IOERR_FSYNC = ResultCode.SQLITE_IOERR_FSYNC
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode.SQLITE_IOERR_DIR_FSYNC
public static let SQLITE_IOERR_TRUNCATE = ResultCode.SQLITE_IOERR_TRUNCATE
public static let SQLITE_IOERR_FSTAT = ResultCode.SQLITE_IOERR_FSTAT
public static let SQLITE_IOERR_UNLOCK = ResultCode.SQLITE_IOERR_UNLOCK
public static let SQLITE_IOERR_RDLOCK = ResultCode.SQLITE_IOERR_RDLOCK
public static let SQLITE_IOERR_DELETE = ResultCode.SQLITE_IOERR_DELETE
public static let SQLITE_IOERR_BLOCKED = ResultCode.SQLITE_IOERR_BLOCKED
public static let SQLITE_IOERR_NOMEM = ResultCode.SQLITE_IOERR_NOMEM
public static let SQLITE_IOERR_ACCESS = ResultCode.SQLITE_IOERR_ACCESS
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode.SQLITE_IOERR_CHECKRESERVEDLOCK
public static let SQLITE_IOERR_LOCK = ResultCode.SQLITE_IOERR_LOCK
public static let SQLITE_IOERR_CLOSE = ResultCode.SQLITE_IOERR_CLOSE
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode.SQLITE_IOERR_DIR_CLOSE
public static let SQLITE_IOERR_SHMOPEN = ResultCode.SQLITE_IOERR_SHMOPEN
public static let SQLITE_IOERR_SHMSIZE = ResultCode.SQLITE_IOERR_SHMSIZE
public static let SQLITE_IOERR_SHMLOCK = ResultCode.SQLITE_IOERR_SHMLOCK
public static let SQLITE_IOERR_SHMMAP = ResultCode.SQLITE_IOERR_SHMMAP
public static let SQLITE_IOERR_SEEK = ResultCode.SQLITE_IOERR_SEEK
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode.SQLITE_IOERR_DELETE_NOENT
public static let SQLITE_IOERR_MMAP = ResultCode.SQLITE_IOERR_MMAP
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode.SQLITE_IOERR_GETTEMPPATH
public static let SQLITE_IOERR_CONVPATH = ResultCode.SQLITE_IOERR_CONVPATH
public static let SQLITE_IOERR_VNODE = ResultCode.SQLITE_IOERR_VNODE
public static let SQLITE_IOERR_AUTH = ResultCode.SQLITE_IOERR_AUTH
public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode.SQLITE_IOERR_BEGIN_ATOMIC
public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode.SQLITE_IOERR_COMMIT_ATOMIC
public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode.SQLITE_IOERR_ROLLBACK_ATOMIC
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode.SQLITE_LOCKED_SHAREDCACHE
public static let SQLITE_LOCKED_VTAB = ResultCode.SQLITE_LOCKED_VTAB
public static let SQLITE_BUSY_RECOVERY = ResultCode.SQLITE_BUSY_RECOVERY
public static let SQLITE_BUSY_SNAPSHOT = ResultCode.SQLITE_BUSY_SNAPSHOT
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode.SQLITE_CANTOPEN_NOTEMPDIR
public static let SQLITE_CANTOPEN_ISDIR = ResultCode.SQLITE_CANTOPEN_ISDIR
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode.SQLITE_CANTOPEN_FULLPATH
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode.SQLITE_CANTOPEN_CONVPATH
public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode.SQLITE_CANTOPEN_DIRTYWAL
public static let SQLITE_CORRUPT_VTAB = ResultCode.SQLITE_CORRUPT_VTAB
public static let SQLITE_CORRUPT_SEQUENCE = ResultCode.SQLITE_CORRUPT_SEQUENCE
public static let SQLITE_READONLY_RECOVERY = ResultCode.SQLITE_READONLY_RECOVERY
public static let SQLITE_READONLY_CANTLOCK = ResultCode.SQLITE_READONLY_CANTLOCK
public static let SQLITE_READONLY_ROLLBACK = ResultCode.SQLITE_READONLY_ROLLBACK
public static let SQLITE_READONLY_DBMOVED = ResultCode.SQLITE_READONLY_DBMOVED
public static let SQLITE_READONLY_CANTINIT = ResultCode.SQLITE_READONLY_CANTINIT
public static let SQLITE_READONLY_DIRECTORY = ResultCode.SQLITE_READONLY_DIRECTORY
public static let SQLITE_ABORT_ROLLBACK = ResultCode.SQLITE_ABORT_ROLLBACK
public static let SQLITE_CONSTRAINT_CHECK = ResultCode.SQLITE_CONSTRAINT_CHECK
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode.SQLITE_CONSTRAINT_COMMITHOOK
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode.SQLITE_CONSTRAINT_FUNCTION
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode.SQLITE_CONSTRAINT_NOTNULL
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode.SQLITE_CONSTRAINT_PRIMARYKEY
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode.SQLITE_CONSTRAINT_TRIGGER
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode.SQLITE_CONSTRAINT_UNIQUE
public static let SQLITE_CONSTRAINT_VTAB = ResultCode.SQLITE_CONSTRAINT_VTAB
public static let SQLITE_CONSTRAINT_ROWID = ResultCode.SQLITE_CONSTRAINT_ROWID
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode.SQLITE_NOTICE_RECOVER_WAL
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode.SQLITE_NOTICE_RECOVER_ROLLBACK
public static let SQLITE_WARNING_AUTOINDEX = ResultCode.SQLITE_WARNING_AUTOINDEX
public static let SQLITE_AUTH_USER = ResultCode.SQLITE_AUTH_USER
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode.SQLITE_OK_LOAD_PERMANENTLY
}
extension DatabaseError {
// TODO: test
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
@@ -292,19 +395,13 @@ extension DatabaseError {
/// NSError bridging: the domain of the error.
/// :nodoc:
public static var errorDomain: String {
return "GRDB.DatabaseError"
}
public static var errorDomain: String { "GRDB.DatabaseError" }
/// NSError bridging: the error code within the given domain.
/// :nodoc:
public var errorCode: Int {
return Int(extendedResultCode.rawValue)
}
public var errorCode: Int { Int(extendedResultCode.rawValue) }
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String: Any] {
return [NSLocalizedDescriptionKey: description]
}
public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: description] }
}
+3 -17
View File
@@ -1,11 +1,3 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An SQL function or aggregate.
public final class DatabaseFunction: Hashable {
// SQLite identifies functions by (name + argument count)
@@ -14,11 +6,11 @@ public final class DatabaseFunction: Hashable {
let nArg: Int32 // -1 for variadic functions
}
public var name: String { return identity.name }
public var name: String { identity.name }
private let identity: Identity
let pure: Bool
private let kind: Kind
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Returns an SQL function.
///
@@ -316,15 +308,9 @@ public final class DatabaseFunction: Hashable {
case .string(let string):
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
#if swift(>=5.0)
data.withUnsafeBytes {
sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
}
#else
data.withUnsafeBytes {
sqlite3_result_blob(sqliteContext, $0, Int32(data.count), SQLITE_TRANSIENT)
}
#endif
}
}
@@ -349,7 +335,7 @@ extension DatabaseFunction {
/// Two functions are equal if they share the same name and arity.
/// :nodoc:
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.identity == rhs.identity
lhs.identity == rhs.identity
}
}
+192 -117
View File
@@ -1,12 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if os(iOS)
import UIKit
#endif
@@ -15,9 +8,6 @@ import UIKit
public final class DatabasePool: DatabaseWriter {
private let writer: SerializedDatabase
private var readerPool: Pool<SerializedDatabase>!
// TODO: remove when the deprecated change(passphrase:) method turns unavailable.
private var readerConfiguration: Configuration
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var tokenizerRegistrations: [(Database) -> Void] = []
@@ -26,13 +16,14 @@ public final class DatabasePool: DatabaseWriter {
// MARK: - Database Information
/// The path to the database.
public var path: String {
return writer.path
/// The database configuration
public var configuration: Configuration {
writer.configuration
}
public var configuration: Configuration {
return writer.configuration
/// The path to the database.
public var path: String {
writer.path
}
// MARK: - Initializer
@@ -59,7 +50,7 @@ public final class DatabasePool: DatabaseWriter {
purpose: "writer")
// Readers
readerConfiguration = configuration
var readerConfiguration = configuration
readerConfiguration.readonly = true
// Readers use deferred transactions by default.
@@ -96,7 +87,7 @@ public final class DatabasePool: DatabaseWriter {
readerCount += 1 // protected by pool (TODO: documented this protection behavior)
let reader = try SerializedDatabase(
path: path,
configuration: self.readerConfiguration,
configuration: readerConfiguration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
@@ -138,12 +129,12 @@ public final class DatabasePool: DatabaseWriter {
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupAutomaticMemoryManagement()
setupMemoryManagement()
#endif
}
deinit {
// Undo job done in setupAutomaticMemoryManagement()
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
@@ -205,14 +196,7 @@ extension DatabasePool {
}
}
#if os(iOS)
// swiftlint:disable:next line_length
@available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.")
public func setupMemoryManagement(in application: UIApplication) {
// No op.
}
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
@@ -220,7 +204,7 @@ extension DatabasePool {
/// - param application: The UIApplication that will start a background
/// task to let the database pool release its memory when the application
/// enters background.
private func setupAutomaticMemoryManagement() {
private func setupMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
@@ -262,23 +246,6 @@ extension DatabasePool {
#endif
}
#if SQLITE_HAS_CODEC
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws {
try readerPool.barrier {
try writer.sync { try $0.changePassphrase(passphrase) }
readerPool.removeAll()
readerConfiguration._passphrase = passphrase
}
}
}
#endif
extension DatabasePool: DatabaseReader {
// MARK: - Interrupting Database Operations
@@ -381,21 +348,19 @@ extension DatabasePool: DatabaseReader {
}
}
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
/// let players = try dbQueue.asyncRead { result in
/// let players = try dbQueue.asyncRead { dbResult in
/// do {
/// let db = try result.get()
/// let db = try dbResult.get()
/// let count = try Player.fetchCount(db)
/// } catch {
/// // Handle error
/// }
/// }
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this method throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
/// Attempts to write in the database from this method throw a DatabaseError
/// of resultCode `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
@@ -430,7 +395,50 @@ extension DatabasePool: DatabaseReader {
}
}
}
#endif
/// :nodoc:
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
// First async jump in order to grab a reader connection.
// Honor configuration dispatching (qos/targetQueue).
configuration
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
.async { [weak self] in
guard let self = self else {
block(nil)
return
}
do {
let (reader, releaseReader) = try self.readerPool.get()
// Second async jump because sync could deadlock if
// configuration has a serial targetQueue.
reader.weakAsync { db in
guard let db = db else {
block(nil)
return
}
defer {
try? db.commit() // Ignore commit error
releaseReader()
}
do {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
// Reset the schema cache before running user code in snapshot isolation
db.clearSchemaCache()
block(.success(db))
} catch {
block(.failure(error))
}
}
} catch {
block(.failure(error))
}
}
}
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
@@ -513,66 +521,13 @@ extension DatabasePool: DatabaseReader {
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: DatabaseResult<T>? = nil
var futureResult: Result<T, Error>? = nil
#if compiler(>=5.0)
asyncConcurrentRead { db in
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = DatabaseResult { try block(db.get()) }
futureResult = dbResult.flatMap { db in Result { try block(db) } }
futureSemaphore.signal()
}
#else
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, """
must not be called from inside a transaction. \
If this error is raised from a DatabasePool.write block, use \
DatabasePool.writeWithoutTransaction instead (and use \
transactions when needed).
""")
}
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let isolationSemaphore = DispatchSemaphore(value: 0)
do {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
try? db.commit() // Ignore commit error
releaseReader()
}
do {
try db.beginSnapshotTransaction()
} catch {
futureResult = .failure(error)
isolationSemaphore.signal()
futureSemaphore.signal()
return
}
// Release the writer queue
isolationSemaphore.signal()
// Fetch and release the future
futureResult = DatabaseResult {
// Reset the schema cache before running user code in snapshot isolation
db.clearSchemaCache()
return try block(db)
}
futureSemaphore.signal()
}
} catch {
futureResult = .failure(error)
isolationSemaphore.signal()
futureSemaphore.signal()
}
// Block the writer queue until snapshot isolation success or error
_ = isolationSemaphore.wait(timeout: .distantFuture)
#endif
return DatabaseFuture {
// Block the future until results are fetched
@@ -581,16 +536,13 @@ extension DatabasePool: DatabaseReader {
}
}
#if compiler(>=5.0)
/// Performs the same job as asyncConcurrentRead.
///
/// :nodoc:
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
asyncConcurrentRead(block)
}
#endif
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
/// This method must be called from a writing dispatch queue, outside of any
@@ -611,9 +563,9 @@ extension DatabasePool: DatabaseReader {
/// try Player.deleteAll()
///
/// // Count players concurrently
/// writer.asyncConcurrentRead { result in
/// writer.asyncConcurrentRead { dbResult in
/// do {
/// let db = try result.get()
/// let db = try dbResult.get()
/// // Guaranteed to be zero
/// let count = try Player.fetchCount(db)
/// } catch {
@@ -662,7 +614,7 @@ extension DatabasePool: DatabaseReader {
// Reset the schema cache before running user code in snapshot isolation
db.clearSchemaCache()
block(.success(db))
}
} catch {
@@ -673,7 +625,6 @@ extension DatabasePool: DatabaseReader {
// Block the writer queue until snapshot isolation success or error
_ = isolationSemaphore.wait(timeout: .distantFuture)
}
#endif
/// Invalidates open read-only SQLite connections.
///
@@ -724,7 +675,7 @@ extension DatabasePool: DatabaseReader {
/// - parameter updates: The updates to the database.
/// - throws: The error thrown by the updates.
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.sync(updates)
try writer.sync(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
@@ -741,7 +692,7 @@ extension DatabasePool: DatabaseReader {
/// - parameter updates: The updates to the database.
/// - throws: The error thrown by the updates.
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try readerPool.barrier {
try readerPool.barrier {
try writer.sync(updates)
}
}
@@ -798,7 +749,7 @@ extension DatabasePool: DatabaseReader {
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(updates)
try writer.reentrantSync(updates)
}
/// Asynchronously executes database updates in a protected dispatch queue,
@@ -810,6 +761,11 @@ extension DatabasePool: DatabaseReader {
writer.async(updates)
}
/// :nodoc:
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
writer.weakAsync(updates)
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -857,6 +813,125 @@ extension DatabasePool: DatabaseReader {
forEachConnection { $0.remove(collation: collation) }
}
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
if configuration.readonly {
return _addReadOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
if observation.requiresWriteAccess {
let observer = _addWriteOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
return AnyDatabaseCancellable(cancel: observer.cancel)
}
let observer = _addConcurrent(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
return AnyDatabaseCancellable(cancel: observer.cancel)
}
/// A concurrent observation fetches the initial value without waiting for
/// the writer.
private func _addConcurrent<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> ValueObserver<Reducer> // For testability
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
let observer = ValueObserver<Reducer>(
requiresWriteAccess: observation.requiresWriteAccess,
writer: self,
reducer: observation.makeReducer(),
scheduling: scheduler,
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
onError: onError,
onChange: onChange)
if scheduler.immediateInitialValue() {
do {
// Fetch the initial value without waiting for the writer.
let initialValue = try unsafeReentrantRead(observer.fetchInitialValue)
onChange(initialValue)
// Now wait for the writer
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Don't miss eventual changes between the
// initial fetch and the writer access.
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
} catch {
observer.cancel()
onError(error)
}
} else {
// Fetch the initial value without waiting for the writer.
_weakAsyncRead { [weak self] dbResult in
guard let dbResult = dbResult else { return }
guard let self = self else { return }
if observer.isCompleted { return }
do {
let initialValue = try observer.fetchInitialValue(dbResult.get())
observer.notifyChange(initialValue)
// Now wait for the writer
self._weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Don't miss eventual changes between the
// initial fetch and the writer access.
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
return observer
}
// MARK: - Custom FTS5 Tokenizers
#if SQLITE_ENABLE_FTS5
+72 -44
View File
@@ -12,12 +12,12 @@ public final class DatabaseQueue: DatabaseWriter {
/// The database configuration
public var configuration: Configuration {
return writer.configuration
writer.configuration
}
/// The path to the database file; it is ":memory:" for in-memory databases.
public var path: String {
return writer.path
writer.path
}
// MARK: - Initializers
@@ -44,7 +44,7 @@ public final class DatabaseQueue: DatabaseWriter {
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupAutomaticMemoryManagement()
setupMemoryManagement()
#endif
}
@@ -65,7 +65,7 @@ public final class DatabaseQueue: DatabaseWriter {
}
deinit {
// Undo job done in setupAutomaticMemoryManagement()
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
@@ -85,12 +85,6 @@ extension DatabaseQueue {
}
#if os(iOS)
// swiftlint:disable:next line_length
@available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.")
public func setupMemoryManagement(in application: UIApplication) {
// No op.
}
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
@@ -98,7 +92,7 @@ extension DatabaseQueue {
/// - param application: The UIApplication that will start a background
/// task to let the database queue release its memory when the application
/// enters background.
private func setupAutomaticMemoryManagement() {
private func setupMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
@@ -140,19 +134,6 @@ extension DatabaseQueue {
#endif
}
#if SQLITE_HAS_CODEC
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws {
try writer.sync { try $0.changePassphrase(passphrase) }
}
}
#endif
extension DatabaseQueue {
// MARK: - Interrupting Database Operations
@@ -208,33 +189,30 @@ extension DatabaseQueue {
///
/// This method is *not* reentrant.
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this method throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
/// Attempts to write in the database from this method throw a DatabaseError
/// of resultCode `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync { db in
try writer.sync { db in
try db.readOnly { try block(db) }
}
}
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
/// let players = try dbQueue.asyncRead { result in
/// let players = try dbQueue.asyncRead { dbResult in
/// do {
/// let db = try result.get()
/// let db = try dbResult.get()
/// let count = try Player.fetchCount(db)
/// } catch {
/// // Handle error
/// }
/// }
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this method throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
/// Attempts to write in the database from this method throw a DatabaseError
/// of resultCode `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
@@ -252,7 +230,28 @@ extension DatabaseQueue {
try? db.endReadOnly()
}
}
#endif
/// :nodoc:
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
writer.weakAsync { db in
guard let db = db else {
block(nil)
return
}
do {
try db.beginReadOnly()
} catch {
block(.failure(error))
return
}
block(.success(db))
// Ignore error because we can not notify it.
try? db.endReadOnly()
}
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
@@ -268,7 +267,7 @@ extension DatabaseQueue {
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync(block)
try writer.sync(block)
}
/// Synchronously executes a block in a protected dispatch queue, and
@@ -283,13 +282,13 @@ extension DatabaseQueue {
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(block)
try writer.reentrantSync(block)
}
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(DatabaseResult {
return DatabaseFuture(Result {
// Check that we're on the writer queue...
try writer.execute { db in
// ... and that no transaction is opened.
@@ -301,7 +300,6 @@ extension DatabaseQueue {
})
}
#if compiler(>=5.0)
/// Performs the same job as asyncConcurrentRead.
///
/// :nodoc:
@@ -324,7 +322,6 @@ extension DatabaseQueue {
try? db.endReadOnly()
}
}
#endif
// MARK: - Writing in Database
@@ -376,7 +373,7 @@ extension DatabaseQueue {
/// - parameter updates: The updates to the database.
/// - throws: The error thrown by the updates.
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.sync(updates)
try writer.sync(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
@@ -390,7 +387,7 @@ extension DatabaseQueue {
/// - parameter updates: The updates to the database.
/// - throws: The error thrown by the updates.
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.sync(updates)
try writer.sync(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
@@ -406,7 +403,7 @@ extension DatabaseQueue {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.sync(updates)
try writer.sync(updates)
}
/// Synchronously executes database updates in a protected dispatch queue, and
@@ -420,7 +417,7 @@ extension DatabaseQueue {
/// This method is reentrant. It is unsafe because it fosters dangerous
/// concurrency practices.
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(updates)
try writer.reentrantSync(updates)
}
/// Asynchronously executes database updates in a protected dispatch queue,
@@ -429,6 +426,11 @@ extension DatabaseQueue {
writer.async(updates)
}
/// :nodoc:
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
writer.weakAsync(updates)
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -471,4 +473,30 @@ extension DatabaseQueue {
public func remove(collation: DatabaseCollation) {
writer.sync { $0.remove(collation: collation) }
}
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
if configuration.readonly {
return _addReadOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
let observer = _addWriteOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
return AnyDatabaseCancellable(cancel: observer.cancel)
}
}
+77 -34
View File
@@ -1,10 +1,4 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Dispatch
/// The protocol for all types that can fetch values from a database.
///
@@ -107,8 +101,7 @@ public protocol DatabaseReader: AnyObject {
/// let count = try Player.fetchCount(db)
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
/// and SQLCipher, attempts to write in the database throw a DatabaseError
/// Guarantee 2: attempts to write in the database throw a DatabaseError
/// whose resultCode is `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
@@ -116,16 +109,15 @@ public protocol DatabaseReader: AnyObject {
/// happen while establishing the read access to the database.
func read<T>(_ block: (Database) throws -> T) throws -> T
#if compiler(>=5.0)
/// Asynchronously executes a read-only block that takes a
/// database connection.
///
/// Guarantee 1: the block argument is isolated. Eventual concurrent
/// database updates are not visible inside the block:
///
/// try reader.asyncRead { result in
/// try reader.asyncRead { dbResult in
/// do (
/// let db = try result.get()
/// let db = try dbResult.get()
/// // Those two values are guaranteed to be equal, even if the
/// // `player` table is modified between the two requests:
/// let count1 = try Player.fetchCount(db)
@@ -135,13 +127,16 @@ public protocol DatabaseReader: AnyObject {
/// }
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
/// and SQLCipher, attempts to write in the database throw a DatabaseError
/// Guarantee 2: attempts to write in the database throw a DatabaseError
/// whose resultCode is `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
#endif
/// Same as asyncRead, but without retaining self
///
/// :nodoc:
func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void)
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
@@ -255,14 +250,14 @@ public protocol DatabaseReader: AnyObject {
/// during observation
/// - parameter onChange: a closure that is provided fresh values
/// - returns: a TransactionObserver
func add<Reducer: ValueReducer>(
///
/// :nodoc:
func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
/// Remove a transaction observer.
func remove(transactionObserver: TransactionObserver)
-> DatabaseCancellable
}
extension DatabaseReader {
@@ -298,6 +293,51 @@ extension DatabaseReader {
}
}
extension DatabaseReader {
// MARK: - Value Observation Support
/// Adding an observation in a read-only database emits only the
/// initial value.
func _addReadOnly<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
if scheduler.immediateInitialValue() {
do {
try onChange(unsafeReentrantRead(observation.fetchValue))
} catch {
onError(error)
}
return AnyDatabaseCancellable(cancel: { })
} else {
var isCancelled = false
_weakAsyncRead { dbResult in
guard
!isCancelled,
let dbResult = dbResult
else { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchValue(db) }
}
scheduler.schedule {
guard !isCancelled else { return }
do {
try onChange(result.get())
} catch {
onError(error)
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
}
}
}
/// A type-erased DatabaseReader
///
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
@@ -312,7 +352,7 @@ public final class AnyDatabaseReader: DatabaseReader {
/// :nodoc:
public var configuration: Configuration {
return base.configuration
base.configuration
}
// MARK: - Interrupting Database Operations
@@ -326,24 +366,27 @@ public final class AnyDatabaseReader: DatabaseReader {
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
try base.read(block)
}
#if compiler(>=5.0)
/// :nodoc:
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(block)
}
#endif
/// :nodoc:
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
base._weakAsyncRead(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
try base.unsafeReentrantRead(block)
}
// MARK: - Functions
@@ -373,17 +416,17 @@ public final class AnyDatabaseReader: DatabaseReader {
// MARK: - Value Observation
/// :nodoc:
public func add<Reducer: ValueReducer>(
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
-> DatabaseCancellable
{
return base.add(observation: observation, onError: onError, onChange: onChange)
}
/// :nodoc:
public func remove(transactionObserver: TransactionObserver) {
base.remove(transactionObserver: transactionObserver)
base._add(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
+12 -6
View File
@@ -45,6 +45,12 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
return tableRegions.isEmpty
}
/// Returns whether the region covers the full database: all columns and all
/// rows from all tables.
public var isFullDatabase: Bool {
tableRegions == nil
}
/// The region that covers the full database: all columns and all rows
/// from all tables.
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
@@ -170,7 +176,7 @@ extension DatabaseRegion {
/// Returns whether the content in the region would be impacted if the
/// database were modified by an event of this kind.
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
return intersection(eventKind.modifiedRegion).isEmpty == false
intersection(eventKind.modifiedRegion).isEmpty == false
}
/// Returns whether the content in the region is impacted by this event.
@@ -233,7 +239,7 @@ extension DatabaseRegion {
}
return tableRegions
.sorted(by: { (l, r) in l.key < r.key })
.map { (table, tableRegion) in
.map({ (table, tableRegion) in
var desc = table
if let columns = tableRegion.columns {
desc += "(" + columns.sorted().joined(separator: ",") + ")"
@@ -244,7 +250,7 @@ extension DatabaseRegion {
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
}
return desc
}
})
.joined(separator: ",")
}
}
@@ -319,7 +325,7 @@ public protocol DatabaseRegionConvertible {
extension DatabaseRegion: DatabaseRegionConvertible {
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return self
self
}
}
@@ -337,7 +343,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return try _region(db)
try _region(db)
}
}
@@ -345,7 +351,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
extension DatabaseRegion {
static func union(_ regions: DatabaseRegion...) -> DatabaseRegion {
return regions.reduce(into: DatabaseRegion()) { union, region in
regions.reduce(into: DatabaseRegion()) { union, region in
union.formUnion(region)
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ private class DatabaseRegionObserver: TransactionObserver {
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return region.isModified(byEventsOfKind: eventKind)
region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange(with event: DatabaseEvent) {
+4 -4
View File
@@ -15,7 +15,7 @@ struct DatabaseSchemaCache {
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return primaryKeys[table]
primaryKeys[table]
}
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
@@ -23,7 +23,7 @@ struct DatabaseSchemaCache {
}
func columns(in table: String) -> [ColumnInfo]? {
return columns[table]
columns[table]
}
mutating func set(columns: [ColumnInfo], forTable table: String) {
@@ -31,7 +31,7 @@ struct DatabaseSchemaCache {
}
func indexes(on table: String) -> [IndexInfo]? {
return indexes[table]
indexes[table]
}
mutating func set(indexes: [IndexInfo], forTable table: String) {
@@ -39,7 +39,7 @@ struct DatabaseSchemaCache {
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
return foreignKeys[table]
foreignKeys[table]
}
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
+21 -59
View File
@@ -11,7 +11,7 @@ public class DatabaseSnapshot: DatabaseReader {
/// The database configuration
public var configuration: Configuration {
return serializedDatabase.configuration
serializedDatabase.configuration
}
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
@@ -65,15 +65,14 @@ extension DatabaseSnapshot {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
try serializedDatabase.sync(block)
}
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
/// let players = try snapshot.asyncRead { result in
/// let players = try snapshot.asyncRead { dbResult in
/// do {
/// let db = try result.get()
/// let db = try dbResult.get()
/// let count = try Player.fetchCount(db)
/// } catch {
/// // Handle error
@@ -84,16 +83,20 @@ extension DatabaseSnapshot {
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
serializedDatabase.async { block(.success($0)) }
}
#endif
/// :nodoc:
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
serializedDatabase.weakAsync { block($0.map { .success($0) }) }
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
try serializedDatabase.sync(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.reentrantSync(block)
try serializedDatabase.reentrantSync(block)
}
// MARK: - Functions
@@ -116,61 +119,20 @@ extension DatabaseSnapshot {
serializedDatabase.sync { $0.remove(collation: collation) }
}
// MARK: - Value Observation
// MARK: - Database Observation
public func add<Reducer: ValueReducer>(
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
-> DatabaseCancellable
{
// TODO: fetch asynchronously when possible
do {
// Deal with initial value
switch observation.scheduling {
case .mainQueue:
if let value = try unsafeReentrantRead(observation.fetchFirst) {
if DispatchQueue.isMain {
onChange(value)
} else {
DispatchQueue.main.async {
onChange(value)
}
}
}
case let .async(onQueue: queue, startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.fetchFirst) {
queue.async {
onChange(value)
}
}
}
case let .unsafe(startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.fetchFirst) {
onChange(value)
}
}
}
} catch {
onError(error)
}
// Return a dummy observer, because snapshots never change
return SnapshotValueObserver()
}
public func remove(transactionObserver: TransactionObserver) {
// Can't remove an observer which could not be added :-)
_addReadOnly(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
/// An observer that does nothing, support for
/// `DatabaseSnapshot.add(observation:onError:onChange:)`.
private class SnapshotValueObserver: TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
}
+4 -11
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - DatabaseValue
@@ -209,12 +202,12 @@ extension DatabaseValue {
extension DatabaseValue {
/// Returns self
public var databaseValue: DatabaseValue {
return self
self
}
/// Returns the database value
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue? {
return dbValue
dbValue
}
}
@@ -223,7 +216,7 @@ extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return self
self
}
}
@@ -277,7 +270,7 @@ extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return self
self
}
}
+9 -17
View File
@@ -1,15 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Conversion Context and Errors
/// A type that helps the user understanding value conversion errors
struct ValueConversionContext: KeyPathRefining {
struct ValueConversionContext: Refinable {
private enum Column {
case columnIndex(Int)
case columnName(String)
@@ -20,12 +12,12 @@ struct ValueConversionContext: KeyPathRefining {
var arguments: StatementArguments?
private var column: Column?
func atColumn(_ columnIndex: Int) -> ValueConversionContext {
return with(\.column, .columnIndex(columnIndex))
func atColumn(_ columnIndex: Int) -> Self {
with(\.column, .columnIndex(columnIndex))
}
func atColumn(_ columnName: String) -> ValueConversionContext {
return with(\.column, .columnName(columnName))
func atColumn(_ columnName: String) -> Self {
with(\.column, .columnName(columnName))
}
var columnIndex: Int? {
@@ -224,7 +216,7 @@ extension DatabaseValueConvertible {
@usableFromInline
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
return decode(
decode(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
@@ -258,7 +250,7 @@ extension DatabaseValueConvertible {
@usableFromInline
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
return decodeIfPresent(
decodeIfPresent(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
@@ -309,7 +301,7 @@ extension Row {
atUncheckedIndex index: Int)
-> Value
{
return impl.fastDecode(type, atUncheckedIndex: index)
impl.fastDecode(type, atUncheckedIndex: index)
}
@usableFromInline
@@ -318,6 +310,6 @@ extension Row {
atUncheckedIndex index: Int)
-> Value?
{
return impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
}
}
+33 -28
View File
@@ -1,13 +1,3 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - DatabaseValueConvertible
/// Types that adopt DatabaseValueConvertible can be initialized from
/// database values.
///
@@ -36,7 +26,7 @@ extension DatabaseValueConvertible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return databaseValue
databaseValue
}
}
@@ -194,7 +184,7 @@ extension DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
@@ -214,7 +204,7 @@ extension DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from a prepared statement.
@@ -273,7 +263,7 @@ extension DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
@@ -294,7 +284,7 @@ extension DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
@@ -318,7 +308,7 @@ extension DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -404,7 +394,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
@@ -416,7 +406,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
@@ -431,7 +421,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
try RowDecoder.fetchOne(db, self)
}
}
@@ -475,7 +465,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of optional values fetched from a prepared statement.
@@ -495,7 +485,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
@@ -529,7 +519,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
@@ -550,7 +540,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -599,7 +589,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
}
}
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible {
// MARK: Fetching Optional values
@@ -619,8 +609,8 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder.Wrapped> {
try Optional<RowDecoder.Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
@@ -631,7 +621,22 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
}
/// The first fetched value.
///
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some FetchRequest that fetches String?
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? {
try RowDecoder.Wrapped.fetchOne(db, self)
}
}
+77 -220
View File
@@ -66,7 +66,6 @@ public protocol DatabaseWriter: DatabaseReader {
/// - throws: The error thrown by the updates.
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
#if compiler(>=5.0)
/// Asynchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction.
///
@@ -92,7 +91,6 @@ public protocol DatabaseWriter: DatabaseReader {
func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
#endif
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction.
@@ -101,6 +99,12 @@ public protocol DatabaseWriter: DatabaseReader {
/// in a transaction.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, without retaining self.
///
/// :nodoc:
func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void)
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
@@ -148,7 +152,6 @@ public protocol DatabaseWriter: DatabaseReader {
/// }
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T>
#if compiler(>=5.0)
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -169,9 +172,9 @@ public protocol DatabaseWriter: DatabaseReader {
/// try Player.deleteAll()
///
/// // Count players concurrently
/// writer.asyncConcurrentRead { result in
/// writer.asyncConcurrentRead { dbResult in
/// do {
/// let db = try result.get()
/// let db = try dbResult.get()
/// // Guaranteed to be zero
/// let count = try Player.fetchCount(db)
/// } catch {
@@ -186,7 +189,6 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter block: A block that accesses the database.
/// :nodoc:
func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void)
#endif
}
extension DatabaseWriter {
@@ -209,7 +211,7 @@ extension DatabaseWriter {
/// - throws: The error thrown by the updates, or by the
/// wrapping transaction.
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
return try writeWithoutTransaction { db in
try writeWithoutTransaction { db in
var result: T?
try db.inTransaction {
result = try updates(db)
@@ -219,7 +221,6 @@ extension DatabaseWriter {
}
}
#if compiler(>=5.0)
/// Asynchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction.
///
@@ -260,7 +261,6 @@ extension DatabaseWriter {
}
}
}
#endif
// MARK: - Transaction Observers
@@ -280,10 +280,10 @@ extension DatabaseWriter {
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
/// Default implementation for the DatabaseReader requirement.
/// :nodoc:
public func remove(transactionObserver: TransactionObserver) {
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
_weakAsyncWriteWithoutTransaction {
$0?.remove(transactionObserver: transactionObserver)
}
}
// MARK: - Erasing the content of the database
@@ -306,218 +306,54 @@ extension DatabaseWriter {
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
// MARK: - Value Observation
// MARK: - Database Observation
/// Default implementation for the DatabaseReader requirement.
/// :nodoc:
public func add<Reducer: ValueReducer>(
/// A write-only observation only uses the serialized writer
func _addWriteOnly<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> TransactionObserver
-> ValueObserver<Reducer> // For testability
{
let requiresWriteAccess = observation.requiresWriteAccess
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
let observer = ValueObserver<Reducer>(
requiresWriteAccess: requiresWriteAccess,
observesSelectedRegion: observation.observesSelectedRegion,
requiresWriteAccess: observation.requiresWriteAccess,
writer: self,
reducer: observation.makeReducer(),
scheduling: scheduler,
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
onError: onError,
onChange: onChange)
switch observation.scheduling {
case .mainQueue:
if DispatchQueue.isMain {
// Use case: observation starts on the main queue and wants
// a synchronous initial fetch. Typically, this helps avoiding
// flashes of missing content.
var startValue: Reducer.Value? = nil
defer {
if let startValue = startValue {
onChange(startValue)
}
}
do {
try unsafeReentrantWrite { db in
observer.notificationQueue = DispatchQueue.main
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Initial value & selected region
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
startValue = value
}
db.add(transactionObserver: observer, extent: .observerLifetime)
}
} catch {
onError(error)
}
} else {
// Use case: observation does not start on the main queue, but
// has the default scheduling .mainQueue
asyncWriteWithoutTransaction { db in
do {
observer.notificationQueue = DispatchQueue.main
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Initial value & selected region
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
DispatchQueue.main.async {
onChange(value)
}
}
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
DispatchQueue.main.async {
onError(error)
}
}
if scheduler.immediateInitialValue() {
do {
let initialValue: Reducer.Value = try unsafeReentrantWrite { db in
let initialValue = try observer.fetchInitialValue(db)
db.add(transactionObserver: observer, extent: .observerLifetime)
return initialValue
}
onChange(initialValue)
} catch {
observer.cancel()
onError(error)
}
case let .async(onQueue: queue, startImmediately: startImmediately):
// Use case: observation must not block the target queue
asyncWriteWithoutTransaction { db in
} else {
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
observer.notificationQueue = queue
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Initial value & selected region
if startImmediately {
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
queue.async {
onChange(value)
}
}
} else if observation.observesSelectedRegion {
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
let initialValue = try observer.fetchInitialValue(db)
observer.notifyChange(initialValue)
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
queue.async {
onError(error)
}
}
}
case let .unsafe(startImmediately: startImmediately):
if startImmediately {
// Use case: third-party integration (RxSwift, Combine, ...) that
// need a synchronous initial fetch.
//
// This is really super extra unsafe.
//
// If the observation is started on one dispatch queue, then
// the onChange and onError callbacks must be asynchronously
// dispatched on the *same* queue.
//
// A failure to follow this rule may mess with the ordering of
// initial values.
var startValue: Reducer.Value? = nil
defer {
if let startValue = startValue {
onChange(startValue)
}
}
do {
try unsafeReentrantWrite { db in
observer.notificationQueue = nil
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Initial value & selected region
if startImmediately {
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
startValue = value
}
} else if observation.observesSelectedRegion {
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
db.add(transactionObserver: observer, extent: .observerLifetime)
}
} catch {
onError(error)
}
} else {
// Use case: ?
//
// This is unsafe because no promise is made on the dispatch
// queue on which the onChange and onError callbacks are called.
asyncWriteWithoutTransaction { db in
do {
observer.notificationQueue = nil
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Selected region
if observation.observesSelectedRegion {
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
onError(error)
}
observer.notifyErrorAndComplete(error)
}
}
}
// TODO
//
// We promise that observation stops when the returned observer is
// deallocated. But the real observer may have not started observing
// the database, because some observations start asynchronously.
// Well... This forces us to return a "token" that cancels any
// observation started asynchronously.
//
// We'll eventually return a proper Cancellable. In GRDB 5?
return ValueObserverToken(writer: self, observer: observer)
return observer
}
}
@@ -542,7 +378,7 @@ public class DatabaseFuture<Value> {
_wait = wait
}
init(_ result: DatabaseResult<Value>) {
init(_ result: Result<Value, Error>) {
_wait = result.get
}
@@ -574,7 +410,7 @@ public final class AnyDatabaseWriter: DatabaseWriter {
/// :nodoc:
public var configuration: Configuration {
return base.configuration
base.configuration
}
// MARK: - Interrupting Database Operations
@@ -588,56 +424,56 @@ public final class AnyDatabaseWriter: DatabaseWriter {
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
try base.read(block)
}
#if compiler(>=5.0)
/// :nodoc:
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(block)
}
#endif
/// :nodoc:
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
base._weakAsyncRead(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
try base.unsafeReentrantRead(block)
}
/// :nodoc:
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
return base.concurrentRead(block)
base.concurrentRead(block)
}
#if compiler(>=5.0)
/// :nodoc:
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(block)
}
#endif
// MARK: - Writing in Database
/// :nodoc:
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
return try base.write(updates)
try base.write(updates)
}
/// :nodoc:
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try base.writeWithoutTransaction(updates)
try base.writeWithoutTransaction(updates)
}
/// :nodoc:
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try base.barrierWriteWithoutTransaction(updates)
try base.barrierWriteWithoutTransaction(updates)
}
#if compiler(>=5.0)
/// :nodoc:
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
@@ -645,16 +481,20 @@ public final class AnyDatabaseWriter: DatabaseWriter {
{
base.asyncWrite(updates, completion: completion)
}
#endif
/// :nodoc:
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
/// :nodoc:
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
base._weakAsyncWriteWithoutTransaction(updates)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(updates)
try base.unsafeReentrantWrite(updates)
}
// MARK: - Functions
@@ -680,4 +520,21 @@ public final class AnyDatabaseWriter: DatabaseWriter {
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onError: @escaping (Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
-> DatabaseCancellable
{
base._add(
observation: observation,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
+7 -57
View File
@@ -49,20 +49,6 @@ public protocol FetchRequest: DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
/// This method is deprecated. Use
/// `makePreparedRequest(_:forSingleResult:)` instead.
///
/// Returns a tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use this to optimize the
/// prepared statement.
/// - returns: A prepared statement and an eventual row adapter.
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
/// Returns a PreparedRequest that is ready to be executed.
///
/// - parameter db: A database connection.
@@ -89,7 +75,7 @@ extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
return AdaptedFetchRequest(self, adapter)
AdaptedFetchRequest(self, adapter)
}
/// Returns the number of rows fetched by the request.
@@ -112,22 +98,7 @@ extension FetchRequest {
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
let request = try makePreparedRequest(db, forSingleResult: false)
return request.statement.databaseRegion
}
// Support for legacy requests which only define prepare(_:forSingleResult:)
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let (statement, adapter) = try prepare(db, forSingleResult: singleResult)
return PreparedRequest(statement: statement, adapter: adapter)
}
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
/// :nodoc:
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
let request = try makePreparedRequest(db, forSingleResult: singleResult)
return (request.statement, request.adapter)
return request.statement.selectedRegion
}
}
@@ -160,12 +131,12 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
try base.fetchCount(db)
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return try base.databaseRegion(db)
try base.databaseRegion(db)
}
}
@@ -189,39 +160,18 @@ public struct AnyFetchRequest<T>: FetchRequest {
_databaseRegion = request.databaseRegion
}
/// Creates a request whose `prepare()` method wraps and forwards
/// operations the argument closure.
@available(*, deprecated, message: "Define your own FetchRequest type instead.")
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) {
_preparedRequest = { db, singleResult in
let (statement, adapter) = try prepare(db, singleResult)
return PreparedRequest(statement: statement, adapter: adapter)
}
_fetchCount = { db in
let (statement, _) = try prepare(db, false)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
}
_databaseRegion = { db in
let (statement, _) = try prepare(db, false)
return statement.databaseRegion
}
}
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
return try _preparedRequest(db, singleResult)
try _preparedRequest(db, singleResult)
}
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try _fetchCount(db)
try _fetchCount(db)
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
return try _databaseRegion(db)
try _databaseRegion(db)
}
}
+61 -92
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A database row.
public final class Row: Equatable, Hashable, RandomAccessCollection,
@@ -78,15 +71,13 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
/// the iteration of a query: make sure to make a copy of it whenever you
/// want to keep a specific one: `row.copy()`.
public func copy() -> Row {
return impl.copiedRow(self)
impl.copiedRow(self)
}
// MARK: - Not Public
/// Returns true if and only if the row was fetched from a database.
var isFetched: Bool {
return impl.isFetched
}
var isFetched: Bool { impl.isFetched }
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
@@ -142,19 +133,19 @@ extension Row {
/// Columns appear in the same order as they occur as the `.0` member
/// of column-value pairs in `self`.
public var columnNames: LazyMapCollection<Row, String> {
return lazy.map { $0.0 }
lazy.map { $0.0 }
}
/// Returns true if and only if the row has that column.
///
/// This method is case-insensitive.
public func hasColumn(_ columnName: String) -> Bool {
return index(ofColumn: columnName) != nil
index(ofColumn: columnName) != nil
}
@usableFromInline
func index(ofColumn name: String) -> Int? {
return impl.index(ofColumn: name)
impl.index(ofColumn: name)
}
}
@@ -382,7 +373,7 @@ extension Row {
/// The result is nil if the row does not contain the column.
@inlinable
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
return self[column.name]
self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -395,7 +386,7 @@ extension Row {
/// `Value`. Should this conversion fail, a fatal error is raised.
@inlinable
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
return self[column.name]
self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -417,7 +408,7 @@ extension Row {
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
return self[column.name]
self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -431,7 +422,7 @@ extension Row {
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
return self[column.name]
self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -454,7 +445,7 @@ extension Row {
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
return self[column.name]
self[column.name]
}
/// Returns the optional Data at given index.
@@ -502,7 +493,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy<Column: ColumnExpression>(_ column: Column) -> Data? {
return dataNoCopy(named: column.name)
dataNoCopy(named: column.name)
}
}
@@ -515,7 +506,7 @@ extension Row {
/// Values appear in the same order as they occur as the `.1` member
/// of column-value pairs in `self`.
public var databaseValues: LazyMapCollection<Row, DatabaseValue> {
return lazy.map { $0.1 }
lazy.map { $0.1 }
}
}
@@ -701,7 +692,7 @@ extension Row {
/// row.scopes["bar"] // [bar:2]
/// row.scopes["baz"] // nil
public var scopes: ScopesView {
return impl.scopes(prefetchedRows: prefetchedRows)
impl.scopes(prefetchedRows: prefetchedRows)
}
/// Returns a view on the scopes tree defined by row adapters.
@@ -724,7 +715,7 @@ extension Row {
/// row.scopesTree["bar"] // [bar:2]
/// row.scopesTree["baz"] // [baz:3]
public var scopesTree: ScopesTreeView {
return ScopesTreeView(scopes: scopes)
ScopesTreeView(scopes: scopes)
}
/// Returns a copy of the row, without any scopes.
@@ -755,7 +746,7 @@ extension Row {
/// This property can turn out useful when you debug the consumption of
/// adapted rows, such as rows fetched from joined requests.
public var unadapted: Row {
return impl.unadaptedRow(self)
impl.unadaptedRow(self)
}
}
@@ -847,7 +838,7 @@ extension Row {
adapter: RowAdapter? = nil)
throws -> RowCursor
{
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of rows fetched from a prepared statement.
@@ -935,7 +926,7 @@ extension Row {
adapter: RowAdapter? = nil)
throws -> RowCursor
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of rows fetched from an SQL query.
@@ -960,7 +951,7 @@ extension Row {
adapter: RowAdapter? = nil)
throws -> [Row]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single row fetched from an SQL query.
@@ -985,7 +976,7 @@ extension Row {
adapter: RowAdapter? = nil)
throws -> Row?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -1093,7 +1084,7 @@ extension FetchRequest where RowDecoder == Row {
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RowCursor {
return try Row.fetchCursor(db, self)
try Row.fetchCursor(db, self)
}
/// An array of fetched rows.
@@ -1105,7 +1096,7 @@ extension FetchRequest where RowDecoder == Row {
/// - returns: An array of fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
return try Row.fetchAll(db, self)
try Row.fetchAll(db, self)
}
/// The first fetched row.
@@ -1117,7 +1108,7 @@ extension FetchRequest where RowDecoder == Row {
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
return try Row.fetchOne(db, self)
try Row.fetchOne(db, self)
}
}
@@ -1142,16 +1133,12 @@ extension Row {
/// The index of the first (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var startIndex: RowIndex {
return Index(0)
}
public var startIndex: RowIndex { RowIndex(0) }
/// The "past-the-end" index, successor of the index of the last
/// (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var endIndex: RowIndex {
return Index(count)
}
public var endIndex: RowIndex { RowIndex(count) }
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
public subscript(position: RowIndex) -> (String, DatabaseValue) {
@@ -1225,14 +1212,14 @@ extension Row {
extension Row {
/// :nodoc:
public var description: String {
return "["
"["
+ map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ")
+ "]"
}
/// :nodoc:
public var debugDescription: String {
return debugDescription(level: 0)
debugDescription(level: 0)
}
private func debugDescription(level: Int) -> String {
@@ -1284,12 +1271,12 @@ public struct RowIndex: Comparable, Strideable {
extension RowIndex {
/// :nodoc:
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
lhs.index == rhs.index
}
/// :nodoc:
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
lhs.index < rhs.index
}
}
@@ -1297,12 +1284,12 @@ extension RowIndex {
extension RowIndex {
/// :nodoc:
public func distance(to other: RowIndex) -> Int {
return other.index - index
other.index - index
}
/// :nodoc:
public func advanced(by n: Int) -> RowIndex {
return RowIndex(index + n)
RowIndex(index + n)
}
}
@@ -1339,7 +1326,7 @@ extension Row {
/// The scopes defined on this row.
public var names: Dictionary<String, LayoutedRowAdapter>.Keys {
return scopes.keys
scopes.keys
}
init() {
@@ -1354,17 +1341,17 @@ extension Row {
/// :nodoc:
public var startIndex: Index {
return scopes.startIndex
scopes.startIndex
}
/// :nodoc:
public var endIndex: Index {
return scopes.endIndex
scopes.endIndex
}
/// :nodoc:
public func index(after i: Index) -> Index {
return scopes.index(after: i)
scopes.index(after: i)
}
/// :nodoc:
@@ -1387,7 +1374,7 @@ extension Row {
/// Returns the row associated with the given scope, or nil if the
/// scope is not defined.
public subscript(_ name: String) -> Row? {
return scopes.index(forKey: name).map { self[$0].row }
scopes.index(forKey: name).map { self[$0].row }
}
}
}
@@ -1500,7 +1487,7 @@ extension Row {
/// True if there is no prefetched associated rows.
public var isEmpty: Bool {
return prefetches.isEmpty
prefetches.isEmpty
}
/// The keys for available prefetched rows
@@ -1666,20 +1653,16 @@ private struct ArrayRowImpl: RowImpl {
self.columns = columns
}
var count: Int {
return columns.count
}
var count: Int { columns.count }
var isFetched: Bool {
return false
}
var isFetched: Bool { false }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return columns[index].1
columns[index].1
}
func columnName(atUncheckedIndex index: Int) -> String {
return columns[index].0
columns[index].0
}
func index(ofColumn name: String) -> Int? {
@@ -1688,7 +1671,7 @@ private struct ArrayRowImpl: RowImpl {
}
func copiedRow(_ row: Row) -> Row {
return row
row
}
}
@@ -1708,20 +1691,16 @@ private struct StatementCopyRowImpl: RowImpl {
self.columnNames = columnNames
}
var count: Int {
return columnNames.count
}
var count: Int { columnNames.count }
var isFetched: Bool {
return true
}
var isFetched: Bool { true }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return dbValues[index]
dbValues[index]
}
func columnName(atUncheckedIndex index: Int) -> String {
return columnNames[index]
columnNames[index]
}
func index(ofColumn name: String) -> Int? {
@@ -1730,7 +1709,7 @@ private struct StatementCopyRowImpl: RowImpl {
}
func copiedRow(_ row: Row) -> Row {
return row
row
}
}
@@ -1755,12 +1734,10 @@ private struct StatementRowImpl: RowImpl {
}
var count: Int {
return Int(sqlite3_column_count(sqliteStatement))
Int(sqlite3_column_count(sqliteStatement))
}
var isFetched: Bool {
return true
}
var isFetched: Bool { true }
func hasNull(atUncheckedIndex index: Int) -> Bool {
// Avoid extracting values, because this modifies the SQLite statement.
@@ -1779,25 +1756,25 @@ private struct StatementRowImpl: RowImpl {
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value
{
return Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value?
{
return Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
func columnName(atUncheckedIndex index: Int) -> String {
return statement.columnNames[index]
statement.columnNames[index]
}
func index(ofColumn name: String) -> Int? {
@@ -1808,22 +1785,22 @@ private struct StatementRowImpl: RowImpl {
}
func copiedRow(_ row: Row) -> Row {
return Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
}
}
// This one is not optimized at all, since it is only used in fatal conversion errors, so far
private struct SQLiteStatementRowImpl: RowImpl {
let sqliteStatement: SQLiteStatement
var count: Int { return Int(sqlite3_column_count(sqliteStatement)) }
var isFetched: Bool { return true }
var count: Int { Int(sqlite3_column_count(sqliteStatement)) }
var isFetched: Bool { true }
func columnName(atUncheckedIndex index: Int) -> String {
return String(cString: sqlite3_column_name(sqliteStatement, Int32(index)))
String(cString: sqlite3_column_name(sqliteStatement, Int32(index)))
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
@@ -1848,13 +1825,9 @@ private struct SQLiteStatementRowImpl: RowImpl {
/// See Row.init()
private struct EmptyRowImpl: RowImpl {
var count: Int {
return 0
}
var count: Int { 0 }
var isFetched: Bool {
return false
}
var isFetched: Bool { false }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
// Programmer error
@@ -1866,11 +1839,7 @@ private struct EmptyRowImpl: RowImpl {
fatalError("row index out of range")
}
func index(ofColumn name: String) -> Int? {
return nil
}
func index(ofColumn name: String) -> Int? { nil }
func copiedRow(_ row: Row) -> Row {
return row
}
func copiedRow(_ row: Row) -> Row { row }
}
+18 -26
View File
@@ -89,11 +89,11 @@ public struct LayoutedColumnMapping {
}
func baseColumnIndex(atMappingIndex index: Int) -> Int {
return layoutColumns[index].0
layoutColumns[index].0
}
func columnName(atMappingIndex index: Int) -> String {
return layoutColumns[index].1
layoutColumns[index].1
}
}
@@ -104,16 +104,12 @@ extension LayoutedColumnMapping: LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns self.
public var mapping: LayoutedColumnMapping {
return self
}
public var mapping: LayoutedColumnMapping { self }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the empty dictionary.
public var scopes: [String: LayoutedRowAdapter] {
return [:]
}
public var scopes: [String: LayoutedRowAdapter] { [:] }
}
/// :nodoc:
@@ -175,13 +171,13 @@ extension SelectStatement: RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var layoutColumns: [(Int, String)] {
return Array(columnNames.enumerated())
Array(columnNames.enumerated())
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutIndex(ofColumn name: String) -> Int? {
return index(ofColumn: name)
index(ofColumn: name)
}
}
@@ -247,7 +243,7 @@ extension RowAdapter {
extension RowAdapter {
func baseColumnIndex(atIndex index: Int, layout: RowLayout) throws -> Int {
return try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index)
try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index)
}
}
@@ -259,7 +255,7 @@ public struct EmptyRowAdapter: RowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: [])
LayoutedColumnMapping(layoutColumns: [])
}
}
@@ -325,7 +321,7 @@ public struct SuffixRowAdapter: RowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
}
}
@@ -355,7 +351,7 @@ public struct RangeRowAdapter: RowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
}
}
@@ -454,7 +450,7 @@ struct ChainedAdapter: RowAdapter {
let second: RowAdapter
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
}
}
@@ -484,16 +480,12 @@ struct AdaptedRowImpl: RowImpl {
self.mapping = adapter.mapping
}
var count: Int {
return mapping.layoutColumns.count
}
var count: Int { mapping.layoutColumns.count }
var isFetched: Bool {
return base.isFetched
}
var isFetched: Bool { base.isFetched }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
return Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows)
Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows)
}
func hasNull(atUncheckedIndex index: Int) -> Bool {
@@ -528,15 +520,15 @@ struct AdaptedRowImpl: RowImpl {
}
func columnName(atUncheckedIndex index: Int) -> String {
return mapping.columnName(atMappingIndex: index)
mapping.columnName(atMappingIndex: index)
}
func index(ofColumn name: String) -> Int? {
return mapping.layoutIndex(ofColumn: name)
mapping.layoutIndex(ofColumn: name)
}
func copiedRow(_ row: Row) -> Row {
return Row(base: base.copy(), adapter: adapter)
Row(base: base.copy(), adapter: adapter)
}
func unscopedRow(_ row: Row) -> Row {
@@ -545,6 +537,6 @@ struct AdaptedRowImpl: RowImpl {
}
func unadaptedRow(_ row: Row) -> Row {
return base.unadapted
base.unadapted
}
}
-2
View File
@@ -1,4 +1,3 @@
#if swift(>=5.0)
/// :nodoc:
public struct SQLInterpolation: StringInterpolationProtocol {
var elements: [SQLLiteral.Element]
@@ -23,4 +22,3 @@ public struct SQLInterpolation: StringInterpolationProtocol {
elements.append(contentsOf: sqlLiteral.elements)
}
}
#endif
+31 -80
View File
@@ -13,18 +13,11 @@ public struct SQLLiteral {
/// SQLLiteral is an array of elements which can be qualified with
/// table aliases.
enum Element {
case sql(String, StatementArguments)
case sql(String, StatementArguments = StatementArguments())
case expression(SQLExpression)
case selectable(SQLSelectable)
case orderingTerm(SQLOrderingTerm)
case subQuery(SQLLiteral)
// TODO: remove when the deprecated SQLLiteral.mapSQL(_:) is removed.
case map(SQLLiteral, (String) -> String)
// TODO: remove and use default case argument when compiler >= 5.1
static func sql(_ sql: String) -> Element {
return .sql(sql, StatementArguments())
}
fileprivate func sql(_ context: inout SQLGenerationContext) -> String {
switch self {
@@ -43,8 +36,6 @@ public struct SQLLiteral {
return orderingTerm.orderingTermSQL(&context)
case let .subQuery(sqlLiteral):
return "(" + sqlLiteral.sql(&context) + ")"
case let .map(sqlLiteral, transform):
return transform(sqlLiteral.sql(&context))
}
}
@@ -61,8 +52,6 @@ public struct SQLLiteral {
case .subQuery:
// subqueries are not requalified
return self
case let .map(sqlLiteral, transform):
return .map(sqlLiteral.qualified(with: alias), transform)
}
}
}
@@ -108,18 +97,12 @@ public struct SQLLiteral {
self.init(elements: [.expression(expression)])
}
// TODO: deprecate when SQL interpolation is always available
/// Returns a literal whose SQL is transformed by the given closure.
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral {
return SQLLiteral(elements: [.map(self, transform)])
}
func sql(_ context: inout SQLGenerationContext) -> String {
return elements.map { $0.sql(&context) }.joined()
elements.map { $0.sql(&context) }.joined()
}
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
return SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
}
}
@@ -165,21 +148,21 @@ extension SQLLiteral {
}
extension SQLLiteral {
/// Creates an SQL literal expression.
/// Creates a literal SQL expression.
///
/// SQLLiteral(sql: "1 + 2").sqlExpression
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
public var sqlExpression: SQLExpression {
return SQLExpressionLiteral(sqlLiteral: self)
_SQLExpressionLiteral(sqlLiteral: self)
}
var sqlSelectable: SQLSelectable {
return SQLSelectionLiteral(sqlLiteral: self)
_SQLSelectionLiteral(sqlLiteral: self)
}
var sqlOrderingTerm: SQLOrderingTerm {
return SQLOrderingLiteral(sqlLiteral: self)
_SQLOrderingLiteral(sqlLiteral: self)
}
}
@@ -195,9 +178,9 @@ extension Sequence where Element == SQLLiteral {
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQLLiteral {
if separator.isEmpty {
return SQLLiteral(elements: flatMap { $0.elements })
return SQLLiteral(elements: flatMap(\.elements))
} else {
return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(.sql(separator)))))
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
@@ -214,16 +197,15 @@ extension Collection where Element == SQLLiteral {
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQLLiteral {
if separator.isEmpty {
return SQLLiteral(elements: flatMap { $0.elements })
return SQLLiteral(elements: flatMap(\.elements))
} else {
return SQLLiteral(elements: Array(map { $0.elements }.joined(separator: CollectionOfOne(.sql(separator)))))
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
// MARK: - ExpressibleByStringInterpolation
#if swift(>=5.0)
extension SQLLiteral: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
@@ -245,9 +227,8 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
self.init(elements: sqlInterpolation.elements)
}
}
#endif
// MARK: - SQLExpressionLiteral
// MARK: - _SQLExpressionLiteral
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -259,50 +240,17 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
///
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
public struct SQLExpressionLiteral: SQLExpression {
private struct _SQLExpressionLiteral: SQLExpression {
private let sqlLiteral: SQLLiteral
public var sql: String { return sqlLiteral.sql }
public var arguments: StatementArguments { return sqlLiteral.arguments }
// Prefer SQLLiteral.sqlExpression
fileprivate init(sqlLiteral: SQLLiteral) {
init(sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral(sql: "1 + 2")
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
@available(*, deprecated, message: "Use SQLiteral.sqlExpression instead")
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
self.init(sqlLiteral: SQLLiteral(sql: sql, arguments: arguments))
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral(literal: SQLLiteral(sql: "1 + 2")
/// SQLExpressionLiteral(literal: SQLLiteral(sql: "? + ?", arguments: [1, 2]))
/// SQLExpressionLiteral(literal: SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// SQLExpressionLiteral(literal: "\(1) + \(2)")
@available(*, deprecated, message: "Use SQLiteral.sqlExpression instead")
public init(literal sqlLiteral: SQLLiteral) {
self.init(sqlLiteral: sqlLiteral)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
@@ -311,14 +259,14 @@ public struct SQLExpressionLiteral: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return sqlLiteral.qualified(with: alias).sqlExpression
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
sqlLiteral.qualified(with: alias).sqlExpression
}
}
// MARK: - SQLSelectionLiteral
// MARK: - _SQLSelectionLiteral
private struct SQLSelectionLiteral: SQLSelectable {
private struct _SQLSelectionLiteral: SQLSelectable {
private let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlSelectable
@@ -327,38 +275,41 @@ private struct SQLSelectionLiteral: SQLSelectable {
}
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
return sqlLiteral.sql(&context)
sqlLiteral.sql(&context)
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func count(distinct: Bool) -> SQLCount? {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func columnCount(_ db: Database) throws -> Int {
fatalError("""
Selection literals don't known how many columns they contain. \
To resolve this error, select one or several SQLExpressionLiteral instead.
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
return sqlLiteral.qualified(with: alias).sqlSelectable
sqlLiteral.qualified(with: alias).sqlSelectable
}
}
// MARK: - SQLOrderingLiteral
// MARK: - _SQLOrderingLiteral
private struct SQLOrderingLiteral: SQLOrderingTerm {
private struct _SQLOrderingLiteral: SQLOrderingTerm {
private let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlOrderingTerm
@@ -374,10 +325,10 @@ private struct SQLOrderingLiteral: SQLOrderingTerm {
}
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
return sqlLiteral.sql(&context)
sqlLiteral.sql(&context)
}
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
return sqlLiteral.qualified(with: alias).sqlOrderingTerm
sqlLiteral.qualified(with: alias).sqlOrderingTerm
}
}
+2 -4
View File
@@ -19,14 +19,14 @@ public struct SQLRequest<T>: FetchRequest {
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.sql // "SELECT * FROM player WHERE id = ?"
public var sql: String { return sqlLiteral.sql }
public var sql: String { sqlLiteral.sql }
/// The request argument
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.arguments // [42]
public var arguments: StatementArguments { return sqlLiteral.arguments }
public var arguments: StatementArguments { sqlLiteral.arguments }
/// The request adapter
public var adapter: RowAdapter?
@@ -162,7 +162,6 @@ public struct SQLRequest<T>: FetchRequest {
}
}
#if swift(>=5.0)
extension SQLRequest: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
@@ -184,4 +183,3 @@ extension SQLRequest: ExpressibleByStringInterpolation {
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
}
}
#endif
+2 -2
View File
@@ -53,10 +53,10 @@ final class SchedulingWatchdog {
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: watchDogKey)
DispatchQueue.getSpecific(key: watchDogKey)
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
allowedDatabases.contains { $0 === db }
}
}
+15 -4
View File
@@ -6,9 +6,7 @@ final class SerializedDatabase {
private let db: Database
/// The database configuration
var configuration: Configuration {
return db.configuration
}
var configuration: Configuration { db.configuration }
/// The path to the database file
var path: String
@@ -186,9 +184,22 @@ final class SerializedDatabase {
}
}
/// Asynchronously executes a block in the serialized dispatch queue,
/// without retaining self.
func weakAsync(_ block: @escaping (Database?) -> Void) {
queue.async { [weak self] in
if let self = self {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
} else {
block(nil)
}
}
}
/// Returns true if any only if the current dispatch queue is valid.
var onValidQueue: Bool {
return SchedulingWatchdog.current?.allows(db) ?? false
SchedulingWatchdog.current?.allows(db) ?? false
}
/// Executes the block in the current queue.
+18 -79
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = OpaquePointer
@@ -31,8 +24,14 @@ public class Statement {
.trimmingCharacters(in: .sqlStatementSeparators)
}
// Selected region is computed during statement compilation, and maybe
// optimized for select statements compiled by QueryInterfaceRequest, in
// order to perform focused database observation. See
// SQLQueryGenerator.optimizedSelectedRegion(_:_:)
var selectedRegion = DatabaseRegion()
var isReadonly: Bool {
return sqlite3_stmt_readonly(sqliteStatement) != 0
sqlite3_stmt_readonly(sqliteStatement) != 0
}
unowned let database: Database
@@ -88,6 +87,7 @@ public class Statement {
self.database = database
self.sqliteStatement = statement
self.selectedRegion = authorizer.selectedRegion
}
deinit {
@@ -124,7 +124,7 @@ public class Statement {
/// The statement arguments.
public var arguments: StatementArguments {
get { return _arguments }
get { _arguments }
set {
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
@@ -153,27 +153,6 @@ public class Statement {
_ = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false)
}
/// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all
/// statement arguments.
///
/// For example:
///
/// let statement = try db.makeUpdateArgument(sql: """
/// INSERT INTO player (id, name) VALUES (?, ?)
/// """)
///
/// // OK
/// statement.validate([1, "Arthur"])
///
/// // Throws
/// statement.validate([1])
///
/// See also setArguments(_:)
@available(*, deprecated, renamed: "validateArguments(_:)")
public func validate(arguments: StatementArguments) throws {
try validateArguments(arguments)
}
/// Set arguments without any validation. Trades safety for performance.
///
/// Only call this method if you are sure input arguments match all expected
@@ -214,34 +193,6 @@ public class Statement {
}
}
/// Set arguments without any validation. Trades safety for performance.
///
/// Only call this method if you are sure input arguments match all expected
/// arguments of the statement.
///
/// For example:
///
/// let statement = try db.makeUpdateArgument(sql: """
/// INSERT INTO player (id, name) VALUES (?, ?)
/// """)
///
/// // OK
/// statement.unsafeSetArguments([1, "Arthur"])
///
/// // OK
/// let arguments: StatementArguments = ... // some untrusted arguments
/// try statement.validateArguments(arguments)
/// statement.unsafeSetArguments(arguments)
///
/// // NOT OK
/// statement.unsafeSetArguments([1])
///
/// See also setArguments(_:)
@available(*, deprecated, renamed: "setUncheckedArguments(_:)")
public func unsafeSetArguments(_ arguments: StatementArguments) {
setUncheckedArguments(arguments)
}
/// Set the statement arguments, or throws a DatabaseError of code
/// SQLITE_ERROR if arguments don't fill all statement arguments.
///
@@ -284,15 +235,9 @@ public class Statement {
case .string(let string):
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
#if swift(>=5.0)
code = data.withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
}
#else
code = data.withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0, Int32(data.count), SQLITE_TRANSIENT)
}
#endif
}
// It looks like sqlite3_bind_xxx() functions do not access the file system.
@@ -377,13 +322,6 @@ extension Statement {
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement: Statement {
// Database region is computed during statement compilation, and maybe
// optimized when statement is compiled for a QueryInterfaceRequest, in
// order to perform focused database observation. See
// SQLQueryGenerator.optimizedDatabaseRegion(_:_:)
/// The database region that the statement looks into.
public internal(set) var databaseRegion = DatabaseRegion()
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
///
@@ -416,13 +354,14 @@ public final class SelectStatement: Statement {
GRDBPrecondition(
authorizer.transactionEffect == nil,
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
self.databaseRegion = authorizer.databaseRegion
}
/// The database region that the statement looks into.
public var databaseRegion: DatabaseRegion { selectedRegion }
/// The number of columns in the resulting rows.
public var columnCount: Int {
return Int(sqlite3_column_count(self.sqliteStatement))
Int(sqlite3_column_count(self.sqliteStatement))
}
/// The column names, ordered from left to right.
@@ -441,14 +380,14 @@ public final class SelectStatement: Statement {
/// Returns the index of the leftmost column named `name`, in a
/// case-insensitive way.
public func index(ofColumn name: String) -> Int? {
return columnIndexes[name.lowercased()]
columnIndexes[name.lowercased()]
}
/// Creates a cursor over the statement which does not produce any
/// value. Each call to the next() cursor method calls the sqlite3_step()
/// C function.
func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor {
return try StatementCursor(statement: self, arguments: arguments)
try StatementCursor(statement: self, arguments: arguments)
}
/// Utility function for cursors
@@ -703,7 +642,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
private(set) var namedValues: [String: DatabaseValue] = [:]
public var isEmpty: Bool {
return values.isEmpty && namedValues.isEmpty
values.isEmpty && namedValues.isEmpty
}
@@ -734,7 +673,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
values = sequence.map { $0.databaseValue }
values = sequence.map(\.databaseValue)
}
/// Creates statement arguments from any array. The result is nil unless all
@@ -1031,7 +970,7 @@ extension StatementArguments {
extension StatementArguments {
/// :nodoc:
public var description: String {
let valuesDescriptions = values.map { $0.description }
let valuesDescriptions = values.map(\.description)
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
"\(String(reflecting: key)): \(value)"
}
+4 -14
View File
@@ -1,13 +1,6 @@
#if os(Linux)
import Glibc
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A protocol around sqlite3_set_authorizer
protocol StatementAuthorizer: AnyObject {
@@ -23,7 +16,7 @@ protocol StatementAuthorizer: AnyObject {
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer: StatementAuthorizer {
/// What this statements reads
var databaseRegion = DatabaseRegion()
var selectedRegion = DatabaseRegion()
/// What this statements writes
var databaseEventKinds: [DatabaseEventKind] = []
@@ -76,10 +69,10 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
databaseRegion.formUnion(DatabaseRegion(table: tableName))
selectedRegion.formUnion(DatabaseRegion(table: tableName))
} else {
// SELECT column FROM table
databaseRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
}
return SQLITE_OK
@@ -145,7 +138,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let cString2 = cString2 else { return SQLITE_OK }
if sqlite3_stricmp(cString2, "COUNT") == 0 {
databaseRegion = .fullDatabase
selectedRegion = .fullDatabase
}
return SQLITE_OK
@@ -193,9 +186,6 @@ final class TruncateOptimizationBlocker: StatementAuthorizer {
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
let rawValue: Int32
init(rawValue: Int32) {
self.rawValue = rawValue
}
var description: String {
switch rawValue {
+32 -25
View File
@@ -1,11 +1,3 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// The StatementColumnConvertible protocol grants access to the low-level C
/// interface that extracts values from query results:
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
@@ -202,7 +194,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{
return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
@@ -222,7 +214,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from a prepared statement.
@@ -281,7 +273,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
@@ -302,7 +294,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
@@ -323,7 +315,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -408,7 +400,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
@@ -420,7 +412,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
@@ -435,7 +427,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
try RowDecoder.fetchOne(db, self)
}
}
@@ -479,7 +471,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of optional values fetched from a prepared statement.
@@ -499,7 +491,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
@@ -533,7 +525,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
@@ -554,7 +546,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -606,7 +598,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
extension FetchRequest
where
RowDecoder: _OptionalProtocol,
RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible
RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible
{
// MARK: Fetching Optional values
@@ -627,8 +619,8 @@ extension FetchRequest
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder.Wrapped> {
try Optional<RowDecoder.Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
@@ -639,7 +631,22 @@ extension FetchRequest
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
}
/// The first fetched value.
///
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some FetchRequest that fetches String?
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? {
try RowDecoder.Wrapped.fetchOne(db, self)
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ extension CGFloat: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Double(self).databaseValue
Double(self).databaseValue
}
/// Returns a CGFloat initialized from *dbValue*, if possible.
+1 -8
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Data is convertible to and from DatabaseValue.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
@@ -21,7 +14,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .blob(self))
DatabaseValue(storage: .blob(self))
}
/// Returns a Data initialized from *dbValue*, if it contains
@@ -1,14 +1,7 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// DatabaseDateComponents reads and stores DateComponents in the database.
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible {
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible, Codable {
/// The available formats for reading and storing date components.
public enum Format: String {
@@ -159,4 +152,30 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
return SQLiteDateParser().components(from: string)
}
// MARK: - Codable adoption
/// Creates a new instance by decoding from the given decoder.
///
/// - parameters:
/// - decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let stringValue = try container.decode(String.self)
guard let decodedValue = DatabaseDateComponents.fromDatabaseValue(stringValue.databaseValue) else {
throw DecodingError.dataCorruptedError(in: container,
debugDescription: "Unable to initialise databaseDateComponent")
}
self = decodedValue
}
/// Encodes this value into the given encoder.
///
/// - parameters:
/// - encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(String.fromDatabaseValue(databaseValue)!)
}
}
@@ -17,12 +17,12 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return (self as! ReferenceType).databaseValue
(self as! ReferenceType).databaseValue
}
/// Returns a value initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
}
}
+2 -9
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if !os(Linux)
/// NSDate is stored in the database using the format
@@ -14,7 +7,7 @@ extension NSDate: DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
return (self as Date).databaseValue
(self as Date).databaseValue
}
/// Returns a date initialized from dbValue, if possible.
@@ -42,7 +35,7 @@ extension Date: DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
return storageDateFormatter.string(from: self).databaseValue
storageDateFormatter.string(from: self).databaseValue
}
/// Returns a date initialized from dbValue, if possible.
+1 -1
View File
@@ -6,7 +6,7 @@ extension NSData: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return (self as Data).databaseValue
(self as Data).databaseValue
}
/// Returns an NSData initialized from *dbValue*, if it contains
+2 -6
View File
@@ -4,12 +4,8 @@ import Foundation
extension NSNull: DatabaseValueConvertible {
/// Returns DatabaseValue.null.
public var databaseValue: DatabaseValue {
return .null
}
public var databaseValue: DatabaseValue { .null }
/// Returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
return nil
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { nil }
}
+1 -1
View File
@@ -6,7 +6,7 @@ extension NSString: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return (self as String).databaseValue
(self as String).databaseValue
}
/// Returns an NSString initialized from *dbValue*, if possible.
@@ -15,7 +15,7 @@ class SQLiteDateParser {
}
func components(from dateString: String) -> DatabaseDateComponents? {
return dateString.withCString { cString in
dateString.withCString { cString in
components(cString: cString, length: strlen(cString))
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ extension NSURL: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
/// (the URL's absoluteString).
public var databaseValue: DatabaseValue {
return absoluteString?.databaseValue ?? .null
absoluteString?.databaseValue ?? .null
}
/// Returns an NSURL initialized from *dbValue*, if possible.
+1 -20
View File
@@ -1,11 +1,4 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if !os(Linux)
/// NSUUID adopts DatabaseValueConvertible
@@ -21,15 +14,9 @@ extension NSUUID: DatabaseValueConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
#if swift(>=5.0)
return data.withUnsafeBytes {
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
}
#else
return data.withUnsafeBytes {
self.init(uuidBytes: $0)
}
#endif
case .string(let string):
return self.init(uuidString: string)
default:
@@ -42,7 +29,7 @@ extension NSUUID: DatabaseValueConvertible {
/// UUID adopts DatabaseValueConvertible
extension UUID: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
return withUnsafeBytes(of: uuid) {
withUnsafeBytes(of: uuid) {
Data(bytes: $0.baseAddress!, count: $0.count).databaseValue
}
}
@@ -50,15 +37,9 @@ extension UUID: DatabaseValueConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
#if swift(>=5.0)
return data.withUnsafeBytes {
UUID(uuid: $0.bindMemory(to: uuid_t.self).first!)
}
#else
return data.withUnsafeBytes {
UUID(uuid: $0.pointee)
}
#endif
case .string(let string):
return UUID(uuidString: string)
default:
@@ -5,9 +5,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool {
return dbValue.isNull
}
func decodeNil() -> Bool { dbValue.isNull }
/// Decodes a single value of the given type.
///
@@ -153,15 +151,8 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
private struct DatabaseValueDecoder: Decoder {
let dbValue: DatabaseValue
init(dbValue: DatabaseValue, codingPath: [CodingKey]) {
self.dbValue = dbValue
self.codingPath = codingPath
}
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { return [:] }
var userInfo: [CodingUserInfoKey: Any] { [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
throw DecodingError.typeMismatch(
@@ -176,13 +167,13 @@ private struct DatabaseValueDecoder: Decoder {
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
return DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
}
}
extension DatabaseValueConvertible where Self: Decodable {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
}
}
@@ -1,7 +1,7 @@
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
var codingPath: [CodingKey] { return [] }
var codingPath: [CodingKey] { [] }
/// Encodes a null value.
///
@@ -50,15 +50,11 @@ private struct DatabaseValueEncoder: Encoder {
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey] { return [] }
var codingPath: [CodingKey] { [] }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey: Any] = [:]
init(encode: @escaping (DatabaseValue) -> Void) {
self.encode = encode
}
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
@@ -88,7 +84,7 @@ private struct DatabaseValueEncoder: Encoder {
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
return DatabaseValueEncodingContainer(encode: encode)
DatabaseValueEncodingContainer(encode: encode)
}
}
@@ -14,11 +14,11 @@ extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue:
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawValue.databaseValue
rawValue.databaseValue
}
/// Returns a value initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
return RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
}
}
@@ -1,11 +1,3 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -23,7 +15,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return (self ? 1 : 0).databaseValue
(self ? 1 : 0).databaseValue
}
/// Returns a Bool initialized from *dbValue*, if possible.
@@ -115,12 +107,12 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
}
@@ -144,12 +136,12 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an Int8 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
}
@@ -173,12 +165,12 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an Int16 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
}
@@ -202,12 +194,12 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an Int32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
}
@@ -226,7 +218,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .int64(self))
DatabaseValue(storage: .int64(self))
}
/// Returns an Int64 initialized from *dbValue*, if possible.
@@ -264,12 +256,12 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
}
@@ -293,12 +285,12 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an UInt8 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
}
@@ -322,12 +314,12 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an UInt16 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
}
@@ -351,12 +343,12 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an UInt32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
}
@@ -380,12 +372,12 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
Int64(self).databaseValue
}
/// Returns an UInt64 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
}
@@ -404,7 +396,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .double(self))
DatabaseValue(storage: .double(self))
}
/// Returns a Double initialized from *dbValue*, if possible.
@@ -435,7 +427,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Double(self).databaseValue
Double(self).databaseValue
}
/// Returns a Float initialized from *dbValue*, if possible.
@@ -466,7 +458,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .string(self))
DatabaseValue(storage: .string(self))
}
/// Returns a String initialized from *dbValue*, if possible.
+29 -41
View File
@@ -1,11 +1,3 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
@@ -54,7 +46,7 @@ extension Database {
}
// Ignore individual changes and transaction rollbacks
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidRollback(_ db: Database) { }
@@ -504,7 +496,7 @@ class DatabaseObservationBroker {
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func databaseDidEndTransaction() {
transactionObservations = transactionObservations.filter { $0.isObserving }
transactionObservations = transactionObservations.filter(\.isObserving)
// Undo disableUntilNextTransaction(transactionObserver:)
for observation in transactionObservations {
@@ -730,7 +722,7 @@ public protocol TransactionObserver: AnyObject {
///
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite.
/// version of SQLite:
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
@@ -794,10 +786,10 @@ final class TransactionObservation {
private weak var weakObserver: TransactionObserver?
private var strongObserver: TransactionObserver?
private var observer: TransactionObserver? { return strongObserver ?? weakObserver }
private var observer: TransactionObserver? { strongObserver ?? weakObserver }
fileprivate var isObserving: Bool {
return observer != nil
observer != nil
}
init(observer: TransactionObserver, extent: Database.TransactionObservationExtent) {
@@ -814,7 +806,7 @@ final class TransactionObservation {
}
func isWrapping(_ observer: TransactionObserver) -> Bool {
return self.observer === observer
self.observer === observer
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
@@ -934,10 +926,10 @@ public struct DatabaseEvent {
public let kind: Kind
/// The database name
public var databaseName: String { return impl.databaseName }
public var databaseName: String { impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
public var tableName: String { impl.tableName }
/// The rowID of the changed row.
public let rowID: Int64
@@ -951,7 +943,7 @@ public struct DatabaseEvent {
/// }
/// }
public func copy() -> DatabaseEvent {
return impl.copy(self)
impl.copy(self)
}
fileprivate init(kind: Kind, rowID: Int64, impl: DatabaseEventImpl) {
@@ -999,11 +991,11 @@ private struct MetalDatabaseEventImpl: DatabaseEventImpl {
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
var databaseName: String { String(cString: databaseNameCString!) }
var tableName: String { String(cString: tableNameCString!) }
func copy(_ event: DatabaseEvent) -> DatabaseEvent {
return DatabaseEvent(
DatabaseEvent(
kind: event.kind,
rowID: event.rowID,
impl: CopiedDatabaseEventImpl(
@@ -1016,9 +1008,7 @@ private struct MetalDatabaseEventImpl: DatabaseEventImpl {
private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
let databaseName: String
let tableName: String
func copy(_ event: DatabaseEvent) -> DatabaseEvent {
return event
}
func copy(_ event: DatabaseEvent) -> DatabaseEvent { event }
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
@@ -1041,13 +1031,13 @@ public struct DatabasePreUpdateEvent {
public let kind: Kind
/// The database name
public var databaseName: String { return impl.databaseName }
public var databaseName: String { impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
public var tableName: String { impl.tableName }
/// The number of columns in the row that is being inserted, updated, or deleted.
public var count: Int { return Int(impl.columnsCount) }
public var count: Int { Int(impl.columnsCount) }
/// The triggering depth of the row update
/// Returns:
@@ -1056,7 +1046,7 @@ public struct DatabasePreUpdateEvent {
/// 1 for inserts, updates, or deletes invoked by top-level triggers;
/// 2 for changes resulting from triggers called by top-level triggers;
/// ... and so forth
public var depth: CInt { return impl.depth }
public var depth: CInt { impl.depth }
/// The initial rowID of the row being changed for .Update and .Delete changes,
/// and nil for .Insert changes.
@@ -1119,7 +1109,7 @@ public struct DatabasePreUpdateEvent {
/// }
/// }
public func copy() -> DatabasePreUpdateEvent {
return impl.copy(self)
impl.copy(self)
}
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) {
@@ -1194,11 +1184,11 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
var databaseName: String { String(cString: databaseNameCString!) }
var tableName: String { String(cString: tableNameCString!) }
var columnsCount: CInt { return sqlite3_preupdate_count(connection) }
var depth: CInt { return sqlite3_preupdate_depth(connection) }
var columnsCount: CInt { sqlite3_preupdate_count(connection) }
var depth: CInt { sqlite3_preupdate_depth(connection) }
var initialDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .delete else { return nil }
return preupdate_getValues_old(connection)
@@ -1232,7 +1222,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
}
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return DatabasePreUpdateEvent(
DatabasePreUpdateEvent(
kind: event.kind,
initialRowID: event.initialRowID,
finalRowID: event.finalRowID,
@@ -1278,7 +1268,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
}
private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(
preupdate_getValues(
connection,
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_old(connection, column, &value)
@@ -1286,7 +1276,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
}
private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(
preupdate_getValues(
connection,
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_new(connection, column, &value)
@@ -1303,12 +1293,10 @@ private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let initialDatabaseValues: [DatabaseValue]?
let finalDatabaseValues: [DatabaseValue]?
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] }
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] }
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { initialDatabaseValues?[index] }
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { finalDatabaseValues?[index] }
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return event
}
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { event }
}
#endif
@@ -1363,7 +1351,7 @@ class SavepointStack {
private var savepoints: [(name: String, index: Int)] = []
/// If true, there is no current save point.
var isEmpty: Bool { return savepoints.isEmpty }
var isEmpty: Bool { savepoints.isEmpty }
func clear() {
eventsBuffer.removeAll()
+8
View File
@@ -0,0 +1,8 @@
// Export the underlying SQLite library
#if SWIFT_PACKAGE
@_exported import CSQLite
#elseif GRDBCIPHER
@_exported import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@_exported import SQLite3
#endif
+1 -1
View File
@@ -43,7 +43,7 @@ public struct FTS3: VirtualTableModule {
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition() -> FTS3TableDefinition {
return FTS3TableDefinition()
FTS3TableDefinition()
}
/// Reserved; part of the VirtualTableModule protocol.
+2 -46
View File
@@ -31,7 +31,6 @@ public struct FTS3Pattern {
self.rawPattern = rawPattern
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
@@ -70,61 +69,18 @@ public struct FTS3Pattern {
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#else
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAnyTokenIn: "") // nil
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(OSX 10.10, *)
public init?(matchingAnyTokenIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAllTokensIn: "") // nil
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(OSX 10.10, *)
public init?(matchingAllTokensIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS3Pattern(matchingPhrase: "") // nil
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(OSX 10.10, *)
public init?(matchingPhrase string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#endif
}
extension FTS3Pattern: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
rawPattern.databaseValue
}
/// Returns an FTS3Pattern initialized from *dbValue*, if it contains
/// a suitable value.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern? {
return String
String
.fromDatabaseValue(dbValue)
.flatMap { try? FTS3Pattern(rawPattern: $0) }
}
+3 -43
View File
@@ -32,7 +32,6 @@ public struct FTS3TokenizerDescriptor {
/// See https://www.sqlite.org/fts3.html#tokenizer
public static let porter = FTS3TokenizerDescriptor("porter")
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS4()) { t in
@@ -54,37 +53,8 @@ public struct FTS3TokenizerDescriptor {
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
_unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#else
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS4()) { t in
/// t.tokenizer = .unicode61()
/// }
///
/// - parameters:
/// - diacritics: By default SQLite will strip diacritics from
/// latin characters.
/// - separators: Unless empty (the default), SQLite will consider these
/// characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will consider
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
@available(OSX 10.10, *)
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#endif
private static func _unicode61(
diacritics: FTS3.Diacritics,
@@ -118,25 +88,15 @@ public struct FTS3TokenizerDescriptor {
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
_tokenize(string)
}
#else
@available(OSX 10.10, *)
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
}
#endif
/// Returns an array of tokens found in the string argument.
///
/// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"]
private func _tokenize(_ string: String) -> [String] {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return DatabaseQueue().inDatabase { db in
DatabaseQueue().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(name)
for option in arguments {
+3 -29
View File
@@ -29,7 +29,7 @@ public struct FTS4: VirtualTableModule {
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition() -> FTS4TableDefinition {
return FTS4TableDefinition()
FTS4TableDefinition()
}
/// Reserved; part of the VirtualTableModule protocol.
@@ -101,10 +101,10 @@ public struct FTS4: VirtualTableModule {
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
let indexedColumns = definition.columns.map { $0.name }
let indexedColumns = definition.columns.map(\.name)
let ftsColumns = (["docid"] + indexedColumns)
.map { $0.quotedDatabaseIdentifier }
.map(\.quotedDatabaseIdentifier)
.joined(separator: ", ")
let newContentColumns = ([rowIDColumn] + indexedColumns)
@@ -261,7 +261,6 @@ public final class FTS4ColumnDefinition {
self.isLanguageId = false
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS4()) { t in
@@ -272,36 +271,11 @@ public final class FTS4ColumnDefinition {
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
/// :nodoc:
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
#else
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS4()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
///
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
@available(OSX 10.10, *)
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
#endif
/// Uses the column as the Int32 language id hidden column.
///
+3 -17
View File
@@ -1,12 +1,5 @@
#if SQLITE_ENABLE_FTS5
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// FTS5 lets you define "fts5" virtual tables.
///
@@ -55,7 +48,7 @@ public struct FTS5: VirtualTableModule {
/// Don't use this method.
public func makeTableDefinition() -> FTS5TableDefinition {
return FTS5TableDefinition()
FTS5TableDefinition()
}
/// Don't use this method.
@@ -137,10 +130,10 @@ public struct FTS5: VirtualTableModule {
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
let indexedColumns = definition.columns.map { $0.name }
let indexedColumns = definition.columns.map(\.name)
let ftsColumns = (["rowid"] + indexedColumns)
.map { $0.quotedDatabaseIdentifier }
.map(\.quotedDatabaseIdentifier)
.joined(separator: ", ")
let newContentColumns = ([rowIDColumn] + indexedColumns)
@@ -200,15 +193,9 @@ public struct FTS5: VirtualTableModule {
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
fatalError("FTS5 is not available")
}
#if swift(>=5.0)
return data.withUnsafeBytes {
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
}
#else
return data.withUnsafeBytes {
$0.pointee
}
#endif
}
// Technique given by Jordan Rose:
@@ -221,7 +208,6 @@ public struct FTS5: VirtualTableModule {
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
-> UnsafePointer<fts5_api>
{
let sqliteConnection = db.sqliteConnection
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
+1 -8
View File
@@ -1,11 +1,4 @@
#if SQLITE_ENABLE_FTS5
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// The protocol for custom FTS5 tokenizers.
public protocol FTS5CustomTokenizer: FTS5Tokenizer {
@@ -39,7 +32,7 @@ extension FTS5CustomTokenizer {
/// t.tokenizer = tokenizer
/// }
public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor {
return FTS5TokenizerDescriptor(components: [name] + arguments)
FTS5TokenizerDescriptor(components: [name] + arguments)
}
}
+3 -3
View File
@@ -128,20 +128,20 @@ extension Database {
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name })
try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map(\.name))
}
}
extension FTS5Pattern: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
rawPattern.databaseValue
}
/// Returns an FTS5Pattern initialized from *dbValue*, if it
/// contains a suitable value.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? {
return String
String
.fromDatabaseValue(dbValue)
.flatMap { try? FTS5Pattern(rawPattern: $0) }
}
+2 -9
View File
@@ -1,12 +1,5 @@
#if SQLITE_ENABLE_FTS5
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
@@ -86,7 +79,7 @@ extension FTS5Tokenizer {
/// - .query: Tokenize like the search pattern of the MATCH operator.
/// - parameter tokenizer: A FTS5TokenizerDescriptor such as .ascii()
func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [(String, FTS5TokenFlags)] {
return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in
try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in
guard let addr = buffer.baseAddress else {
return []
}
@@ -170,7 +163,7 @@ extension Database {
_ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result)
-> Result
{
return car.withCString { cString in
car.withCString { cString in
if let car = cdr.first {
array.append(cString)
return convertArguments(&array, car, Array(cdr.suffix(from: 1)), body)
+2 -4
View File
@@ -23,12 +23,10 @@ public struct FTS5TokenizerDescriptor {
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
var name: String {
return components[0]
}
var name: String { components[0] }
var arguments: [String] {
return Array(components.suffix(from: 1))
Array(components.suffix(from: 1))
}
/// Creates an FTS5 tokenizer descriptor.
-7
View File
@@ -1,12 +1,5 @@
#if SQLITE_ENABLE_FTS5
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Flags that tell SQLite how to register a token.
///
-271
View File
@@ -1,271 +0,0 @@
import Dispatch
// Fixits for changes introduced by GRDB 4.0.0
extension Cursor {
@available(*, unavailable, renamed: "compactMap")
public func flatMap<ElementOfResult>(
_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{ preconditionFailure() }
}
extension DatabaseWriter {
@available(*, unavailable, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() }
}
extension ValueObservation {
@available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer)
-> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "Use removeDuplicates() instead")
public static func tracking<Value>(
_ regions: DatabaseRegionConvertible...,
fetchDistinct fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Value>>>
where Value: Equatable
{ preconditionFailure() }
}
@available(*, unavailable, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value> = FastDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value> = FastNullableDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
extension Database {
@available(*, unavailable, renamed: "execute(sql:arguments:)")
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws { preconditionFailure() }
@available(*, unavailable, renamed: "makeSelectStatement(sql:)")
public func makeSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedSelectStatement(sql:)")
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "makeUpdateStatement(sql:)")
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedUpdateStatement(sql:)")
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
}
extension DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{ preconditionFailure() }
}
extension Row {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RowCursor
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Row]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Row?
{ preconditionFailure() }
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RecordCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension SQLRequest {
@available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)")
public init(
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
cached: Bool = false)
{ preconditionFailure() }
}
extension SQLExpressionLiteral {
@available(*, unavailable, renamed: "init(sql:arguments:)")
public init(_ sql: String, arguments: StatementArguments? = nil) { preconditionFailure() }
}
extension SQLExpression {
@available(*, unavailable, message: "Use sqlLiteral property instead")
public var literal: SQLExpressionLiteral { preconditionFailure() }
}
extension FTS3TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(
removeDiacritics: Bool,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{ preconditionFailure() }
}
#if SQLITE_ENABLE_FTS5
extension FTS5TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(
removeDiacritics: Bool = true,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS5TokenizerDescriptor
{ preconditionFailure() }
}
#endif
extension DatabaseValue {
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T
where T: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T?
where T: DatabaseValueConvertible
{ preconditionFailure() }
}
extension ValueScheduling {
@available(*, unavailable, renamed: "async(onQueue:startImmediately:)")
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool)
-> ValueScheduling
{ preconditionFailure() }
}
extension ValueObservation {
// swiftlint:disable:next line_length
@available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.")
public var extent: Database.TransactionObservationExtent {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension Configuration {
@available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.prepareDatabase instead.")
public var cipherPageSize: Int {
get { preconditionFailure() }
set { preconditionFailure() }
}
@available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.prepareDatabase instead.")
public var kdfIterations: Int {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
+502
View File
@@ -0,0 +1,502 @@
// Fixits for changes introduced by GRDB 5.0.0
// swiftlint:disable all
import Dispatch
#if os(iOS)
import UIKit
#endif
extension AnyFetchRequest {
@available(*, unavailable, message: "Define your own FetchRequest type instead.")
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
{ preconditionFailure() }
}
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public struct AnyValueReducer<Fetched, Value>: _ValueReducer {
public var isSelectedRegionDeterministic: Bool
{ preconditionFailure() }
public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
{ preconditionFailure() }
public init<Base: _ValueReducer>(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value
{ preconditionFailure() }
public func fetch(_ db: Database) throws -> Fetched
{ preconditionFailure() }
public func value(_ fetched: Fetched) -> Value?
{ preconditionFailure() }
}
extension AssociationAggregate {
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ name: String) -> AssociationAggregate<RowDecoder>
{ preconditionFailure() }
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
{ preconditionFailure() }
}
extension DatabaseFunction {
@available(*, unavailable, renamed: "callAsFunction(_:)")
public func apply(_ arguments: SQLExpressible...) -> SQLExpression
{ preconditionFailure() }
}
extension DatabaseMigrator {
@available(*, unavailable, renamed: "registerMigration(_:migrate:)")
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{ preconditionFailure() }
@available(*, unavailable, message: "Wrap this method: reader.read(migrator.appliedMigrations) }")
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String>
{ preconditionFailure() }
@available(*, unavailable, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }")
public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool
{ preconditionFailure() }
@available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)")
public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool
{ preconditionFailure() }
@available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).last")
public func lastCompletedMigration(in reader: DatabaseReader) throws -> String?
{ preconditionFailure() }
}
extension DatabasePool {
#if os(iOS)
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
#endif
}
extension DatabaseQueue {
#if os(iOS)
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
#endif
}
extension FetchRequest {
@available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.")
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchCount) instead")
public func observationForCount() -> ValueObservation<ValueReducers.Unavailable<Int>>
{ preconditionFailure() }
}
extension FetchRequest where RowDecoder: DatabaseValueConvertible {
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead")
public func observationForAll() -> ValueObservation<ValueReducers.Unavailable<[RowDecoder]>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead")
public func observationForFirst() -> ValueObservation<ValueReducers.Unavailable<RowDecoder?>>
{ preconditionFailure() }
}
extension FetchRequest where RowDecoder: FetchableRecord {
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead")
public func observationForAll() -> ValueObservation<ValueReducers.Unavailable<[RowDecoder]>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead")
public func observationForFirst() -> ValueObservation<ValueReducers.Unavailable<RowDecoder?>>
{ preconditionFailure() }
}
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible {
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead")
public func observationForAll() -> ValueObservation<ValueReducers.Unavailable<[RowDecoder.Wrapped?]>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead")
public func observationForFirst() -> ValueObservation<ValueReducers.Unavailable<RowDecoder.Wrapped?>>
{ preconditionFailure() }
}
extension FetchRequest where RowDecoder == Row {
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchAll) instead")
public func observationForAll() -> ValueObservation<ValueReducers.Unavailable<[Row]>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchOne) instead")
public func observationForFirst() -> ValueObservation<ValueReducers.Unavailable<Row?>>
{ preconditionFailure() }
}
extension SQLExpression {
@available(*, unavailable, message: "Use SQLLiteral initializer instead")
public var sqlLiteral: SQLLiteral
{ preconditionFailure() }
}
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
public struct SQLExpressionLiteral: SQLExpression {
public var sql: String { preconditionFailure() }
public var arguments: StatementArguments { preconditionFailure() }
public init(sql: String, arguments: StatementArguments = StatementArguments())
{ preconditionFailure() }
public init(literal sqlLiteral: SQLLiteral)
{ preconditionFailure() }
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
{ preconditionFailure() }
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression
{ preconditionFailure() }
}
extension SQLLiteral {
@available(*, unavailable, message: "Use SQL interpolation instead.")
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral
{ preconditionFailure() }
}
@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
extension SQLSpecificExpressible {
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ name: String) -> SQLSelectable
{ preconditionFailure() }
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> SQLSelectable
{ preconditionFailure() }
}
extension Statement {
@available(*, unavailable, renamed: "setUncheckedArguments(_:)")
public func unsafeSetArguments(_ arguments: StatementArguments)
{ preconditionFailure() }
@available(*, unavailable, renamed: "validateArguments(_:)")
public func validate(arguments: StatementArguments) throws
{ preconditionFailure() }
}
extension TableRecord {
@available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchCount) instead")
public static func observationForCount() -> ValueObservation<ValueReducers.Unavailable<Int>>
{ preconditionFailure() }
}
extension TableRecord where Self: FetchableRecord {
@available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchAll) instead")
public static func observationForAll() -> ValueObservation<ValueReducers.Unavailable<[Self]>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchOne) instead")
public static func observationForFirst() -> ValueObservation<ValueReducers.Unavailable<Self?>>
{ preconditionFailure() }
}
extension ValueObservation {
@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration")
var scheduling: ValueScheduling {
get { preconditionFailure() }
set { preconditionFailure() }
}
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: @escaping (Database) throws -> Reducer) -> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func tracking(_ regions: [DatabaseRegionConvertible], reducer: @escaping (Database) throws -> Reducer) -> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
Combined>(
_ other: ValueObservation<R1>,
_ transform: @escaping (Reducer.Value, R1.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
R2: _ValueReducer,
Combined>(
_ observation1: ValueObservation<R1>,
_ observation2: ValueObservation<R2>,
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
Combined>(
_ observation1: ValueObservation<R1>,
_ observation2: ValueObservation<R2>,
_ observation3: ValueObservation<R3>,
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
R4: _ValueReducer,
Combined>(
_ observation1: ValueObservation<R1>,
_ observation2: ValueObservation<R2>,
_ observation3: ValueObservation<R3>,
_ observation4: ValueObservation<R4>,
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value, R4.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "compactMap is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func compactMap<T>(_ transform: @escaping (Reducer.Value) -> T?) -> ValueObservation<ValueReducers.Unavailable<T>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use start(in:onError:onChange:) instead.")
public func start(
in reader: DatabaseReader,
onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver
{ preconditionFailure() }
}
extension ValueObservation where Reducer == ValueReducers.Auto {
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value, R3.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
R4: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value, R3.Value, R4.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
R4: _ValueReducer,
R5: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>,
_ o5: ValueObservation<R5>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
R4: _ValueReducer,
R5: _ValueReducer,
R6: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>,
_ o5: ValueObservation<R5>,
_ o6: ValueObservation<R6>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value, R6.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
R4: _ValueReducer,
R5: _ValueReducer,
R6: _ValueReducer,
R7: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>,
_ o5: ValueObservation<R5>,
_ o6: ValueObservation<R6>,
_ o7: ValueObservation<R7>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value, R6.Value, R7.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func combine<
R1: _ValueReducer,
R2: _ValueReducer,
R3: _ValueReducer,
R4: _ValueReducer,
R5: _ValueReducer,
R6: _ValueReducer,
R7: _ValueReducer,
R8: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>,
_ o3: ValueObservation<R3>,
_ o4: ValueObservation<R4>,
_ o5: ValueObservation<R5>,
_ o6: ValueObservation<R6>,
_ o7: ValueObservation<R7>,
_ o8: ValueObservation<R8>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value, R3.Value, R4.Value, R5.Value, R6.Value, R7.Value, R8.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingCount<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<Int>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<[Request.RowDecoder]>>
where Request.RowDecoder: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<Request.RowDecoder?>>
where Request.RowDecoder: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<[Request.RowDecoder.Wrapped?]>>
where Request.RowDecoder: _OptionalProtocol,
Request.RowDecoder.Wrapped: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<[Request.RowDecoder]>>
where Request.RowDecoder: FetchableRecord
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request) ->
ValueObservation<ValueReducers.Unavailable<Request.RowDecoder?>>
where Request.RowDecoder: FetchableRecord
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<[Row]>>
where Request.RowDecoder == Row
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.Unavailable<Row?>>
where Request.RowDecoder == Row
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func tracking<Value>(
_ regions: DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Unavailable<Value>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use ValueObservation.tracking(_:) instead")
public static func tracking<Value>(
_ regions: [DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Unavailable<Value>>
{ preconditionFailure() }
@available(*, unavailable, renamed: "tracking(_:)")
public static func tracking<Value>(
value: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Unavailable<Value>>
{ preconditionFailure() }
}
extension ValueObservation where Reducer.Value: Equatable {
@available(*, unavailable, renamed: "removeDuplicates")
public func distinctUntilChanged() -> ValueObservation<ValueReducers.Unavailable<Reducer.Value>>
{ preconditionFailure() }
}
extension ValueReducers {
@available(*, unavailable)
public enum Unavailable<T>: _ValueReducer {
public var isSelectedRegionDeterministic: Bool
{ preconditionFailure() }
public func fetch(_ db: Database) throws -> Never
{ preconditionFailure() }
public mutating func value(_ fetched: Never) -> T? { }
}
}
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
typealias ValueReducer = _ValueReducer
@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration")
enum ValueScheduling {
case mainQueue
case async(onQueue: DispatchQueue, startImmediately: Bool)
case unsafe(startImmediately: Bool)
}
#if SQLITE_HAS_CODEC
extension Configuration {
@available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
public var passphrase: String? {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension DatabasePool {
@available(*, unavailable, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws { preconditionFailure() }
}
extension DatabaseQueue {
@available(*, unavailable, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws { preconditionFailure() }
}
#endif
+3 -65
View File
@@ -93,28 +93,6 @@ public struct DatabaseMigrator {
registerMigration(Migration(identifier: identifier, migrate: migrate))
}
/// Registers a migration.
///
/// migrator.registerMigrationWithDeferredForeignKeyCheck("createAuthors") { db in
/// try db.create(table: "author") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("creationDate", .datetime)
/// t.column("name", .text).notNull()
/// }
/// }
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
@available(*, deprecated, renamed: "registerMigration(_:migrate:)")
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{
registerMigration(identifier, migrate: migrate)
}
// MARK: - Applying Migrations
/// Iterate migrations in the same order as they were registered. If a
@@ -192,15 +170,6 @@ public struct DatabaseMigrator {
// MARK: - Querying Migrations
/// Returns the set of applied migration identifiers.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - throws: An eventual database error.
@available(*, deprecated, message: "Wrap this method: reader.read(migrator.appliedMigrations) }")
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String> {
return try Set(reader.read(appliedMigrations))
}
/// Returns the applied migration identifiers, in the same order as
/// registered migrations.
///
@@ -218,51 +187,20 @@ public struct DatabaseMigrator {
/// - throws: An eventual database error.
public func completedMigrations(_ db: Database) throws -> [String] {
let appliedIdentifiers = try appliedMigrations(db)
let knownIdentifiers = migrations.map { $0.identifier }
let knownIdentifiers = migrations.map(\.identifier)
return Array(zip(appliedIdentifiers, knownIdentifiers)
.prefix(while: { $0 == $1 })
.map { $0.0 })
}
/// Returns true if all migrations are applied.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - throws: An eventual database error.
@available(*, deprecated, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }")
public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool {
return try reader.read(hasCompletedMigrations)
}
/// Returns true if all migrations are applied.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
return try completedMigrations(db).last == migrations.last?.identifier
try completedMigrations(db).last == migrations.last?.identifier
}
/// Returns true if all migrations up to the provided target are applied,
/// and maybe further.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - parameter targetIdentifier: The identifier of a registered migration.
/// - throws: An eventual database error.
@available(*, deprecated, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)")
public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool {
return try reader.read(completedMigrations).contains(targetIdentifier)
}
/// Returns the identifier of the last migration for which all predecessors
/// have been applied.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - returns: An eventual migration identifier.
/// - throws: An eventual database error.
@available(*, deprecated, message: "Prefer reader.read(migrator.completedMigrations).last")
public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? {
return try reader.read(completedMigrations).last
}
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
-14
View File
@@ -1,21 +1,8 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An internal struct that defines a migration.
struct Migration {
let identifier: String
let migrate: (Database) throws -> Void
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.migrate = migrate
}
func run(_ db: Database) throws {
// PRAGMA foreign_key_check and SQLITE_CONSTRAINT_FOREIGNKEY were
// introduced in SQLite 3.7.16
@@ -27,7 +14,6 @@ struct Migration {
}
}
private func runWithoutDisabledForeignKeys(_ db: Database) throws {
try db.inTransaction(.immediate) {
try migrate(db)
@@ -37,7 +37,7 @@ extension TableRecord {
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
all().matching(pattern)
}
}
@@ -50,6 +50,6 @@ extension ColumnExpression {
/// If the search pattern is nil, SQLite will evaluate the expression
/// to false.
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
}
}
@@ -38,7 +38,7 @@ extension TableRecord {
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
all().matching(pattern)
}
}
#endif
@@ -46,33 +46,33 @@ public protocol Association: DerivableRequest {
extension Association {
/// :nodoc:
public func _including(all association: SQLAssociation) -> Self {
return mapDestinationRelation { $0._including(all: association) }
mapDestinationRelation { $0._including(all: association) }
}
/// :nodoc:
public func _including(optional association: SQLAssociation) -> Self {
return mapDestinationRelation { $0._including(optional: association) }
mapDestinationRelation { $0._including(optional: association) }
}
/// :nodoc:
public func _including(required association: SQLAssociation) -> Self {
return mapDestinationRelation { $0._including(required: association) }
mapDestinationRelation { $0._including(required: association) }
}
/// :nodoc:
public func _joining(optional association: SQLAssociation) -> Self {
return mapDestinationRelation { $0._joining(optional: association) }
mapDestinationRelation { $0._joining(optional: association) }
}
/// :nodoc:
public func _joining(required association: SQLAssociation) -> Self {
return mapDestinationRelation { $0._joining(required: association) }
mapDestinationRelation { $0._joining(required: association) }
}
}
extension Association {
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
return .init(sqlAssociation: sqlAssociation.map(\.destination.relation, transform))
.init(sqlAssociation: sqlAssociation.map(\.destination.relation, transform))
}
}
@@ -102,9 +102,7 @@ extension Association {
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["custom"]
/// }
var key: SQLAssociationKey {
return sqlAssociation.destination.key
}
var key: SQLAssociationKey { sqlAssociation.destination.key }
/// Creates an association which selects *selection*.
///
@@ -128,7 +126,7 @@ extension Association {
/// .select([Column("color")])
/// var request = Player.including(required: association)
public func select(_ selection: [SQLSelectable]) -> Self {
return mapDestinationRelation { $0.select(selection) }
mapDestinationRelation { $0.select(selection) }
}
/// Creates an association which appends *selection*.
@@ -145,7 +143,7 @@ extension Association {
/// .annotated(with: [Column("name")])
/// var request = Player.including(required: association)
public func annotated(with selection: [SQLSelectable]) -> Self {
return mapDestinationRelation { $0.annotated(with: selection) }
mapDestinationRelation { $0.annotated(with: selection) }
}
/// Creates an association with the provided *predicate promise* added to
@@ -161,7 +159,7 @@ extension Association {
/// let association = Player.team.filter { db in true }
/// var request = Player.including(required: association)
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
return mapDestinationRelation { $0.filter(predicate) }
mapDestinationRelation { $0.filter(predicate) }
}
/// Creates an association with the provided *orderings promise*.
@@ -189,7 +187,7 @@ extension Association {
/// .order{ _ in [Column("name")] }
/// var request = Player.including(required: association)
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
return mapDestinationRelation { $0.order(orderings) }
mapDestinationRelation { $0.order(orderings) }
}
/// Creates an association that reverses applied orderings.
@@ -213,7 +211,7 @@ extension Association {
/// let association = Player.team.reversed()
/// var request = Player.including(required: association)
public func reversed() -> Self {
return mapDestinationRelation { $0.reversed() }
mapDestinationRelation { $0.reversed() }
}
/// Creates an association without any ordering.
@@ -228,7 +226,7 @@ extension Association {
/// let association = Player.team.order(Column("name")).unordered()
/// var request = Player.including(required: association)
public func unordered() -> Self {
return mapDestinationRelation { $0.unordered() }
mapDestinationRelation { $0.unordered() }
}
/// Creates an association with the given key.
@@ -254,7 +252,7 @@ extension Association {
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
return forKey(codingKey.stringValue)
forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
@@ -286,14 +284,14 @@ extension Association {
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
return mapDestinationRelation { $0.qualified(with: alias) }
mapDestinationRelation { $0.qualified(with: alias) }
}
}
// TableRequest
extension Association {
/// :nodoc:
public var databaseTableName: String { return RowDecoder.databaseTableName }
public var databaseTableName: String { RowDecoder.databaseTableName }
}
// MARK: - AssociationToOne
@@ -326,7 +324,7 @@ extension AssociationToMany {
extension AssociationToMany {
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let tableAlias = TableAlias()
let request = request
.joining(optional: self.aliased(tableAlias))
@@ -352,7 +350,8 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
return makeAggregate(SQLExpressionCountDistinct(Column.rowID))
// TODO: try to replace rowid with actual primary key
makeAggregate(SQLExpressionCountDistinct(Column.rowID))
.forKey("\(key.singularizedName)Count")
}
@@ -372,7 +371,8 @@ extension AssociationToMany {
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
// TODO: try to replace rowid with actual primary key
makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
@@ -27,6 +27,7 @@ typealias AssociationAggregatePreparation<RowDecoder> =
/// // Won't compile because Fruit is not Author.
/// let request = Fruit.annotated(with: bookCount)
public struct AssociationAggregate<RowDecoder> {
// TODO: replace rowid with actual primary key in the doc when implemented
/// Given a request, returns a tuple made of a request extended with the
/// associated records used to compute the aggregate, and an expression
/// whose value is the aggregated value.
@@ -63,28 +64,10 @@ public struct AssociationAggregate<RowDecoder> {
let prepare: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String?
init(_ prepare: @escaping AssociationAggregatePreparation<RowDecoder>) {
self.prepare = prepare
}
var key: String? = nil
}
extension AssociationAggregate: KeyPathRefining {
/// Returns an aggregate that is selected in a column with the given name.
///
/// For example:
///
/// let aggregate = Author.books.count.aliased("numberOfBooks")
/// let request = Author.annotated(with: aggregate)
/// if let row = try Row.fetchOne(db, request) {
/// let numberOfBooks: Int = row["numberOfBooks"]
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ name: String) -> AssociationAggregate<RowDecoder> {
return forKey(name)
}
extension AssociationAggregate: Refinable {
/// Returns an aggregate that is selected in a column with the given name.
///
/// For example:
@@ -94,28 +77,8 @@ extension AssociationAggregate: KeyPathRefining {
/// if let row = try Row.fetchOne(db, request) {
/// let numberOfBooks: Int = row["numberOfBooks"]
/// }
public func forKey(_ key: String) -> AssociationAggregate<RowDecoder> {
return with(\.key, key)
}
/// Returns an aggregate that is selected in a column named like the given
/// coding key.
///
/// For example:
///
/// struct AuthorInfo: Decodable, FetchableRecord {
/// var author: Author
/// var numberOfBooks: Int
///
/// static func fetchAll(_ db: Database) throws -> [AuthorInfo] {
/// let aggregate = Author.books.count.aliased(CodingKeys.numberOfBooks)
/// let request = Author.annotated(with: aggregate)
/// return try AuthorInfo.fetchAll(db, request)
/// }
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder> {
return forKey(key)
public func forKey(_ key: String) -> Self {
with(\.key, key)
}
/// Returns an aggregate that is selected in a column named like the given
@@ -133,8 +96,8 @@ extension AssociationAggregate: KeyPathRefining {
/// return try AuthorInfo.fetchAll(db, request)
/// }
/// }
public func forKey(_ key: CodingKey) -> AssociationAggregate<RowDecoder> {
return forKey(key.stringValue)
public func forKey(_ key: CodingKey) -> Self {
forKey(key.stringValue)
}
}
@@ -146,7 +109,7 @@ extension AssociationAggregate: KeyPathRefining {
///
/// Author.having(!Author.books.isEmpty)
public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression: !expression)
}
@@ -162,7 +125,7 @@ public func && <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression && rExpression)
@@ -176,7 +139,7 @@ public func && <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression && rhs)
}
@@ -189,7 +152,7 @@ public func && <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs && expression)
}
@@ -206,7 +169,7 @@ public func || <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression || rExpression)
@@ -220,7 +183,7 @@ public func || <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression || rhs)
}
@@ -233,7 +196,7 @@ public func || <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs || expression)
}
@@ -251,7 +214,7 @@ public func == <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression == rExpression)
@@ -268,7 +231,7 @@ public func == <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
@@ -284,7 +247,7 @@ public func == <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
@@ -296,7 +259,7 @@ public func == <RowDecoder>(
///
/// Author.having(Author.books.isEmpty == false)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
@@ -308,7 +271,7 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// Author.having(false == Author.books.isEmpty)
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
@@ -324,7 +287,7 @@ public func != <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression != rExpression)
@@ -341,7 +304,7 @@ public func != <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
@@ -357,7 +320,7 @@ public func != <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
@@ -369,7 +332,7 @@ public func != <RowDecoder>(
///
/// Author.having(Author.books.isEmpty != true)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
@@ -381,7 +344,7 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// Author.having(true != Author.books.isEmpty)
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
@@ -397,7 +360,7 @@ public func === <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression === rExpression)
@@ -414,7 +377,7 @@ public func === <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression === rhs)
}
@@ -430,7 +393,7 @@ public func === <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs === expression)
}
@@ -446,7 +409,7 @@ public func !== <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression !== rExpression)
@@ -463,7 +426,7 @@ public func !== <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression !== rhs)
}
@@ -479,7 +442,7 @@ public func !== <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs !== expression)
}
@@ -497,7 +460,7 @@ public func <= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression <= rExpression)
@@ -514,7 +477,7 @@ public func <= <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression <= rhs)
}
@@ -530,7 +493,7 @@ public func <= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs <= expression)
}
@@ -546,7 +509,7 @@ public func < <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression < rExpression)
@@ -563,7 +526,7 @@ public func < <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression < rhs)
}
@@ -579,7 +542,7 @@ public func < <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs < expression)
}
@@ -595,7 +558,7 @@ public func > <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression > rExpression)
@@ -612,7 +575,7 @@ public func > <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression > rhs)
}
@@ -628,7 +591,7 @@ public func > <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs > expression)
}
@@ -644,7 +607,7 @@ public func >= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression >= rExpression)
@@ -661,7 +624,7 @@ public func >= <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression >= rhs)
}
@@ -677,7 +640,7 @@ public func >= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs >= expression)
}
@@ -691,7 +654,7 @@ public func >= <RowDecoder>(
///
/// Author.annotated(with: -Author.books.count)
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression:-expression)
}
@@ -707,7 +670,7 @@ public func + <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression + rExpression)
@@ -724,7 +687,7 @@ public func + <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression + rhs)
}
@@ -740,7 +703,7 @@ public func + <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs + expression)
}
@@ -756,7 +719,7 @@ public func - <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression - rExpression)
@@ -773,7 +736,7 @@ public func - <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression - rhs)
}
@@ -789,7 +752,7 @@ public func - <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs - expression)
}
@@ -805,7 +768,7 @@ public func * <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression * rExpression)
@@ -822,7 +785,7 @@ public func * <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression * rhs)
}
@@ -838,7 +801,7 @@ public func * <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs * expression)
}
@@ -854,7 +817,7 @@ public func / <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression / rExpression)
@@ -871,7 +834,7 @@ public func / <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression / rhs)
}
@@ -887,7 +850,7 @@ public func / <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs / expression)
}
@@ -99,4 +99,69 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
relation: Destination.all().relation,
cardinality: .toMany)
}
/// Creates a "Has one" association between the source and
/// destination types.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let firstBook = hasMany(Book.self).order(Column("year")).first
/// }
///
/// The association lets you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, firstBook) pairs:
/// let request = Author.including(required: Author.firstBook)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var firstBook: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.firstBook.title) first")
/// }
public var first: HasOneAssociation<Origin, Destination> {
HasOneAssociation(sqlAssociation: sqlAssociation.associationForFirst())
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates a "Has one" association between the source and
/// destination types.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let lastBook = hasMany(Book.self).order(Column("year")).last
/// }
///
/// The association lets you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, firstBook) pairs:
/// let request = Author.including(required: Author.lastBook)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var lastBook: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.lastBook.title) last")
/// }
public var last: HasOneAssociation<Origin, Destination> {
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
}
}
@@ -55,4 +55,15 @@ public struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableR
public init(sqlAssociation: SQLAssociation) {
self.sqlAssociation = sqlAssociation
}
// TODO
public var first: HasOneThroughAssociation<Origin, Destination> {
HasOneThroughAssociation(sqlAssociation: sqlAssociation.associationForFirst())
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
}
// TODO
public var last: HasOneThroughAssociation<Origin, Destination> {
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
}
}
@@ -11,6 +11,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
}
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -18,9 +19,10 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
return annotated(with: aggregates)
annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -28,11 +30,12 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest {
return aggregates.reduce(self) { request, aggregate in
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
@@ -30,11 +30,9 @@
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<T> {
var query: SQLQuery
init(query: SQLQuery) {
self.query = query
}
}
extension QueryInterfaceRequest {
init(relation: SQLRelation) {
self.init(query: SQLQuery(relation: relation))
}
@@ -78,7 +76,7 @@ extension QueryInterfaceRequest: FetchRequest {
/// - parameter db: A database connection.
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try query.fetchCount(db)
try query.fetchCount(db)
}
/// Returns the database region that the request looks into.
@@ -86,7 +84,7 @@ extension QueryInterfaceRequest: FetchRequest {
/// - parameter db: A database connection.
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
var region = try SQLQueryGenerator(query).makeSelectStatement(db).databaseRegion
var region = try SQLQueryGenerator(query).makeSelectStatement(db).selectedRegion
// Iterate all prefetched associations
var fifo = query.relation.prefetchedAssociations
@@ -96,7 +94,7 @@ extension QueryInterfaceRequest: FetchRequest {
// Build the query for prefetched rows.
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
let pivotMappings = try association.pivot.condition.columnMappings(db)
let pivotColumns = pivotMappings.map { $0.right }
let pivotColumns = pivotMappings.map(\.right)
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
@@ -105,7 +103,7 @@ extension QueryInterfaceRequest: FetchRequest {
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
// Union region
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).databaseRegion)
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).selectedRegion)
// Append nested prefetched associations (support for
// A.including(all: A.bs.including(all: B.cs))
@@ -132,7 +130,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select([Column("id")])
/// .select([Column("email")])
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest {
return map(\.query, { $0.select(selection) })
map(\.query) { $0.select(selection) }
}
/// Creates a request which selects *selection*, and fetches values of
@@ -146,7 +144,7 @@ extension QueryInterfaceRequest: SelectionRequest {
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
return map(\.query, { $0.select(selection) }).asRequest(of: RowDecoder.self)
map(\.query, { $0.select(selection) }).asRequest(of: RowDecoder.self)
}
/// Creates a request which selects *selection*, and fetches values of
@@ -160,7 +158,7 @@ extension QueryInterfaceRequest: SelectionRequest {
public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
return select(selection, as: type)
select(selection, as: type)
}
/// Creates a request which selects *sql*, and fetches values of
@@ -177,7 +175,7 @@ extension QueryInterfaceRequest: SelectionRequest {
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
}
/// Creates a request which selects an SQL *literal*, and fetches values of
@@ -212,7 +210,7 @@ extension QueryInterfaceRequest: SelectionRequest {
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
return select(sqlLiteral.sqlSelectable, as: type)
select(sqlLiteral.sqlSelectable, as: type)
}
/// Creates a request which appends *selection*.
@@ -223,7 +221,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select([Column("id"), Column("email")])
/// .annotated(with: [Column("name")])
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest {
return map(\.query, { $0.annotated(with: selection) })
map(\.query) { $0.annotated(with: selection) }
}
}
@@ -237,7 +235,7 @@ extension QueryInterfaceRequest: FilteredRequest {
/// var request = Player.all()
/// request = request.filter { db in true }
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
return map(\.query, { $0.filter(predicate) })
map(\.query) { $0.filter(predicate) }
}
}
@@ -258,7 +256,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// .reversed()
/// .order{ _ in [Column("name")] }
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
return map(\.query, { $0.order(orderings) })
map(\.query) { $0.order(orderings) }
}
/// Creates a request that reverses applied orderings.
@@ -273,7 +271,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all()
/// request = request.reversed()
public func reversed() -> QueryInterfaceRequest {
return map(\.query, { $0.reversed() })
map(\.query) { $0.reversed() }
}
/// Creates a request without any ordering.
@@ -282,7 +280,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all().order(Column("name"))
/// request = request.unordered()
public func unordered() -> QueryInterfaceRequest {
return map(\.query, { $0.unordered() })
map(\.query) { $0.unordered() }
}
}
@@ -291,46 +289,46 @@ extension QueryInterfaceRequest: AggregatingRequest {
/// Creates a request grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
return map(\.query, { $0.group(expressions) })
map(\.query) { $0.group(expressions) }
}
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest {
return map(\.query, { $0.having(predicate) })
map(\.query) { $0.having(predicate) }
}
}
extension QueryInterfaceRequest: _JoinableRequest {
/// :nodoc:
public func _including(all association: SQLAssociation) -> QueryInterfaceRequest {
return map(\.query, { $0._including(all: association) })
map(\.query) { $0._including(all: association) }
}
/// :nodoc:
public func _including(optional association: SQLAssociation) -> QueryInterfaceRequest {
return map(\.query, { $0._including(optional: association) })
map(\.query) { $0._including(optional: association) }
}
/// :nodoc:
public func _including(required association: SQLAssociation) -> QueryInterfaceRequest {
return map(\.query, { $0._including(required: association) })
map(\.query) { $0._including(required: association) }
}
/// :nodoc:
public func _joining(optional association: SQLAssociation) -> QueryInterfaceRequest {
return map(\.query, { $0._joining(optional: association) })
map(\.query) { $0._joining(optional: association) }
}
/// :nodoc:
public func _joining(required association: SQLAssociation) -> QueryInterfaceRequest {
return map(\.query, { $0._joining(required: association) })
map(\.query) { $0._joining(required: association) }
}
}
extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
extension QueryInterfaceRequest: KeyPathRefining {
extension QueryInterfaceRequest: Refinable {
// MARK: Request Derivation
@@ -344,7 +342,7 @@ extension QueryInterfaceRequest: KeyPathRefining {
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest {
return map(\.query, { $0.distinct() })
map(\.query) { $0.distinct() }
}
/// Creates a request which expects a single result.
@@ -355,7 +353,7 @@ extension QueryInterfaceRequest: KeyPathRefining {
///
/// :nodoc:
public func expectingSingleResult() -> QueryInterfaceRequest {
return map(\.query, { $0.expectingSingleResult() })
map(\.query) { $0.expectingSingleResult() }
}
@@ -367,7 +365,7 @@ extension QueryInterfaceRequest: KeyPathRefining {
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
return map(\.query, { $0.limit(limit, offset: offset) })
map(\.query) { $0.limit(limit, offset: offset) }
}
/// Creates a request that allows you to define expressions that target
@@ -388,7 +386,7 @@ extension QueryInterfaceRequest: KeyPathRefining {
/// .aliased(playerAlias)
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
return map(\.query, { $0.qualified(with: alias) })
map(\.query) { $0.qualified(with: alias) }
}
/// Creates a request bound to type Target.
@@ -405,7 +403,7 @@ extension QueryInterfaceRequest: KeyPathRefining {
/// - parameter type: The fetched type Target
/// - returns: A typed request bound to type Target.
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return QueryInterfaceRequest<RowDecoder>(query: query)
QueryInterfaceRequest<RowDecoder>(query: query)
}
}
@@ -483,7 +481,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.all().updateAll(db, [Column("score") <- 0])
/// try Player.all().updateAll(db, [Column("score").set(to: 0)])
/// }
///
/// - parameter db: A database connection.
@@ -517,7 +515,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.all().updateAll(db, Column("score") <- 0)
/// try Player.all().updateAll(db, Column("score").set(to: 0))
/// }
///
/// - parameter db: A database connection.
@@ -535,7 +533,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
_ otherAssignments: ColumnAssignment...)
throws -> Int
{
return try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
}
}
@@ -575,7 +573,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
// // FROM book
// // WHERE authorId IN (1, 2, 3)
// Author.including(all: Author.books)
let pivotColumns = pivotMappings.map { $0.right }
let pivotColumns = pivotMappings.map(\.right)
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
@@ -587,7 +585,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
// TODO: can we remove those grdb_ columns now that grouping has been done?
}
let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map { $0.left })
let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map(\.left))
for row in rows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedRows[groupingKey, default: []]
@@ -613,7 +611,7 @@ extension Array where Element == Row {
extension Row {
/// - precondition: Columns all exist in the row.
fileprivate func indexes(ofColumns columns: [String]) -> [Int] {
return columns.map { column -> Int in
columns.map { column -> Int in
guard let index = index(ofColumn: column) else {
fatalError("Column \(column) is not selected")
}
@@ -624,53 +622,42 @@ extension Row {
// MARK: - ColumnAssignment
precedencegroup ColumnAssignment {
associativity: left
assignment: true
lowerThan: AssignmentPrecedence
}
infix operator <- : ColumnAssignment
/// A ColumnAssignment can update rows in the database.
///
/// You create an assignment from a column and an assignment operator, such as
/// `<-` or `+=`:
/// You create an assignment from a column and an assignment method or operator,
/// such as `set(to:)` or `+=`:
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// let assignment = Column("score") <- 0
/// let assignment = Column("score").set(to: 0)
/// try Player.updateAll(db, assignment)
/// }
public struct ColumnAssignment {
var column: ColumnExpression
var value: SQLExpressible?
var value: SQLExpressible
func sql(_ context: inout SQLGenerationContext) -> String {
if let value = value {
return column.expressionSQL(&context, wrappedInParenthesis: false) +
" = " +
value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
} else {
return column.expressionSQL(&context, wrappedInParenthesis: false) +
" = NULL"
}
column.expressionSQL(&context, wrappedInParenthesis: false) +
" = " +
value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
}
}
/// Creates an assignment to a value.
///
/// Column("valid") <- true
/// Column("score") <- 0
/// Column("score") <- nil
/// Column("score") <- Column("score") + Column("bonus")
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.updateAll(db, Column("score") <- 0)
/// }
public func <- (column: ColumnExpression, value: SQLExpressible?) -> ColumnAssignment {
return ColumnAssignment(column: column, value: value)
extension ColumnExpression {
/// Creates an assignment to a value.
///
/// Column("valid").set(to: true)
/// Column("score").set(to: 0)
/// Column("score").set(to: nil)
/// Column("score").set(to: Column("score") + Column("bonus"))
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.updateAll(db, Column("score").set(to: 0))
/// }
public func set(to value: SQLExpressible?) -> ColumnAssignment {
ColumnAssignment(column: self, value: value ?? DatabaseValue.null)
}
}
/// Creates an assignment that adds a value
@@ -683,7 +670,7 @@ public func <- (column: ColumnExpression, value: SQLExpressible?) -> ColumnAssig
/// try Player.updateAll(db, Column("score") += 1)
/// }
public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment {
return column <- column + value
column.set(to: column + value)
}
/// Creates an assignment that subtracts a value
@@ -696,7 +683,7 @@ public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
/// try Player.updateAll(db, Column("score") -= 1)
/// }
public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment {
return column <- column - value
column.set(to: column - value)
}
/// Creates an assignment that multiplies by a value
@@ -709,7 +696,7 @@ public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
/// try Player.updateAll(db, Column("score") *= 2)
/// }
public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment {
return column <- column * value
column.set(to: column * value)
}
/// Creates an assignment that divides by a value
@@ -722,5 +709,5 @@ public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
/// try Player.updateAll(db, Column("score") /= 2)
/// }
public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment {
return column <- column / value
column.set(to: column / value)
}
@@ -45,7 +45,7 @@ extension SelectionRequest {
/// .select(Column("id"))
/// .select(Column("email"))
public func select(_ selection: SQLSelectable...) -> Self {
return select(selection)
select(selection)
}
/// Creates a request which selects *sql*.
@@ -61,7 +61,7 @@ extension SelectionRequest {
/// .select(sql: "id")
/// .select(sql: "email")
public func select(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return select(literal: SQLLiteral(sql: sql, arguments: arguments))
select(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request which selects an SQL *literal*.
@@ -102,7 +102,7 @@ extension SelectionRequest {
/// .select([Column("id"), Column("email")])
/// .annotated(with: Column("name"))
public func annotated(with selection: SQLSelectable...) -> Self {
return annotated(with: selection)
annotated(with: selection)
}
}
@@ -135,7 +135,7 @@ public protocol FilteredRequest {
/// :nodoc:
extension FilteredRequest {
public func expectingSingleResult() -> Self {
return self
self
}
/// Creates a request with the provided *predicate* added to the
@@ -145,7 +145,7 @@ extension FilteredRequest {
/// var request = Player.all()
/// request = request.filter(Column("email") == "arthur@example.com")
public func filter(_ predicate: SQLExpressible) -> Self {
return filter { _ in predicate }
filter { _ in predicate }
}
/// Creates a request with the provided *predicate* added to the
@@ -155,7 +155,7 @@ extension FilteredRequest {
/// var request = Player.all()
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
public func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return filter(literal: SQLLiteral(sql: sql, arguments: arguments))
filter(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *predicate* added to the
@@ -183,7 +183,7 @@ extension FilteredRequest {
/// var request = Player.all()
/// request = request.none()
public func none() -> Self {
return filter(false)
filter(false)
}
}
@@ -353,17 +353,17 @@ public protocol AggregatingRequest {
extension AggregatingRequest {
/// Creates a request grouped according to *expressions*.
public func group(_ expressions: [SQLExpressible]) -> Self {
return group { _ in expressions }
group { _ in expressions }
}
/// Creates a request grouped according to *expressions*.
public func group(_ expressions: SQLExpressible...) -> Self {
return group(expressions)
group(expressions)
}
/// Creates a request with a new grouping.
public func group(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return group(literal: SQLLiteral(sql: sql, arguments: arguments))
group(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with a new grouping.
@@ -375,7 +375,7 @@ extension AggregatingRequest {
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return having(literal: SQLLiteral(sql: sql, arguments: arguments))
having(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *sql* added to the
@@ -446,7 +446,7 @@ extension OrderedRequest {
/// .reversed()
/// .order(Column("name"))
public func order(_ orderings: SQLOrderingTerm...) -> Self {
return order { _ in orderings }
order { _ in orderings }
}
/// Creates a request with the provided *orderings*.
@@ -463,7 +463,7 @@ extension OrderedRequest {
/// .reversed()
/// .order(Column("name"))
public func order(_ orderings: [SQLOrderingTerm]) -> Self {
return order { _ in orderings }
order { _ in orderings }
}
/// Creates a request sorted according to *sql*.
@@ -479,7 +479,7 @@ extension OrderedRequest {
/// .order(sql: "email")
/// .order(sql: "name")
public func order(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return order(literal: SQLLiteral(sql: sql, arguments: arguments))
order(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request sorted according to an SQL *literal*.
@@ -556,35 +556,35 @@ public protocol JoinableRequest: _JoinableRequest {
extension JoinableRequest {
/// Creates a request that prefetches an association.
public func including<A: AssociationToMany>(all association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return _including(all: association.sqlAssociation)
_including(all: association.sqlAssociation)
}
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned request does not
/// require that the associated database table contains a matching row.
public func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return _including(optional: association.sqlAssociation)
_including(optional: association.sqlAssociation)
}
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned request requires
/// that the associated database table contains a matching row.
public func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return _including(required: association.sqlAssociation)
_including(required: association.sqlAssociation)
}
/// Creates a request that joins an association. The columns of the
/// associated record are not selected. The returned request does not
/// require that the associated database table contains a matching row.
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return _joining(optional: association.sqlAssociation)
_joining(optional: association.sqlAssociation)
}
/// Creates a request that joins an association. The columns of the
/// associated record are not selected. The returned request requires
/// that the associated database table contains a matching row.
public func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return _joining(required: association.sqlAssociation)
_joining(required: association.sqlAssociation)
}
}
+3 -5
View File
@@ -28,13 +28,13 @@ extension ColumnExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
return name.quotedDatabaseIdentifier
name.quotedDatabaseIdentifier
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return QualifiedColumn(name, alias: alias)
QualifiedColumn(name, alias: alias)
}
}
@@ -94,7 +94,5 @@ struct QualifiedColumn: ColumnExpression {
/// }
/// }
extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String {
public var name: String {
return rawValue
}
public var name: String { rawValue }
}
@@ -37,13 +37,13 @@ struct DatabasePromise<T> {
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
return DatabasePromise<U> { db in
DatabasePromise<U> { db in
try transform(self.resolve(db))
}
}
func flatMap<U>(_ transform: @escaping (T) -> DatabasePromise<U>) -> DatabasePromise<U> {
return DatabasePromise<U> { db in
DatabasePromise<U> { db in
try transform(self.resolve(db)).resolve(db)
}
}
+44 -27
View File
@@ -54,17 +54,15 @@
public /* TODO: internal */ struct SQLAssociation {
// All steps, from pivot to destination. Never empty.
private(set) var steps: [SQLAssociationStep]
var keyPath: [String] {
return steps.map { $0.keyName }
}
var keyPath: [String] { steps.map(\.keyName) }
var destination: SQLAssociationStep {
get { return steps[steps.count - 1] }
get { steps[steps.count - 1] }
set { steps[steps.count - 1] = newValue }
}
var pivot: SQLAssociationStep {
get { return steps[0] }
get { steps[0] }
set { steps[0] = newValue }
}
@@ -88,13 +86,24 @@ public /* TODO: internal */ struct SQLAssociation {
}
/// Changes the destination key
func forDestinationKey(_ key: SQLAssociationKey) -> SQLAssociation {
return with(\.destination.key, key)
func forDestinationKey(_ key: SQLAssociationKey) -> Self {
with(\.destination.key, key)
}
/// Returns a new association
func through(_ other: SQLAssociation) -> SQLAssociation {
return SQLAssociation(steps: other.steps + steps)
func through(_ other: SQLAssociation) -> Self {
SQLAssociation(steps: other.steps + steps)
}
func associationForFirst() -> Self {
SQLAssociation(steps: steps.map { step in
switch step.cardinality {
case .toOne:
return step
case .toMany:
return step.map(\.relation) { $0.with(\.firstOnly, true) }
}
})
}
/// Given an origin alias and rows, returns the destination of the
@@ -140,13 +149,10 @@ public /* TODO: internal */ struct SQLAssociation {
func destinationRelation(fromOriginRows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation {
// Filter the pivot
let pivot = self.pivot
let pivotAlias = TableAlias()
let filteredPivotRelation = pivot.relation
.qualified(with: pivotAlias)
.filter({ db in
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
try pivot.condition.filteringExpression(db, leftRows: originRows(db), rightAlias: pivotAlias)
})
let filteredPivotRelation = pivot.relation.filter({ db in
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
try pivot.condition.filteringExpression(db, leftRows: originRows(db))
})
if steps.count == 1 {
// This is a direct join from origin to destination, without
@@ -180,10 +186,15 @@ public /* TODO: internal */ struct SQLAssociation {
// children are useless:
let relation = step.relation
.selectOnly([])
.filteringChildren { $0.kind.cardinality == .toOne }
.filteringChildren({
switch $0.kind {
case .allPrefetched, .allNotPrefetched: return false
case .oneRequired, .oneOptional: return true
}
})
// Don't interfere with user-defined keys that could be added later
let key = step.key.map(\.baseName, { "grdb_\($0)" })
let key = step.key.map(\.baseName) { "grdb_\($0)" }
return SQLAssociationStep(
key: key,
@@ -197,17 +208,24 @@ public /* TODO: internal */ struct SQLAssociation {
}
}
extension SQLAssociation: KeyPathRefining { }
extension SQLAssociation: Refinable { }
struct SQLAssociationStep: KeyPathRefining {
struct SQLAssociationStep: Refinable {
var key: SQLAssociationKey
var condition: SQLAssociationCondition
var relation: SQLRelation
var cardinality: SQLAssociationCardinality
var keyName: String {
return key.name(for: cardinality)
var isSingular: Bool {
switch cardinality {
case .toOne:
return true
case .toMany:
return relation.firstOnly
}
}
var keyName: String { key.name(singular: isSingular) }
}
enum SQLAssociationCardinality {
@@ -260,7 +278,7 @@ enum SQLAssociationCardinality {
///
/// The SQLAssociationKey type aims at providing the necessary support for
/// those various inflections.
enum SQLAssociationKey: KeyPathRefining {
enum SQLAssociationKey: Refinable {
/// A key that is inflected in singular and plural contexts.
///
/// For example:
@@ -323,11 +341,10 @@ enum SQLAssociationKey: KeyPathRefining {
}
}
func name(for cardinality: SQLAssociationCardinality) -> String {
switch cardinality {
case .toOne:
func name(singular: Bool) -> String {
if singular {
return singularizedName
case .toMany:
} else {
return pluralizedName
}
}
Loaded 100 of 415 files, more files were not shown because too many files have changed in this diff. Show more