Compare commits

...
1691 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é c493b17232 Merge branch 'development' 2020-04-13 11:52:21 +02:00
Gwendal Roué 94d34a744d v4.12.2 2020-04-13 11:51:28 +02:00
Gwendal Roué 0cda88bd28 Merge pull request #757 from groue/dev/lazy-inflections
Don't load association inflections unless necessary
2020-04-13 11:47:20 +02:00
Gwendal Roué c62ccf1de7 Make sure Inflections.default is lazily loaded, even in optimized release builds
This commit addresses #755
2020-04-13 11:31:03 +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é ed15498871 Merge branch 'master' into development 2020-04-06 20:16:19 +02:00
Gwendal Roué 97a05b97d9 [skip travis] Fix typo 2020-04-06 19:56:32 +02:00
Gwendal Roué 0b69aa82fd [skip travis] Add a Brag Document 2020-04-06 19:54:47 +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é c01c4d6de5 Looks like jazzy and Xcode 11.4 go well together 2020-03-29 18:49:54 +02:00
Gwendal Roué f4c763dc31 Merge branch 'development' 2020-03-29 17:44:31 +02:00
Gwendal Roué 66989f2ff7 v4.12.1 2020-03-29 17:43:49 +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é ba0c771346 Merge pull request #744 from groue/dev/fix-741
Fix DatabaseMigrator deadlock with serial target queues
2020-03-29 16:37:55 +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é 97a84c6470 Fix failing test for #741 2020-03-29 12:09:58 +02:00
Gwendal Roué 70c6f3ec44 Failing test for #741 2020-03-29 12:09: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é e831c64e93 Merge branch 'development' 2020-03-21 12:54:52 +01:00
Gwendal Roué 50f64dc45d v4.12.0 2020-03-21 12:54:30 +01:00
Gwendal Roué 24872373c4 TODO 2020-03-21 12:26:35 +01:00
Gwendal Roué f04efea09c CHANGELOG 2020-03-18 20:47:04 +01:00
Gwendal Roué cda254bb2d Update documentation for eraseDatabaseOnSchemaChange 2020-03-18 20:43:09 +01:00
Gwendal Roué c1d1797576 Address #725 2020-03-18 20:36:56 +01:00
Gwendal Roué a0faf6aa68 Support for nil assignment 2020-03-18 19:34:43 +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é 84eef52cb0 Merge branch 'master' into development 2020-03-11 22:44:05 +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é 6a582869c6 Merge pull request #730 from jackalcooper/patch-1
fix typo
2020-03-11 12:45:58 +01:00
Shenghang Tsai 813f28e5da fix typo 2020-03-11 19:35:48 +08: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é 3973b66ab3 Fix and test throwingFirstError 2020-03-10 09:16:24 +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é 435f5ff559 TODO: fix throwingFirstError 2020-03-10 07:41:15 +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
Gwendal Roué f6e6758525 Merge branch 'master' into development 2020-03-07 15:13:33 +01:00
Gwendal Roué 039dd37759 [skip travis] Enhancements to WhyAdoptGRDB.md 2020-03-07 15:13:14 +01:00
Gwendal Roué e9dd8b2b09 Enhance DatabaseMigrator querying methods
// New
dbQueue.read(migrator.hasCompletedMigrations)
dbQueue.read(migrator.completedMigrations).contains("v2")
dbQueue.read(migrator.completedMigrations).last == "v2"
dbQueue.read(migrator.appliedMigrations)

// Deprecated
migrator.hasCompletedMigrations(in: dbQueue)
migrator.hasCompletedMigrations(in: dbQueue, through: "v2")
migrator.lastCompletedMigration(in: dbQueue) == "v2"
migrator.appliedMigrations(in: dbQueue)
2020-03-07 13:59:46 +01:00
Gwendal Roué ee64f8ff9d Rename statement argument methods 2020-03-04 08:43:31 +01:00
Gwendal Roué db546bf478 Merge branch 'development' 2020-03-02 08:01:55 +01:00
Gwendal Roué 5a7c6fb33f v4.11.0 2020-03-02 07:59:48 +01:00
Gwendal Roué fa7ae31894 TODO 2020-03-02 07:53:25 +01:00
Gwendal Roué 48097ba7e7 Update thank you notice 2020-03-01 18:42:05 +01:00
Gwendal Roué 7c684d06c1 Simplify schema cache management
We don't need EmptyDatabaseSchemaCache. It does not help unsafe reads to work better if concurrent writes modify the schema anyway.
2020-03-01 15:51:37 +01:00
Gwendal Roué c8321201d8 Merge pull request #713 from groue/dev/barrierMigrations
Enhance DatabaseMigrator isolation
2020-03-01 15:41:27 +01:00
Gwendal Roué ea421865aa Improve barrierWriteWithoutTransaction documentation 2020-03-01 11:34:58 +01:00
Gwendal Roué f5019eeb60 Merge branch 'development' into dev/barrierMigrations
# Conflicts:
#	GRDB/Migration/DatabaseMigrator.swift
2020-03-01 09:13:45 +01:00
Gwendal Roué 62222f441d Merge pull request #710 from groue/dev/unappliedMigrations
Check if all migrations have been applied
2020-03-01 09:00:20 +01:00
Gwendal Roué 0e43f1b95a appliedIdentifiers always filters out unknown migrations 2020-03-01 08:58:50 +01:00
Gwendal Roué 50cd4418d2 CHANGELOG 2020-02-29 17:32:15 +01:00
Gwendal Roué e1b14d4ee5 DatabaseMigrator uses barrierWriteWithoutTransaction
This prevents concurrent reads from reading right in between two migration transactions
2020-02-29 17:26:59 +01:00
Gwendal Roué ce0df653f4 Expose Database.erase() 2020-02-29 17:19:08 +01:00
Gwendal Roué 11f8807545 Make barrierWriteWithoutTransaction a requirement of DatabaseWriter 2020-02-29 16:01:45 +01:00
Gwendal Roué 7af846c87f Rename new DatabaseMigrator methods 2020-02-29 15:07:36 +01:00
Gwendal Roué 9f46f34d16 Merge branch 'development' into dev/unappliedMigrations
# Conflicts:
#	CHANGELOG.md
2020-02-29 14:46:50 +01:00
Gwendal Roué e62df26a53 Disable flaky testDatabasePoolReleaseMemoryClosesReaderConnections
See https://github.com/groue/GRDB.swift/issues/489
2020-02-29 14:45:06 +01:00
Gwendal Roué b71de1559a Disable flaky testCachedStatementsAreNotShared
See https://github.com/groue/GRDB.swift/issues/679
2020-02-29 14:43:17 +01:00
Gwendal Roué c2c587752c Disable flaky testBusyModeTimeoutTooShort
It just ruins Travis builds :-(
2020-02-29 14:41:46 +01:00
Gwendal Roué fd029ff230 Merge pull request #712 from pakko972/automatic-ios-memory-management
Automatic ios memory management
2020-02-29 14:38:00 +01:00
Gwendal Roué c534193f5c CHANGELOG 2020-02-29 14:36:07 +01:00
Gwendal Roué 7b29156664 Fix typo and improve wording 2020-02-29 14:33:02 +01:00
Gwendal Roué 9ed8cb3eff Fix Swiftlint warnings 2020-02-29 14:30:05 +01:00
Gwendal Roué a7d02b90a5 Update license year 2020-02-29 14:09:29 +01:00
Gwendal Roué 522639282d Update JSONSynchronization playground 2020-02-29 14:03:12 +01:00
Pakkito eb98f50891 Avoid breaking changes
- Deprecate setupMemoryManagement(application:)
- UIApplication is not available on watchOS, so instead of checking against `#if canImport(UIKit)` we use `#if os(iOS)`

Signed-off-by: Pakkito <pe@pierlis.com>
2020-02-28 18:00:16 +01:00
Pakkito f07735f05f Add support for xcode 11.4
Signed-off-by: Pakkito <pe@pierlis.com>
2020-02-28 17:21:53 +01:00
Pakkito 32675b38f1 Automatically setup memory management when UIKit is available
Signed-off-by: Pakkito <pe@pierlis.com>
2020-02-28 17:21:27 +01:00
Gwendal Roué d35d6fc2f8 Rename isMigrated(in:upTo:) to isMigrated(in:beyond:), introduce lastAppliedMigration(in:) 2020-02-28 14:27:52 +01:00
Gwendal Roué fa26faa6fd CHANGELOG 2020-02-28 07:42:38 +01:00
Gwendal Roué 91a3557281 Rename hasUnappliedMigrations to isMigrated 2020-02-28 07:40:19 +01:00
Gwendal Roué f09e0b5ed2 CHANGELOG 2020-02-27 21:19:57 +01:00
Gwendal Roué 0580705b1e Enhance App Group Container documentation with database schema check 2020-02-27 21:10:35 +01:00
Gwendal Roué 0c7e14eb9b Documentation for DatabaseMigrator.hasUnappliedMigrations 2020-02-27 21:02:17 +01:00
Gwendal Roué 92e8ef9b87 More DatabaseMigrator tests 2020-02-27 21:01:56 +01:00
Gwendal Roué 692af926be Tests for DatabaseMigrator.hasUnappliedMigrations 2020-02-27 20:51:44 +01:00
Gwendal Roué a17669b082 DatabaseMigrator.hasUnappliedMigrations 2020-02-27 20:50:25 +01:00
Gwendal Roué 2ff8c66b9e TODO 2020-02-27 19:29:21 +01:00
Gwendal Roué be53b0d403 Merge pull request #709 from groue/dev/migration
Simplify DatabaseMigrator API
2020-02-27 19:28:12 +01:00
Gwendal Roué ba02ba4237 CHANGELOG 2020-02-27 19:25:55 +01:00
Gwendal Roué 0d2ede4440 Document that migrations run with deferred foreign key checks 2020-02-27 08:43:51 +01:00
Gwendal Roué bf89883ff5 Import SQLite C functions for SPM 2020-02-26 22:26:29 +01:00
Gwendal Roué efcc3a3dfb Merge branch 'development' into dev/migration
# Conflicts:
#	CHANGELOG.md
2020-02-26 19:31:38 +01:00
Gwendal Roué fefeb1e9e2 Merge pull request #706 from groue/dev/690-improvement
Enhance SQLLiteral and SQL interpolation again
2020-02-26 19:28:39 +01:00
Gwendal Roué f12436e55b CHANGELOG 2020-02-26 14:09:24 +01:00
Gwendal Roué 98c4356638 Cleanup 2020-02-26 14:07:38 +01:00
Gwendal Roué e5c4fb7e30 Update DatabaseMigrator documentation 2020-02-26 13:59:04 +01:00
Gwendal Roué 4f9878a1da Update tests for the deprecated registerMigrationWithDeferredForeignKeyCheck method 2020-02-26 13:57:49 +01:00
Gwendal Roué 8557d113a3 Deprecate registerMigrationWithDeferredForeignKeyCheck
This method is now equivalent to registerMigration, starting SQLite 3.7.16
2020-02-26 13:57:14 +01:00
Gwendal Roué 9400e7f5d5 Fix tests for Xcode 10.3 2020-02-26 08:17:48 +01:00
Gwendal Roué 193509db58 Merge pull request #707 from haikusw/pr_docs_typos_fixes
Docs: Fix a collection of typos
2020-02-26 08:05:22 +01:00
Tyler Morrison d7ce175b8e Documentation: Fixes for some typos 2020-02-25 14:43:39 -08:00
Gwendal Roué 0a8001a128 CHANGELOG 2020-02-25 22:25:36 +01:00
Gwendal Roué b46a8c897a Update SQLLiteral documentation 2020-02-25 22:21:32 +01:00
Gwendal Roué bad8d85729 Add test for legacy literal expression function 2020-02-25 22:18:16 +01:00
Gwendal Roué eb6f6e57ff Fix failing test for literal expression function 2020-02-25 22:13:17 +01:00
Gwendal Roué cc495e3fd5 Failing test for literal expression function 2020-02-25 22:11:18 +01:00
Gwendal Roué d190a26737 More precise documentation vocabulary 2020-02-25 15:05:11 +01:00
Gwendal Roué 7ee4e269c3 Fix sample code 2020-02-25 15:02:18 +01:00
Gwendal Roué f7465896fa Enhance documentation for features brought by #690 2020-02-25 14:59:11 +01:00
Gwendal Roué 4c8574aa4c Merge branch 'development' 2020-02-23 14:09:57 +01:00
Gwendal Roué 7475c25fa7 v4.10.0 2020-02-23 13:17:32 +01:00
Gwendal Roué 3379bf3b08 Merge pull request #690 from groue/dev/qualifiedSQLLiteral
Enhance SQLLiteral and SQL interpolation
2020-02-15 09:34:23 +01:00
Gwendal Roué 7af3f48150 TODO 2020-02-15 07:04:50 +01:00
Gwendal Roué 1b8511ab51 Documentation 2020-02-14 12:59:06 +01:00
Gwendal Roué 355ae49bc2 CHANGELOG 2020-02-14 12:46:01 +01:00
Gwendal Roué 8c3274bd3c Cleanup 2020-02-14 12:36:36 +01:00
Gwendal Roué 591384576f SQLOrderingLiteral (and prevent reversing of requests ordered by literal) 2020-02-14 12:31:54 +01:00
Gwendal Roué cdda2852d3 Merge branch 'development' into dev/qualifiedSQLLiteral 2020-02-14 11:43:15 +01:00
Gwendal Roué 03992ab45c CHANGELOG 2020-02-14 11:41:37 +01:00
Gwendal Roué 1f4b374bce Documentation for #689 2020-02-14 11:40:17 +01:00
Gwendal Roué a5b2757128 Merge pull request #689 from groue/rename-column
Add support for renaming columns within a table
2020-02-14 11:25:42 +01:00
Gwendal Roué b961962f93 Cleanup 2020-01-25 16:29:04 +01:00
Gwendal Roué c64b2d1032 Cleanup 2020-01-25 16:18:12 +01:00
Gwendal Roué 3ccfcb61ce Cleanup SQLLiteral elements 2020-01-25 16:11:17 +01:00
Gwendal Roué e4c6029e72 Cleanup internal APIs 2020-01-25 14:37:32 +01:00
Gwendal Roué d448bd8bd5 Test SQLLiteral.mapSQL qualification 2020-01-25 14:32:13 +01:00
Gwendal Roué e999ab5ecb Don't deprecate SQLLiteral.mapSQL, after all 2020-01-25 13:46:00 +01:00
Gwendal Roué db8585aa85 Test for SQLLiteral(expression) 2020-01-25 12:34:22 +01:00
Gwendal Roué e2545b3427 Test for more complex SQLLiteral generation 2020-01-25 12:15:14 +01:00
gjeck 38a161f92b Fix imports for SPM tests 2020-01-24 10:53:34 -08:00
gjeck d14ac3e8d3 Resolve test issues with SQLCipher
Note: SQLCipher3 will have the new column rename method exposed, but it
will throw an error at runtime if used.
2020-01-24 09:22:43 -08:00
gjeck 09087bdbf9 Adjust available checks 2020-01-24 08:46:55 -08:00
gjeck 538252a4bf Allow column rename on custom sqlite target 2020-01-24 08:46:55 -08:00
gjeck 371e8f0dbe Add support for renaming columns within a table
SQLite introduced enhancements to the `ALTER TABLE` command in 3.25.0.
iOS 13.0+, macOS 10.15+, tvOS 13.0+, and watchOS 6.0+ have a SQLite
library bundled higher than 3.25.0.

For more information see https://www.sqlite.org/lang_altertable.html
2020-01-24 08:46:55 -08:00
Gwendal Roué b8c5af5cef Fix availability test 2020-01-24 09:03:06 +01:00
Gwendal Roué ddd22a1dfb Restore Swift 4.2 by default 2020-01-24 09:00:51 +01:00
Gwendal Roué 2d3a9991d4 Test documented use case 2020-01-24 08:55:55 +01:00
Gwendal Roué 7f513cbc1d SQLLiteral cleanup 2020-01-24 08:55:55 +01:00
Gwendal Roué 812f30fb75 Remove SQLLiteral.generate() 2020-01-24 08:55:55 +01:00
Gwendal Roué 86e32cdc23 Cleanup SQLGenerationContext 2020-01-24 08:55:55 +01:00
Gwendal Roué 554cbaa307 Stop using SQLExpression.sqlLiteral 2020-01-24 08:55:55 +01:00
Gwendal Roué 6a0cc838da Deprecate SQLLiteral.mapSQL and SQLExpression.sqlLiteral 2020-01-24 08:55:55 +01:00
Gwendal Roué 4811bc3c5b Test SQLLiteral qualification 2020-01-24 08:55:55 +01:00
Gwendal Roué 65c94590eb Make SQLLiteral able to be qualified with a table alias 2020-01-24 08:55:55 +01:00
Gwendal Roué 5e67ca5566 Deprecate SQLExpressionLiteral, hide SQLSelectionLiteral, introduce SQLLiteral.sqlExpression and .sqlSelectable 2020-01-24 08:55:55 +01:00
Gwendal Roué d7ef314a15 SQLLiteral is now a promise that needs an SQLGenerationContext 2020-01-24 08:55:55 +01:00
Gwendal Roué a3c43efb85 Fix KeyPathRefining for Xcode 10.0 2020-01-24 07:50:12 +01:00
Gwendal Roué 9dcd0b8f42 Fix KeyPathRefining for compiler(<5.1) 2020-01-24 07:45:20 +01:00
Gwendal Roué 349e34b1c1 Internal API experiment: KeyPathRefining 2020-01-21 19:37:19 +01:00
Gwendal Roué 66bce33a36 SPM installation technique: warn against #642 2020-01-19 12:27:30 +01:00
Gwendal Roué f67232b80f Merge branch 'development' 2020-01-17 07:41:27 +01:00
Gwendal Roué 6b32c3aeec v4.9.0 2020-01-17 07:40:42 +01:00
Gwendal Roué f3bc08160d Merge pull request #683 from groue/dev/concat
String concatenation
2020-01-17 07:34:44 +01:00
Gwendal Roué 1cca8a2303 Merge branch 'development' into dev/concat
# Conflicts:
#	CHANGELOG.md
2020-01-16 20:04:38 +01:00
Gwendal Roué ac215430c2 CHANGELOG and thank you notice 2020-01-16 19:48:29 +01:00
Gwendal Roué 7f8a088306 Merge pull request #685 from gjeck/defaultDatabaseTableName
Add cache for TableRecord.defaultDatabaseTableName
2020-01-16 19:42:12 +01:00
gjeck 2717b52e97 Add cache for TableRecord.defaultDatabaseTableName
Resolves cpu/memory impact from repeated calls by cacheing the name in a
private global NSCache.
2020-01-16 09:59:18 -08:00
Gwendal Roué 25cf030498 CHANGELOG 2020-01-16 18:51:47 +01:00
Gwendal Roué 4bfab90750 Restore and deprecate SQLLogicalBinaryOperator 2020-01-16 18:50:48 +01:00
Gwendal Roué 95ddae7968 More tests for associative operators 2020-01-16 09:08:30 +01:00
Gwendal Roué 62fad30af5 Documentation associative operator joining for add and multiply operations 2020-01-16 08:57:07 +01:00
Gwendal Roué c9373929ca Documentation for the || string concatenation operator 2020-01-16 08:50:40 +01:00
Gwendal Roué 01b47a833a Introduce the || string concatenation operator 2020-01-16 08:38:17 +01:00
Gwendal Roué a398c6dc99 Flattten stricly associative operators 2020-01-16 08:17:11 +01:00
Gwendal Roué 32a40b18fd Introduce associative binary operators 2020-01-16 08:01:48 +01:00
Gwendal Roué c7fcde83cf Merge branch 'development' 2020-01-12 12:53:40 +01:00
Gwendal Roué a9cd4faff0 v4.8.1 2020-01-12 12:53:18 +01:00
Gwendal Roué ddccbaacdb Merge pull request #677 from groue/dev/fixAssociationFiltering
Fix associations altered by another association
2020-01-12 09:52:51 +01:00
Gwendal Roué 6a7ecb2c63 CHANGELOG 2020-01-11 20:43:43 +01:00
Gwendal Roué 0b07a6a696 Cleanup 2020-01-11 20:43:37 +01:00
Gwendal Roué 58a36ec509 Add including(all:) test fixed by ebdfa9e52a 2020-01-11 19:00:57 +01:00
Gwendal Roué ebdfa9e52a Fix failiing tests for children relations 2020-01-11 18:36:36 +01:00
Gwendal Roué 4c145b11a5 OrderedDictionary.filter(_:) 2020-01-11 18:12:30 +01:00
Gwendal Roué c14739cb4a Failiing tests for children relations 2020-01-11 18:11:05 +01:00
Gwendal Roué 5b841cf4cb Cleanup 2020-01-09 08:24:00 +01:00
Gwendal Roué 8fa17c578c Fix typo 2020-01-08 08:46:17 +01:00
Gwendal Roué 183612a4e3 Merge branch 'development' 2020-01-08 08:25:30 +01:00
Gwendal Roué e3fbfe6541 v4.8.0 2020-01-08 07:49:12 +01:00
Gwendal Roué 69b9d04aad Less TODO 2020-01-07 08:01:25 +01:00
Gwendal Roué ffd1222990 Fix comment 2020-01-06 09:14:57 +01:00
Gwendal Roué 07266d0b31 Remove useless captures 2020-01-06 09:12:55 +01:00
Gwendal Roué eb8ec327a8 Cleanup 2020-01-06 09:09:27 +01:00
Gwendal Roué f79b60083e Remove TODO and document why 2020-01-06 08:36:53 +01:00
Gwendal Roué fc50302e14 Remove unwise TODO 2020-01-06 08:14:46 +01:00
Gwendal Roué 4896741706 Remove code smell 2020-01-06 08:13:32 +01:00
Gwendal Roué fd7783c39d Fix uses of throwingFirstError(execute:finally:) 2020-01-06 08:12:49 +01:00
Gwendal Roué c60a945610 Fix SQL 2020-01-05 20:36:49 +01:00
Gwendal Roué ef9bab627d Fix markdown 2020-01-05 14:28:41 +01:00
Gwendal Roué 9ca2a2e782 Add context to the "Refining Association Requests" chapter 2020-01-05 14:27:17 +01:00
Gwendal Roué 3613b6ed45 Add missing documentation for annotated(with: expression) 2020-01-05 13:56:25 +01:00
Gwendal Roué adc7079943 Cleanup 2020-01-05 13:55:10 +01:00
Gwendal Roué cd8fbbe8f2 Add a test for foreign column annotation 2020-01-05 13:45:23 +01:00
Gwendal Roué e5726f3993 throwingFirstError(execute:finally:) 2020-01-05 13:30:12 +01:00
Gwendal Roué 14c3c7865e Move association initialization where they belong 2020-01-03 08:27:15 +01:00
Gwendal Roué 9dd5fd198b Fix documentation bug - #672 2020-01-03 08:09:54 +01:00
Gwendal Roué 2595729c8c Documentation 2020-01-03 08:04:22 +01:00
Gwendal Roué 6b6a422ead Travis: only build master and development branches 2019-12-30 18:26:17 +01:00
Gwendal Roué 72a4e2073f Update make doc so that it works with Xcode 11 2019-12-30 18:23:26 +01:00
Gwendal Roué 1fa93abb5b Merge pull request #676 from groue/dev/moreDeleteAndUpdate
More batch delete and update
2019-12-30 13:37:44 +01:00
Gwendal Roué 81c763750f CHANGELOG 2019-12-29 19:14:28 +01:00
Gwendal Roué 944f4309a8 Cleanup 2019-12-29 19:06:29 +01:00
Gwendal Roué b302051f87 Cleanup 2019-12-29 18:46:06 +01:00
Gwendal Roué 070f85b541 More tests for batch update and delete 2019-12-29 18:26:47 +01:00
Gwendal Roué 71d97b04a5 Move code 2019-12-29 18:26:27 +01:00
Gwendal Roué b1edf78f13 Add missing reference to updateAll 2019-12-29 18:26:05 +01:00
Gwendal Roué fa5198354a Fix failing tests for deleteAll and updateAll for grouped and joined queries 2019-12-29 17:50:53 +01:00
Gwendal Roué e8803804ec Failing tests for deleteAll and updateAll for grouped and joined queries 2019-12-29 17:50:47 +01:00
Gwendal Roué baa9695678 SQLQueryGenerator.grouping(_:) 2019-12-29 17:18:17 +01:00
Gwendal Roué a42a5cc2ca SQLQualifiedRelation.selectOnly(_:) 2019-12-29 16:57:26 +01:00
Gwendal Roué db7edd389f rowid is a unique key 2019-12-29 16:40:57 +01:00
Gwendal Roué 985794e733 Merge pull request #670 from groue/development
GRDB 4.7.0
2019-12-18 08:01:17 +01:00
Gwendal Roué 5d0e37e2cc v4.7.0 2019-12-17 18:59:12 +01:00
Gwendal Roué e69fb4a0db Remove unused code 2019-12-17 18:58:51 +01:00
Gwendal Roué 8512607fb6 Merge pull request #668 from groue/dev/suspend
Database Suspension
2019-12-15 18:18:58 +01:00
Gwendal Roué 299bfef7b5 Busy timeouts are really weird 2019-12-15 13:17:47 +01:00
Gwendal Roué a7f99b83f9 fix busy timeout tests on macOS 2019-12-15 10:54:13 +01:00
Gwendal Roué e7f1153c85 [skip travis] FUNDING.yml 2019-12-15 10:44:45 +01:00
Gwendal Roué f873bb1cfb fix busy timeout tests on Xcode 10.3 2019-12-15 10:00:57 +01:00
Gwendal Roué aadc58d349 [skip travis] documentation tweak 2019-12-14 19:49:26 +01:00
Gwendal Roué 5e75f0e0aa [skip travis] remove outdated documentation 2019-12-14 19:45:33 +01:00
Gwendal Roué a450df823b [skip travis] fix typo 2019-12-14 19:44:16 +01:00
Gwendal Roué af305afc2a LastUpgradeVersion 1130 2019-12-14 18:33:00 +01:00
Gwendal Roué 3d15751e44 Don't code sign performance tests 2019-12-14 18:28:28 +01:00
Gwendal Roué a09b8522ad Update make test_performance 2019-12-13 09:06:55 +01:00
Gwendal Roué 16186b6ac7 Extract performance tests to their own project 2019-12-13 09:02:47 +01:00
Gwendal Roué 1c2bd4134c Upgrade performance tests for Xcode 11.3 2019-12-13 08:39:24 +01:00
Gwendal Roué c4b6fbec76 Interrupt documentation 2019-12-13 08:24:42 +01:00
Gwendal Roué 974055b90b Suspension is experimental 2019-12-13 08:24:27 +01:00
Gwendal Roué 4bf5724543 Can't issue ROLLBACK on suspension
This is because this would allow a database modification to run in an aborted transaction
2019-12-13 08:14:49 +01:00
Gwendal Roué 19ba7d67e8 Suspension is fully experimental 2019-12-12 19:26:08 +01:00
Gwendal Roué 34eff46e56 Sharing a Datatase in an App Group Container 2019-12-12 19:23:41 +01:00
Gwendal Roué 0529869617 Fix busyMode tests for encrypted databases 2019-12-12 18:57:37 +01:00
Gwendal Roué 81ce5c9134 CHANGELOG 2019-12-12 08:53:16 +01:00
Gwendal Roué 6656f72782 Rename "lock prevention" to "suspension" 2019-12-12 08:47:49 +01:00
Gwendal Roué dfb013bf78 #664 is not quite easy to fix with optionals :-/ 2019-12-09 19:54:06 +01:00
Gwendal Roué 2b37e28691 remove debugging code 2019-12-09 19:20:02 +01:00
Gwendal Roué 69fc6a0496 Test that RowDecoder won't decode several sub-records from the root row - addresses #664 2019-12-09 19:09:27 +01:00
Gwendal Roué daba7e13fc Merge branch 'master' into development 2019-12-09 08:08:36 +01:00
Gwendal Roué 580fa6a554 Merge pull request #662 from groue/dev/SQLite3.30.1
Upgrade custom SQLite builds to version 3.30.1
2019-12-09 08:06:45 +01:00
Gwendal Roué e90ef7aa6e Fix acceptsDoubleQuotedStringLiterals tests 2019-12-08 18:07:41 +01:00
Gwendal Roué d1e1dcd097 Fix test for SPM 2019-12-08 08:55:05 +01:00
Gwendal Roué 16354be1c5 Merge pull request #656 from groue/dev/request-selection-inference
Type inference of selected columns
2019-12-07 19:36:08 +01:00
Gwendal Roué a0fddfe7ec Documentation 2019-12-07 13:47:00 +01:00
Gwendal Roué d6a459ad78 CHANGELOG 2019-12-07 13:42:52 +01:00
Gwendal Roué 7b4dc14485 [breaking] disable double-quoted string literals by default 2019-12-07 13:32:33 +01:00
Gwendal Roué 7208f53176 Support for NULLS FIRST and NULLS LAST 2019-12-07 12:31:58 +01:00
Gwendal Roué 2c9bef6440 "*" is no longer a valid FTS5 pattern 2019-12-07 12:07:06 +01:00
Gwendal Roué 820772fc6d SQlite 3.30.1 2019-12-07 12:01:51 +01:00
Gwendal Roué 710cea5437 CHANGELOG 2019-12-07 11:56:37 +01:00
Gwendal Roué b6ede15b18 Static tests for QueryInterfaceRequest type inference 2019-12-07 10:37:02 +01:00
Gwendal Roué aa536813d9 Add request type inference - cc @pakko972 2019-12-07 10:24:15 +01:00
Gwendal Roué 2b9932c1ee [skip travis] demo app icon, dark mode, content category adjustment 2019-12-07 10:03:53 +01:00
Gwendal Roué 2efb4e0d7d [skip travis] logo 2019-12-06 19:57:12 +01:00
Gwendal Roué 64935e78e3 Update TODO.md 2019-12-04 11:53:43 +01:00
Gwendal Roué 831ded3ec2 beginReadOnly only increments _readOnlyDepth if it succeeds 2019-12-03 19:18:05 +01:00
Gwendal Roué bbf8e773f8 Remove useless code 2019-12-03 19:17:35 +01:00
Gwendal Roué e4073cbe9a Test for stopPreventingLock 2019-12-03 19:12:41 +01:00
Gwendal Roué 6d0bdd3a4d CHANGELOG 2019-12-03 19:09:35 +01:00
Gwendal Roué 698dc262e0 Merge pull request #660 from groue/dev/startPreventingExclusiveLock
Database Lock Prevention
2019-12-03 19:08:09 +01:00
Gwendal Roué 41cd4c2140 Check for aborted transactions before checking for lock prevention 2019-12-03 09:01:03 +01:00
Gwendal Roué 12106387d1 Cleanup 2019-12-03 08:51:10 +01:00
Gwendal Roué 17864d3dcc Documentation 2019-12-03 08:15:57 +01:00
Gwendal Roué 4e26e8e744 Lock prevention: better error message 2019-12-03 08:13:19 +01:00
Gwendal Roué 7f66c85e67 Cleanup 2019-12-03 08:11:14 +01:00
Gwendal Roué 9efd5965ea Cleanup 2019-12-02 20:56:06 +01:00
Gwendal Roué 2b4a920732 Cleanup 2019-12-02 20:39:55 +01:00
Gwendal Roué 16025356bf Adapt lock prevention to the journal mode 2019-12-02 20:27:39 +01:00
Gwendal Roué 7015b66636 Update TODO.md 2019-12-02 09:50:57 +01:00
Gwendal Roué f604005b4c Improve interrupt() documentation 2019-12-01 19:03:47 +01:00
Gwendal Roué 1c318892c9 Documentation 2019-12-01 18:56:06 +01:00
Gwendal Roué f66cf92bba CHANGELOG 2019-12-01 18:54:21 +01:00
Gwendal Roué 559aae0263 CHANGELOG 2019-12-01 18:54:01 +01:00
Gwendal Roué 74bb9c11d7 Documentatioon 2019-12-01 18:52:51 +01:00
Gwendal Roué 98dc5df039 Avoid race condition in assertExclusiveLockPrevention 2019-12-01 18:44:23 +01:00
Gwendal Roué d85a7883bb Database.assertExclusiveLockPrevention mirrors assertNotInsideAbortedTransactionBlock 2019-12-01 18:34:51 +01:00
Gwendal Roué d1db8406f4 SQLITE_ABORT_EXCLUSIVE had no real purpose. 2019-12-01 18:26:52 +01:00
Gwendal Roué c8bb6873be Add SQLITE_CREATE_VTABLE to authorizer codes that invalidate schema cache 2019-12-01 17:59:49 +01:00
Gwendal Roué b54a8f7fe8 DatabaseWriter.startPreventingExclusiveLock() 2019-12-01 17:59:49 +01:00
Gwendal Roué 9cdebc45c0 Better assertNotInsideAbortedTransactionBlock 2019-12-01 17:59:49 +01:00
Gwendal Roué f8b6c1a285 More aborted transaction tests 2019-12-01 17:59:49 +01:00
Gwendal Roué 1fb12a2fdf Merge pull request #659 from groue/dev/interrupt
Database interruption
2019-12-01 11:54:04 +01:00
Gwendal Roué e3d25bda61 CHANGELOG 2019-12-01 05:23:19 +01:00
Gwendal Roué eb05c9b87d Documentation 2019-12-01 05:19:56 +01:00
Gwendal Roué 8145915d19 Fix aborted transaction tests for iOS 10.3.1 2019-12-01 04:01:03 +01:00
Gwendal Roué 62ef81c5fb Remove useless code 2019-11-30 21:16:48 +01:00
Gwendal Roué d4fa4c9d5e CHANGELOG 2019-11-30 21:14:06 +01:00
Gwendal Roué 64cb3091cf white space 2019-11-30 21:12:53 +01:00
Gwendal Roué b5ff80e858 Documentation 2019-11-30 21:12:47 +01:00
Gwendal Roué cae66fd5e0 Documentation 2019-11-30 20:51:24 +01:00
Gwendal Roué 79871e2d00 Documentation 2019-11-30 20:26:18 +01:00
Gwendal Roué fa1abdff2b Fix Swiftlint warnings 2019-11-30 19:56:26 +01:00
Gwendal Roué af00fd0f30 Less TODO 2019-11-30 19:53:04 +01:00
Gwendal Roué f90a408630 Tests for aborted transactions 2019-11-30 19:52:25 +01:00
Gwendal Roué f3e9c29f82 Monitor aborted transactions 2019-11-30 19:51:55 +01:00
Gwendal Roué 3ed7174838 DatabaseReader.interrupt() tests 2019-11-30 15:35:29 +01:00
Gwendal Roué 0a83848cfc DatabaseReader.interrupt() 2019-11-30 15:35:11 +01:00
Gwendal Roué 047ada75c7 Thank @MaxDesiatov 2019-11-29 09:02:04 +01:00
Gwendal Roué 129d2fae06 Fix documentation typo 2019-11-29 09:00:45 +01:00
Gwendal Roué 15a97f2b2b Merge pull request #658 from MaxDesiatov/patch-1
Fix typo in README.md
2019-11-27 17:01:52 +01:00
Max Desiatov 975d15733f Fix typo in README.md
> One want to build
2019-11-27 15:57:27 +00:00
Gwendal Roué 62f091a40b Fix typo 2019-11-23 11:45:21 +01:00
Max Desiatov 078f259061 Fix typo in README.md
> `concurrenRead`
2019-11-22 18:25:36 +01:00
Gwendal Roué a67070dd9a Merge branch 'development' 2019-11-20 18:51:03 +01:00
Gwendal Roué f257fb7a4e v4.6.2 2019-11-20 18:47:28 +01:00
Gwendal Roué 3f79892fdb Merge pull request #653 from signalapp/mkirk/empty-migrations
Fix: `appliedMigrations` throws error on new install
2019-11-20 09:04:35 +01:00
Michael Kirk cd6d46e349 move fix to private 2019-11-18 11:33:35 -07:00
Michael Kirk 9ea160b116 Fix: appliedMigrations throws error on new install
Before setup, the grdb_migrations table doesn't exist, so calling
`appliedMigrations` would throw an error.

To avoid this, if the table to track migrations doesn't exist yet, we can be
sure no migrations have been run, and we retun the empty set.

FIXES https://github.com/groue/GRDB.swift/issues/652
2019-11-18 09:09:46 -07:00
Gwendal Roué 8f03b5c8f3 Improve Configuration.targetQueue documentation - #651 2019-11-17 17:41:55 +01:00
Gwendal Roué 3ce3f2fa71 Xcode 11.3 in the Makefile 2019-11-17 17:31:42 +01:00
Gwendal Roué d9c26a40b4 Fix Swiftlint warning 2019-11-14 08:21:50 +01:00
Gwendal Roué 09e271de77 TODO 2019-11-13 19:25:09 +01:00
Gwendal Roué 205dea122f Upgrade performance tests 2019-11-13 04:37:08 +01:00
Gwendal Roué 2eb10aa19a Upgrade performance tests 2019-11-13 04:37:08 +01:00
Gwendal Roué 63fc59fd7c Merge pull request #649 from AnthonyEgerton/patch-1
Fix typo in Release Notes
2019-11-13 04:34:57 +01:00
Anthony Egerton bf6ee31491 Fix typo 2019-11-13 10:44:05 +11:00
Gwendal Roué 146151ffd7 Merge branch 'development' 2019-11-10 17:07:35 +01:00
Gwendal Roué 5b24f598a5 v4.6.1 2019-11-10 17:07:12 +01:00
Gwendal Roué 51a1c418a6 Merge pull request #647 from groue/dev/batch-update-policy
Honor conflict resolution for batch updates
2019-11-10 16:58:32 +01:00
Gwendal Roué e1ff862ffc CHANGELOG 2019-11-10 13:12:42 +01:00
Gwendal Roué 630a2c358a Document conflict resolution for batch updates 2019-11-10 13:05:33 +01:00
Gwendal Roué e0ea30041f Batch update: customization of conflict resolution 2019-11-10 13:00:19 +01:00
Gwendal Roué 58263e9b60 Fix failing test for batch update policy 2019-11-10 12:42:01 +01:00
Gwendal Roué 1e80aecfbd Failing test for batch update policy 2019-11-10 12:34:33 +01:00
Gwendal Roué d5c6dde3d9 Merge branch 'development' 2019-11-10 08:24:32 +01:00
Gwendal Roué 7819c9026a v4.6.0 2019-11-09 17:44:26 +01:00
Gwendal Roué e6617c8e12 Fix typo 2019-11-09 17:24:25 +01:00
Gwendal Roué d03a01a84a Fix typo 2019-11-09 16:23:51 +01:00
Gwendal Roué 90735fb3a7 CHANGELOG 2019-11-09 16:22:42 +01:00
Gwendal Roué 264906221e New Ordered vs. Unordered Associations chapter 2019-11-09 15:51:12 +01:00
Gwendal Roué be21704633 More usage tests for ordered to-many associations: reordering 2019-11-09 15:50:14 +01:00
Gwendal Roué b68bb00033 Simplify association to property type documentation 2019-11-09 14:52:32 +01:00
Gwendal Roué 1dd5c17bc7 Simplify Refining Association Requests chapter 2019-11-09 14:48:49 +01:00
Gwendal Roué c8a2c68728 Typo fix 2019-11-09 14:46:59 +01:00
Gwendal Roué f40c6511ef Usage tests for ordered to-many associations 2019-11-09 14:01:15 +01:00
Gwendal Roué 60aa6c2bf2 Less TODO 2019-11-09 13:11:25 +01:00
Gwendal Roué fe7446431b More NSDecimalNumber tests 2019-11-09 13:07:47 +01:00
Gwendal Roué abe2a62d47 Less TODO 2019-11-09 12:37:00 +01:00
Gwendal Roué 65d0f1edcc Merge pull request #646 from groue/dev/batch-update
Batch updates
2019-11-09 08:49:30 +01:00
Gwendal Roué c09615bab0 Fix bad tests 2019-11-08 20:32:54 +01:00
Gwendal Roué 218afa72c3 Test that order without limit is unused and harmless with updateAll() and deleteAll() 2019-11-08 18:09:11 +01:00
Gwendal Roué cb77fe2ed3 Don't check for ENABLE_UPDATE_DELETE_LIMIT: let SQLite emit syntax errors 2019-11-08 18:08:27 +01:00
Gwendal Roué 7345c5f2dd Fix Swiftlint warnings 2019-11-08 09:04:34 +01:00
Gwendal Roué efdebf59d3 CHANGELOG 2019-11-08 09:04:34 +01:00
Gwendal Roué 35d7490092 Fix SQLCipher tests (it misses ENABLE_UPDATE_DELETE_LIMIT) 2019-11-08 09:04:34 +01:00
Gwendal Roué dd4a2c5d9c Better error message when ENABLE_UPDATE_DELETE_LIMIT is missing 2019-11-08 09:04:34 +01:00
Gwendal Roué eae70f426e URIs don't change: people change them. 2019-11-08 09:04:34 +01:00
Gwendal Roué c7a6ca964c Doc cleanup 2019-11-08 09:04:34 +01:00
Gwendal Roué acb0004cea Move Full-Text documentation in its own file 2019-11-08 09:04:34 +01:00
Gwendal Roué 995d1b851a Rename setter to assignment 2019-11-08 09:04:34 +01:00
Gwendal Roué beab493dd5 Batch update documentation 2019-11-08 09:04:34 +01:00
Gwendal Roué 1c76eb7e9f Test encapsulation of batch update 2019-11-08 09:04:34 +01:00
Gwendal Roué 205398b65a Batch update 2019-11-08 09:04:34 +01:00
Gwendal Roué 61a6c5785f More request.deleteAll() tests 2019-11-08 09:04:34 +01:00
Gwendal Roué d983c6407c Update the list of extended result codes 2019-11-08 09:03:55 +01:00
Gwendal Roué 7cb78a4c86 Makefile: support for Xcode 11.2.1 GM seed 2019-11-08 09:03:47 +01:00
Gwendal Roué 733f6883d0 More TODO 2019-11-07 12:01:07 +01:00
Gwendal Roué 594874656a TODO 2019-11-06 08:24:22 +01:00
Gwendal Roué 6142020c50 Test association aggregate + inner join 2019-11-06 08:24:16 +01:00
Gwendal Roué 6f5b18854d TODO: enhance SQLRequest documentation - #617 2019-11-05 19:05:54 +01:00
Gwendal Roué b39c678a3d Remove dead code 2019-11-05 08:55:30 +01:00
Gwendal Roué a8a85d9a1f Disable some Travis tests
WTF? Travis has removed some simulators in the Xcode 11 setup?

https://travis-ci.org/groue/GRDB.swift/jobs/604303972
https://travis-ci.org/groue/GRDB.swift/jobs/604303975
2019-10-30 08:20:35 +01:00
Gwendal Roué 182b92f010 Opt in for more Swiftlint rules 2019-10-27 19:27:53 +01:00
Gwendal Roué a78f3699eb Help compiling GRDB with SWIFT_VERSION 5.0 and all opt-in APIs 2019-10-27 19:20:21 +01:00
Gwendal Roué 89bc509170 Merge branch 'development' 2019-10-15 18:55:25 +02:00
Gwendal Roué cfa615444e v4.5.0 2019-10-15 08:27:56 +02:00
Gwendal Roué 35389ed978 Fix demo app paths 2019-10-15 07:45:05 +02:00
Gwendal Roué caacecfd83 Remove obsolete GRDBPlus.podspec 2019-10-14 08:07:19 +02:00
Gwendal Roué 924b460c7a Move playgrounds to the Documentation folder 2019-10-14 08:05:50 +02:00
Gwendal Roué 60a9cf4942 Move the demo app to the Documentation folder 2019-10-14 08:03:54 +02:00
Gwendal Roué f9f3080819 Merge pull request #635 from groue/dev/sunsetFetchedRecordsController
Sunset FetchedRecordsController
2019-10-13 19:41:19 +02:00
Gwendal Roué 02c024e819 CocoaPods test apps don't rely on demo app, which requires Swift 5.1 2019-10-13 12:53:09 +02:00
Gwendal Roué 10249675ff CHANGELOG 2019-10-12 15:19:50 +02:00
Gwendal Roué b6553c0b59 Demo app: replace FetchedRecordsController with ValueObservation 2019-10-12 14:49:18 +02:00
Gwendal Roué dfd3e50b9c Sunset FetchedRecordsController 2019-10-12 14:10:56 +02:00
Gwendal Roué 79b8f7ed1d Merge pull request #633 from groue/dev/CocoaPodsOptions
SQLITE_ENABLE_PREUPDATE_HOOK support with CocoaPods
2019-10-12 13:00:22 +02:00
Gwendal Roué f184c626e0 SQLITE_ENABLE_PREUPDATE_HOOK documentation 2019-10-12 12:56:39 +02:00
Gwendal Roué 24ba40a77e GRDB_SQLITE_ENABLE_PREUPDATE_HOOK exposes missing SQLITE_ENABLE_PREUPDATE_HOOK declarations 2019-10-10 20:16:15 +02:00
Gwendal Roué 66326d79a2 Minor doc fix 2019-10-10 19:50:30 +02:00
Gwendal Roué fcd6c100ee Fix Xcode 11.1 tvOS destination in Makefile 2019-10-10 18:33:53 +02:00
Gwendal Roué 95b7879e33 CHANGELOG 2019-10-10 18:33:17 +02:00
Gwendal Roué 404532f6f0 Add LockedBox to GRDBCustom 2019-10-10 13:52:33 +02:00
Gwendal Roué 751262cdb3 Better DatabaseReader tests 2019-10-10 13:51:44 +02:00
Gwendal Roué 0ac0d31796 Better snapshot tests 2019-10-10 13:51:33 +02:00
Gwendal Roué 9d5d7f0216 Database.withSchemaCache 2019-10-10 13:51:00 +02:00
Gwendal Roué b59521e247 ReadWriteBox(value:) initializer 2019-10-10 13:50:42 +02:00
Gwendal Roué 7dd90c4af3 Don’t return Void 2019-10-10 13:49:55 +02:00
Gwendal Roué b06e4ad298 Make DatabaseSnapshot.reentrantRead actually reentrant 2019-10-10 13:49:39 +02:00
Gwendal Roué ff21f86341 DatabasePool setup: handle #102 in a savepoint 2019-10-10 13:49:12 +02:00
Gwendal Roué c89d41adbb Rename readerConfig to readerConfiguration 2019-10-10 13:48:20 +02:00
Gwendal Roué b3e1bf6f05 Database.checkpoint 2019-10-10 13:45:01 +02:00
Gwendal Roué fc57a69672 Rename beginSnapshotTransaction to beginSnapshotTransaction 2019-10-10 13:43:10 +02:00
Gwendal Roué fdbc0c8ec8 LockedBox: for when one does not need single writer/multiple readers 2019-10-10 13:41:58 +02:00
Gwendal Roué e3edf6daec Snapshot documentation improvements 2019-10-10 13:38:43 +02:00
Gwendal Roué 1b8f7b95f4 CHANGELOG and thank you notice 2019-10-10 08:20:32 +02:00
Gwendal Roué f756f39772 Merge pull request #632 from runhum/bugfix/readme-typos
Fix Accout -> Account
2019-10-09 17:28:45 +02:00
Runar Hummelsund 836f34297d Fix Accout -> Account 2019-10-09 17:19:44 +02:00
Gwendal Roué cd6d2579a5 Merge pull request #631 from groue/dev/issue630
Fix custom SQLite builds
2019-10-07 06:31:00 +02:00
Gwendal Roué 2892424006 CHANGELOG 2019-10-06 13:51:03 +02:00
Gwendal Roué 856792d688 Travis: test custom SQLite installation 2019-10-06 13:03:43 +02:00
Gwendal Roué 00115ba60c More explicit documentation for the Pre-action script 2019-10-06 12:57:03 +02:00
Gwendal Roué 1cdddd35c8 Fix Xcode warnings 2019-10-06 12:55:35 +02:00
Gwendal Roué ccaf4c942f Test installation procedure for custom SQLite 2019-10-06 12:55:21 +02:00
Gwendal Roué 9f9fcb1a8e Address #630 2019-10-06 12:21:49 +02:00
Gwendal Roué b6955377c9 CHANGELOG 2019-10-06 11:49:45 +02:00
Gwendal Roué 5f085f2df8 Merge pull request #627 from groue/dev/SPM
Swift Package Manager: define SQLite as a system library target
2019-10-04 19:01:49 +02:00
Gwendal Roué 3cc5bb7c98 Test SPM integration from Xcode 2019-10-02 18:27:40 +02:00
Gwendal Roué 3dc4567233 SPM: Replace groue/CSQLite with a systemLibrary target 2019-10-02 18:02:49 +02:00
Gwendal Roué 37477adada Merge pull request #622 from groue/dev/620
Allow observation of FTS4 virtual tables
2019-09-27 06:04:03 +02:00
Gwendal Roué a44afd79e0 Makefile: support for Xcode 11.1 2019-09-26 13:15:32 +02:00
Gwendal Roué 61088ee2e7 Makefile: use iPhone 11 simulator with Xcode 11.0 2019-09-26 13:07:47 +02:00
Gwendal Roué a721917d95 CHANGELOG 2019-09-26 09:03:10 +02:00
Gwendal Roué a08b078c3e Fix a swiftlint warning 2019-09-26 08:49:57 +02:00
Gwendal Roué aa1cfb9020 Fix testSynchronizedFTS4Observation 2019-09-26 08:49:44 +02:00
Gwendal Roué 0d961ce48e Simplify DatabaseRegion.iisModified(by:)
There is no "fast path" any longer. Performance impact should be minimal since most observers call `stopObservingDatabaseChangesUntilNextTransaction` on first impactful change anyway.
2019-09-26 06:55:54 +02:00
Gwendal Roué 1b753802dd Address #620, but a failing test remains 2019-09-25 20:03:00 +02:00
Gwendal Roué 3f3bdde10c #620 explorations 2019-09-25 17:08:02 +02:00
Gwendal Roué b2ea9e51d2 Help debugging authorization issues like #620 2019-09-25 17:04:26 +02:00
Gwendal Roué 27a05028db SQLRequest+SQLLiteral: added literal initialization tests 2019-09-17 08:54:34 +02:00
Gwendal Roué 725e16390b Fix failing test for eraseDatabaseOnSchemaChange 2019-09-17 08:22:36 +02:00
Gwendal Roué 6b83ba3585 Failing test for eraseDatabaseOnSchemaChange 2019-09-17 08:18:45 +02:00
Gwendal Roué 62e50b1a73 Simplify eraseDatabaseOnSchemaChange implementation 2019-09-17 08:10:28 +02:00
Gwendal Roué bf7192cef1 Siimplify Row: Swift has better ARC optimizations now 2019-09-13 19:39:45 +02:00
Gwendal Roué 18d634b171 Update performance tests for Xcode 11 2019-09-13 19:11:21 +02:00
Gwendal Roué a5b5bccc61 Update TODO.md 2019-09-13 14:04:43 +02:00
Gwendal Roué 988852a438 Makefile/Travis: min tvOS 10.2 on Xcode 10.3 2019-09-13 04:59:51 +02:00
Gwendal Roué 2313713603 Makefile/Travis: min iOS 10.3.1 on Xcode 10.3 2019-09-13 04:56:32 +02:00
Gwendal Roué 6a5ce71c12 Makefile/Travis: Don't code sign 2019-09-12 07:09:27 +02:00
Gwendal Roué 9872e945ba Makefile/Travis: Xcode 11 use iPhone Xs + iOS 13.0 2019-09-11 19:48:50 +02:00
Gwendal Roué b3341cc552 Makefile/Travis: Xcode 11 min iOS is 10.3.1 2019-09-11 19:42:41 +02:00
Gwendal Roué 0a1e3afa82 Makefile/Travis: Xcode 11 2019-09-11 08:52:18 +02:00
Gwendal Roué 483728bfbf Fix typo 2019-09-09 08:43:29 +02:00
Gwendal Roué b459536b66 TODO 2019-09-07 15:55:07 +02:00
Gwendal Roué d990b47814 Fix compiler warnings 2019-09-07 12:51:46 +02:00
Gwendal Roué aa157a77d2 Merge branch 'development' 2019-09-06 08:07:49 +02:00
Gwendal Roué 254f3760b4 v4.4.0 2019-09-06 08:06:15 +02:00
Gwendal Roué 896ec284e1 Merge pull request #602 from groue/dev/passphrase-refactoring
Don't keep the sqlCipher passphrase in memory longer than necessary
2019-09-06 07:59:35 +02:00
Gwendal Roué 036178a55a CHANGELOG 2019-09-06 07:52:18 +02:00
Gwendal Roué 3ff94c7607 CHANGELOG 2019-09-06 07:44:15 +02:00
Gwendal Roué 5c125fae8b Add a "Managing the lifetime of the passphrase string" security consideration 2019-09-05 13:28:19 +02:00
Gwendal Roué 642089f41a Suggest using Data Protection 2019-09-04 19:16:14 +02:00
Gwendal Roué 6285a59926 Fix sample code 2019-09-04 19:09:32 +02:00
Gwendal Roué 4ba199f0aa Organization 2019-09-04 18:53:11 +02:00
Gwendal Roué 75f3540b8f Typo 2019-09-04 18:50:16 +02:00
Gwendal Roué bfa1689d7d Typo 2019-09-04 18:49:47 +02:00
Gwendal Roué a1c96f9093 Another suggestion by @michaelkirk-signal 2019-09-04 18:46:44 +02:00
Gwendal Roué 32842c22f0 Wording 2019-09-04 18:38:37 +02:00
Gwendal Roué 8e764aadd2 Fix typo 2019-09-04 18:36:53 +02:00
Gwendal Roué ad9b32f9a2 Fix ambiguous wording 2019-09-04 18:35:52 +02:00
Gwendal Roué cb9323480c Fix typo 2019-09-04 18:31:32 +02:00
Gwendal Roué cc7d19d925 Apply wording by @michaelkirk-signal 2019-09-04 18:24:25 +02:00
Gwendal Roué c2e68d95fe Passphrase documentation 2019-09-04 08:54:22 +02:00
Gwendal Roué 7b3275ce45 Make lastErrorCode and lastErrorMessage public 2019-09-04 08:54:06 +02:00
Gwendal Roué 9a69dbd8a1 Remove testDatabaseQueueWithPassphraseToDatabaseQueueWithWrongPassphraseAndRetry 2019-09-03 13:26:16 +02:00
Gwendal Roué f2198f5af7 Passphrase documentation (WIP) 2019-09-03 09:11:52 +02:00
Gwendal Roué 8150dda951 Passphrase documentation (WIP) 2019-09-03 09:10:02 +02:00
Gwendal Roué d4928eff99 Test that prepareDatabase errors are rethrown 2019-09-03 09:07:14 +02:00
Gwendal Roué 1f48405b5c Rewrite passphrase documentation (WIP) 2019-09-03 08:56:41 +02:00
Gwendal Roué 55d4a9c029 Test for attempting several passphrases 2019-09-03 08:56:16 +02:00
Gwendal Roué e6bc1c40fe CHANGELOG 2019-09-03 08:55:57 +02:00
Gwendal Roué b9e2f35728 Deprecate change(passphrase:), and provide an alternative solution 2019-09-02 09:05:37 +02:00
Gwendal Roué 6fc7794e64 Restore testDeprecatedPassphrase 2019-09-02 08:38:15 +02:00
Gwendal Roué 1d71b9f311 Update testPrepareDatabase for snapshots 2019-09-02 08:38:15 +02:00
Gwendal Roué 9f26777cc3 prepareDatabase did not need to be deprecated, after all 2019-09-02 08:38:15 +02:00
Gwendal Roué 0b9fe9ae92 Documentation 2019-09-02 08:38:15 +02:00
Gwendal Roué 1ba4e8c771 Fix failing test for change(passphrase:) 2019-09-02 08:38:15 +02:00
Gwendal Roué aded6d206d Failing test for change(passphrase:) 2019-09-02 08:38:15 +02:00
Gwendal Roué d644f01557 Deprecate Configuration.passphrase, introduce Database.usePassphrase(_:) 2019-09-02 08:38:15 +02:00
Gwendal Roué eb112c912c Fix Xcode 11 warnings in SQLCipher test projects 2019-09-02 08:37:28 +02:00
Gwendal Roué d8b0b95842 DatabaseConfiguration.onConnect 2019-09-02 08:37:28 +02:00
Gwendal Roué 8f66114042 Deprecate Configuration.prepareDatabase 2019-09-02 08:37:28 +02:00
Gwendal Roué 943eca10a6 TODO 2019-09-02 08:37:28 +02:00
Gwendal Roué 82f56ee596 Merge pull request #603 from groue/dev/pool-barrier
DatabasePool write barrier
2019-09-02 08:36:01 +02:00
Gwendal Roué 00e2c2a626 Fix testBarrierIsLockedByOneUnfinishedRead for Swift 4.2 2019-09-02 05:39:38 +02:00
Gwendal Roué c7e4492846 Fix DatabasePool.change(passphrase:) 2019-09-01 19:33:03 +02:00
Gwendal Roué 04a6e969a5 DatabasePool.barrierWriteWithoutTransaction documentation 2019-09-01 17:30:01 +02:00
Gwendal Roué 5b4a225dc3 DatabasePool.barrierWriteWithoutTransaction tests 2019-09-01 17:19:12 +02:00
Gwendal Roué e3efcc0d87 CHANGELOG 2019-09-01 17:03:22 +02:00
Gwendal Roué 8580023eda DatabasePool.barrierWriteWithoutTransaction 2019-09-01 16:46:17 +02:00
Gwendal Roué 473f6ff0d8 Tests for Pool.barrier 2019-09-01 16:32:39 +02:00
Gwendal Roué e495df0114 Pool.barrier 2019-09-01 16:32:18 +02:00
Gwendal Roué 06d6c3866b ReadWriteBox Cleanup 2019-09-01 16:28:16 +02:00
Gwendal Roué da459386a0 Merge branch 'development' 2019-08-28 08:25:35 +02:00
Gwendal Roué 1023f260b7 v4.3.0 2019-08-28 08:22:38 +02:00
Gwendal Roué a6fa76a954 More TODO 2019-08-28 08:07:19 +02:00
Gwendal Roué 3e48eb703e CHANGELOG 2019-08-24 10:57:24 +02:00
Gwendal Roué 7cf10bfb67 Merge pull request #600 from outfoxx/tvos-support
Add support for tvOS
2019-08-24 10:49:20 +02:00
Kevin Wooten 055e33b381 Add missing tvOS stages to Xcode 10.1 2019-08-23 10:54:58 -07:00
Kevin Wooten 7fffc2791e Bump min tvOS to 10.0
tvOS 9.0 appears to have issues with running tests
2019-08-23 10:54:27 -07:00
Kevin Wooten 4d3f0bd88b Add support for tvOS
## Xcode Project
- [x] tvOS Target
- [x] tvOS Unit Test Target
- [x] tvOS Scheme

## Makefile
- [x] tvOS Target Min/Max
- [x] tvOS Actions (copies iOS)

## CI
- [x] tvOS Travis stages

## Packaging
- [x] CocoaPods - Podfile Updated
- [x] ~SwiftPM - Not Changes Required~

## Documentation
- [x] Readme Updated
2019-08-22 13:15:31 -07:00
Gwendal Roué 881d4c6bfc TODO 2019-08-22 05:34:43 +02:00
Gwendal Roué ba02713d78 TODO 2019-08-14 07:55:49 +02:00
Gwendal Roué 6f6e382948 Merge branch 'development' 2019-08-13 07:58:27 +02:00
Gwendal Roué b7c7892a74 v4.2.1 2019-08-13 07:56:28 +02:00
Gwendal Roué a6112a5ca2 Merge pull request #592 from groue/dev/issue-591
Fix Data interpolation
2019-08-12 12:34:24 +02:00
Gwendal Roué d219f5589e CHANGELOG 2019-08-11 13:14:44 +02:00
Gwendal Roué 01a1a7c962 Fix typo 2019-08-11 13:04:24 +02:00
Gwendal Roué 8e38af9aae Fix #591 2019-08-11 13:03:43 +02:00
Gwendal Roué d28847bf3d Failing test for https://github.com/groue/GRDB.swift/issues/591 2019-08-11 12:56:29 +02:00
Gwendal Roué 24c25dfd04 Explicit tests for DatabaseValueConvertible interpolation 2019-08-11 12:25:48 +02:00
Gwendal Roué 18e09cda11 TODO 2019-08-11 12:04:03 +02:00
Gwendal Roué fb54c2ae45 Merge branch 'development' 2019-08-06 12:10:28 +02:00
Gwendal Roué a08e8f0ef6 Merge pull request #587 from groue/GRDB-4.2
GRDB 4.2.0
2019-08-06 12:09:28 +02:00
Gwendal Roué bd81f6e7a6 v4.2.0 2019-08-06 06:58:13 +02:00
Gwendal Roué eea8f7b1e9 Use ValueObservation.tracking(value:) in demo app 2019-08-06 06:54:39 +02:00
Gwendal Roué c734eba245 Upgrade performance tests
Upgrade Realm to v3.17.3
Upgrade FMDB to v2.7.4
Upgrade SQLite.swift to v0.12.2
2019-08-05 20:56:49 +02:00
Gwendal Roué 71bf6fdbcf TODO 2019-08-05 20:30:29 +02:00
Gwendal Roué 226410caf8 TODO cleanup 2019-08-05 20:19:48 +02:00
Gwendal Roué 82d80d4120 Merge pull request #586 from groue/dev/value-observation-variable-region
Automatic region tracking for ValueObservation
2019-08-05 19:47:59 +02:00
Gwendal Roué 80baa798d6 CHANGELOG 2019-08-05 12:39:37 +02:00
Gwendal Roué ba1142ac58 Fix typo 2019-08-05 12:34:23 +02:00
Gwendal Roué e279d287b9 Even more fostering of ValueObservation.tracking(fetch:) in README 2019-08-05 12:32:12 +02:00
Gwendal Roué 87b474029e Test that observations of tuples are easy to consume. 2019-08-05 12:31:39 +02:00
Gwendal Roué 8af3b58e54 Fix documentation 2019-08-05 09:04:14 +02:00
Gwendal Roué a770d46843 Rename ValueObservation.tracking(fetch:) to ValueObservation.tracking(value:) 2019-08-05 09:03:05 +02:00
Gwendal Roué efaa387ee2 Remove useless documentation paragraph 2019-08-05 08:38:25 +02:00
Gwendal Roué f849c38f43 Foster ValueObservation.tracking(fetch:) in README 2019-08-05 08:34:47 +02:00
Gwendal Roué ea43468a6f Documentation 2019-08-05 07:52:32 +02:00
Gwendal Roué fd18a7b75d Fix for Xcode < 10.2 2019-08-05 07:48:34 +02:00
Gwendal Roué fe9c4381e0 Makefile: support for Xcode 10.3, and fix test_performance target 2019-08-04 14:59:48 +02:00
Gwendal Roué 0f2c5cd8a0 Fix failling test for rowid optimization in Database.recordingSelectedRegion 2019-08-04 14:37:40 +02:00
Gwendal Roué 9c864bc768 Failling test for rowid optimization in Database.recordingSelectedRegion 2019-08-04 14:37:10 +02:00
Gwendal Roué dc146a431c Tests for Database.recordingSelectedRegion 2019-08-04 14:36:20 +02:00
Gwendal Roué c718889418 Update ValueObservation documentation 2019-08-04 11:45:43 +02:00
Gwendal Roué d61522ee5f Update ValueObservation documentation 2019-08-04 11:42:54 +02:00
Gwendal Roué c4481f4e79 Fix ValueObservationRegionRecordingTests for SQLite < 3.19.0 2019-08-04 10:44:08 +02:00
Gwendal Roué 731a83908d Test automatic ValueObservation region tracking with various schedulings 2019-08-03 18:03:05 +02:00
Gwendal Roué 62a12d94ce CHANGELOG 2019-08-03 17:41:39 +02:00
Gwendal Roué 4f025e59af Documentation 2019-08-03 17:21:42 +02:00
Gwendal Roué 2039cd4874 Documentation 2019-08-03 17:18:47 +02:00
Gwendal Roué 1b94c38b4f Documentation 2019-08-03 17:16:03 +02:00
Gwendal Roué f556fc39ab Documentation 2019-08-03 17:01:16 +02:00
Gwendal Roué a5c8f23ba4 Support for variable observed region of ValueObservation based on actual selection 2019-08-03 16:32:33 +02:00
Gwendal Roué af0ac156aa More explicit observation initializers 2019-08-03 14:21:46 +02:00
Gwendal Roué 8d5cddd293 Merge pull request #585 from groue/dev/issue-583
Fix use of SQLite authorizers
2019-08-03 13:37:50 +02:00
Gwendal Roué 38599b007f CHANGELOG 2019-08-03 07:15:55 +02:00
Gwendal Roué 5908c26a79 Fix Makefile so that it can checkoutt the FMDB submodule 2019-08-03 06:48:08 +02:00
Gwendal Roué d32b5271bd Performance tests: update paths for Xcode 10.3 2019-08-03 06:43:31 +02:00
Gwendal Roué 55803b29b0 Keep a memory of how to trigger #583 error 2019-08-02 17:56:47 +02:00
Gwendal Roué 870d22fd95 Explain why we call sqlite3_set_authorizer once per database connection 2019-08-02 16:06:19 +02:00
Gwendal Roué c6cb92d757 Cleanup 2019-08-02 15:40:19 +02:00
Gwendal Roué 3ab8a34d58 Fix a Swiftlint warning 2019-08-02 15:34:49 +02:00
Gwendal Roué bd9104d29f Cleanup 2019-08-02 15:34:25 +02:00
Gwendal Roué e351b79526 Database only exposes its current authorizer with the withAuthorizer(_:_:) wrapper method. 2019-08-02 15:16:48 +02:00
Gwendal Roué a59f4ef096 Fix #583 by keeping a single authorizer active for the whole lifetime of a database connection
SQLite invalidates statements when authorizer changes, which can lead to undesired behaviors. This is why we now call sqlite3_set_authorizer only once. See http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
2019-08-02 14:17:48 +02:00
Gwendal Roué bb959fa5c3 Add failing test for #583 2019-08-02 14:14:48 +02:00
Gwendal Roué 2b3e5a06db CONTRIBUTING: mention GRDBCombine 2019-07-31 08:07:52 +02:00
Gwendal Roué e58b652970 CONTRIBUTING: static libray is possible since #570 2019-07-31 08:04:38 +02:00
Gwendal Roué 62f5bd1940 CONTRIBUTING: fix inner link 2019-07-31 08:03:04 +02:00
Gwendal Roué 63cb9f2ad2 CONTRIBUTING: mention #575 2019-07-31 08:01:39 +02:00
Gwendal Roué 19cf569036 Add @chrisballinger to the thank you notice 2019-07-31 07:43:16 +02:00
Gwendal Roué e23cb4ed76 Merge pull request #570 from Rightpoint/fix-issue-360-modulemap
Allow Swift static library integration via CocoaPods
2019-07-31 06:59:05 +02:00
Chris Ballinger bdf802ab34 Update CHANGELOG and README 2019-07-30 16:34:19 -07:00
Gwendal Roué 507ae0dfdc Tests for framework & static CocoaPods integration 2019-07-30 16:33:20 -07:00
Chris Ballinger 56af3ceff6 Remove modulemap from podspec 2019-07-30 16:33:20 -07:00
Gwendal Roué 4ffb59719a Fix #580 2019-07-30 06:57:03 +02:00
Gwendal Roué bb0c11f7d5 TODO 2019-07-29 09:11:47 +02:00
Gwendal Roué 82c8958c44 Merge pull request #576 from groue/dev/fullltext
Expose table name and full-text filtering methods to DerivableRequest
2019-07-28 14:00:59 +02:00
Gwendal Roué e8ad3871f7 Fix for Xcode 10.0, 10.1 2019-07-28 08:59:23 +02:00
Gwendal Roué 53aaca480e Merge branch 'development' into dev/fullltext
# Conflicts:
#	CHANGELOG.md
2019-07-27 23:11:00 +02:00
Gwendal Roué 23678ab9da Update documentatiion for #577 2019-07-27 23:06:36 +02:00
Gwendal Roué 2996a24de9 Merge pull request #577 from groue/dev/renameAliased
Rename aliased(_:) methods to forKey(_:)
2019-07-27 22:59:09 +02:00
Gwendal Roué dba8d636bb Less TODO 2019-07-27 17:10:31 +02:00
Gwendal Roué faa7bf7e53 Less TODO 2019-07-27 17:10:01 +02:00
Gwendal Roué 05fdf5cfdd CHANGELOG 2019-07-27 17:08:53 +02:00
Gwendal Roué b4ef6a3dad CHANGELOG 2019-07-27 17:08:11 +02:00
Gwendal Roué 0c709294a0 Fix documentation 2019-07-27 16:45:06 +02:00
Gwendal Roué d15bb190eb Enable Code Coverage in GRDBCustomSQLiteOSX target 2019-07-27 16:36:53 +02:00
Gwendal Roué ede4572da3 Update tests for the new forKey(_:) methods 2019-07-27 16:34:17 +02:00
Gwendal Roué b4929bb638 Rename aliased(_:) to forKey(_:) 2019-07-27 16:29:09 +02:00
Gwendal Roué 52cd98547d Fix DerivableRequest.matching(_:) tests so that OSX 10.0 is not required 2019-07-27 15:58:33 +02:00
Gwendal Roué 5cced46a61 API diff 2019-07-27 15:23:29 +02:00
Gwendal Roué 3f8e994501 API diff 2019-07-27 15:23:29 +02:00
Gwendal Roué ae60bc6e18 CHANGELOG 2019-07-27 15:23:29 +02:00
Gwendal Roué 462e5eee24 Cleanup 2019-07-27 15:23:29 +02:00
Gwendal Roué c1a0b7f9e2 Add missing Foundation imports (https://github.com/openbitapp/GRDB.swift/commit/9669e3007f42359e4165759208c5df8455531b12) 2019-07-27 15:23:29 +02:00
Gwendal Roué 89001f11c3 Spot that annotations are another challenge on the way to optional + required join chaining 2019-07-27 15:23:29 +02:00
Gwendal Roué 026db8f19a Tests for TableRequest requirement on DerivableRequest, including the new support for full-text search 2019-07-27 15:23:29 +02:00
Gwendal Roué 2d1f218ec5 Force TableRecord on Association origin & destination, append TableRequest to DerivableRequest requirements 2019-07-27 15:23:29 +02:00
Gwendal Roué 4d558488c0 Expose matching(_:) on TableRequest&FilteredRequest 2019-07-27 15:23:29 +02:00
Gwendal Roué bf73f0ded2 CHANGELOG 2019-07-27 15:22:13 +02:00
Gwendal Roué b8cc4c30f9 TODO 2019-07-27 12:47:39 +02:00
Gwendal Roué cf2a6763b5 Merge pull request #574 from groue/dev/swiftlint
SwiftLint
2019-07-27 12:46:53 +02:00
Gwendal Roué e65e2a3bd1 CHANGELOG 2019-07-26 21:18:51 +02:00
Gwendal Roué 56d355c903 The kiss of Xcode 10.3 2019-07-26 21:09:19 +02:00
Gwendal Roué 35ceeebb3d Style tweaks 2019-07-26 20:56:33 +02:00
Gwendal Roué d9e1a04cc2 Fix FTS3 & FTS4 regressions 2019-07-26 19:52:34 +02:00
Gwendal Roué d7a51c39ca Remove Swiift 5 conversion warning 2019-07-26 19:30:59 +02:00
Gwendal Roué 756f1b9387 swiftlint: remove large_tuple, add unused_declaration 2019-07-26 19:30:52 +02:00
Gwendal Roué df6bb8761c Swiftlint + whitespace 2019-07-01 08:57:53 +02:00
Gwendal Roué b3215cc471 Less TODO 2019-06-30 13:43:12 +02:00
Gwendal Roué 7defc8ea07 Merge pull request #563 from groue/dev/eager-loading-from-optional-to-one
More tests for eager loading of hasMany associations
2019-06-30 10:24:33 +02:00
Gwendal Roué 2b401fe745 We don't really care about useless LEFT JOINs 2019-06-29 15:32:13 +02:00
Gwendal Roué 3e4c6fd102 Add more eager loading SQL tests (and spot a possible optimization) 2019-06-29 15:21:24 +02:00
Gwendal Roué 9946880c5e Add tests for including(optional: hasOne.including(all: hasMany)) 2019-06-29 14:12:46 +02:00
Gwendal Roué 738ea4ed10 Merge pull request #562 from groue/dev/fix-561
Fix crash when using more than one DatabaseCollation
2019-06-29 10:31:53 +02:00
Gwendal Roué 498c65a64c CHANGELOG 2019-06-28 19:06:49 +02:00
Gwendal Roué fbc50dd2d1 CHANGELOG 2019-06-28 19:06:11 +02:00
Gwendal Roué 7802eb356d Fix failing test for #561 2019-06-28 19:02:21 +02:00
Gwendal Roué 036e236dc0 Failing test for #561 2019-06-28 19:01:58 +02:00
Gwendal Roué ff2f8bd88e More TODO 2019-06-28 17:18:00 +02:00
Gwendal Roué 1d47fb16be TODO: predicates 2019-06-26 09:34:50 +02:00
Gwendal Roué 5345ccd53e Merge pull request #560 from bellebethcooper/patch-1
Minor typo fix
2019-06-26 09:31:29 +02:00
bellebethcooper e1ee2afba1 Minor typo fix 2019-06-26 17:24:26 +10:00
Gwendal Roué d290102d9c v4.1.1 2019-06-22 09:14:48 +02:00
Gwendal Roué de3f32b6ad Merge pull request #552 from groue/GRDB-4.1
GRDB 4.1
2019-06-20 08:13:03 +02:00
Gwendal Roué cb517dc5c9 Update release date 2019-06-20 08:08:32 +02:00
Gwendal Roué 49d098eb7b Merge pull request #555 from groue/dev/readOnlyError
Avoid a crash when read-only access can't be established
2019-06-19 08:04:00 +02:00
Gwendal Roué caa624f56b Readonly: avoid hitting the db if unnecessary 2019-06-19 04:16:07 +02:00
Gwendal Roué c190b1355e CHANGELOG 2019-06-18 20:45:23 +02:00
Gwendal Roué 335850c5fe Fix #554 2019-06-18 20:40:49 +02:00
Gwendal Roué 2730f8f806 Fix DatabasePool.concurrentRead for Swift < 5 2019-06-18 08:37:21 +02:00
Gwendal Roué dc2871d5eb DatabaseWriter.spawnConcurrentRead (experimental method) 2019-06-18 08:21:55 +02:00
Gwendal Roué cdccac8c86 Documentation 2019-06-17 19:52:55 +02:00
Gwendal Roué 173c8af3ef asyncConcurrentRead documentation 2019-06-17 19:48:25 +02:00
Gwendal Roué 3cea3db2b4 DatabasePool.asyncConcurrentRead 2019-06-17 19:35:11 +02:00
Gwendal Roué 7526276f98 Documentation 2019-06-16 14:54:42 +02:00
Gwendal Roué b9925d1620 Avoid iPhone XS/iPhone Xs ambiguity 2019-06-15 14:16:52 +02:00
Gwendal Roué 68d4889864 Ignore various Podfile.lock 2019-06-15 14:14:45 +02:00
Gwendal Roué c5cb8f44f3 Fix Xcode warnings and update GRDBDemoiOS to latest APIs 2019-06-15 13:29:24 +02:00
Gwendal Roué 309fa97606 Prepare 4.1.0: README.md 2019-06-15 12:44:52 +02:00
Gwendal Roué a2ba53ab26 Prepare 4.1.0: Info.plist 2019-06-15 12:37:18 +02:00
Gwendal Roué 3a98f337bd Prepare 4.1.0: GRDB.swift.podspec 2019-06-15 12:36:40 +02:00
Gwendal Roué 8663a1bf3f Prepare 4.1.0: CustomSQLiteBuilds.md 2019-06-15 12:35:39 +02:00
Gwendal Roué fc13454f29 Prepare 4.1.0: Makefile 2019-06-15 12:34:53 +02:00
Gwendal Roué 8cadb97b2f Prepare 4.1.0: CHANGELOG 2019-06-15 12:33:13 +02:00
Gwendal Roué 278e4190db Enhance SQLite error 10/23 FAQ with sample code 2019-06-15 04:55:53 +02:00
Gwendal Roué d3fe40127c Forget SR-1570 2019-06-15 04:44:16 +02:00
Gwendal Roué 3f9b94f95e Group SQLite error FAQs together 2019-06-15 04:39:07 +02:00
Gwendal Roué 02e1793cc9 Move configuration requirement to DatabaseReader 2019-06-15 04:32:14 +02:00
Gwendal Roué e40e37bd04 FetchRequest.makePreparedRequest 2019-06-15 04:24:29 +02:00
Gwendal Roué 65de31a335 Polishing 2019-06-14 22:01:57 +02:00
Gwendal Roué 66552ebc77 Merge pull request #550 from groue/dev/async
Asynchronous Database Access Methods
2019-06-14 18:58:06 +02:00
Gwendal Roué 4a79a20116 Foster asyncWrite over asyncWriteWithoutTransaction 2019-06-14 08:10:16 +02:00
Gwendal Roué f03fd276f1 asyncWrite's completion handler accepts a database connection
This guarantees that the asyncWrite method provides exclusive write access for the whole duration of (transaction + result handling).
2019-06-14 08:03:13 +02:00
Gwendal Roué 0e031cd5a9 CHANGELOG 2019-06-13 22:40:51 +02:00
Gwendal Roué cd3c84d19e Stop fostering ValueObservation.start(in:onChange:) without error handling 2019-06-13 22:37:21 +02:00
Gwendal Roué 29cfebdec0 GRDBCombine is a companion library 2019-06-13 20:26:44 +02:00
Gwendal Roué d0e839c2b4 Note about availability of asynchronous APIs 2019-06-13 20:13:19 +02:00
Gwendal Roué d18c65fbe5 Documentation for asynchronous APIs 2019-06-13 20:06:58 +02:00
Gwendal Roué 07ade5ee75 Merge branch 'development' into dev/async 2019-06-13 19:20:57 +02:00
Gwendal Roué 3897e9824c CHANGELOG 2019-06-13 19:20:46 +02:00
Gwendal Roué 0c2875a310 TODO 2019-06-13 14:39:50 +02:00
Gwendal Roué f7946834f1 Fix compiler checks for async methods 2019-06-13 14:14:35 +02:00
Gwendal Roué 0ad819902d Tests for asyncRead, asyncWrite, asyncWriteWithoutTransaction 2019-06-13 13:42:31 +02:00
Gwendal Roué b715ca5eb8 DatabaseWriter.asyncWrite 2019-06-13 13:20:59 +02:00
Gwendal Roué bc7c3e5eb1 DatabaseReader.asyncRead 2019-06-13 08:45:49 +02:00
Gwendal Roué 9650783ea4 Update code snippets for ValueObservation.start 2019-06-13 06:13:26 +02:00
Gwendal Roué 4b0e43f884 TODO 2019-06-13 05:29:05 +02:00
Gwendal Roué f120632e36 Rename unsafeAsyncWrite to asyncWriteWithoutTransaction
Hold on: a more complete set of async APIs will come eventually.
2019-06-13 05:25:56 +02:00
Gwendal Roué d42b515fb6 Documentation 2019-06-13 04:56:05 +02:00
Gwendal Roué 47b813057a Merge pull request #549 from groue/dev/CombineSupport
Support for Combine
2019-06-13 04:28:09 +02:00
Gwendal Roué 1db76a9d85 Merge pull request #540 from groue/dev/SQLite-3.28.0
Update SQLite to 3.28.0
2019-06-13 04:24:29 +02:00
Gwendal Roué a59546203f CHANGELOG 2019-06-12 19:54:39 +02:00
Gwendal Roué 085f4c9597 removeDuplicates 2019-06-12 19:48:32 +02:00
Gwendal Roué bec731d763 Rename file 2019-06-12 19:40:07 +02:00
Gwendal Roué b0be32be71 Merge branch 'development' into dev/SQLite-3.28.0 2019-06-12 19:09:40 +02:00
Gwendal Roué d774d353e7 Upgrade swiftlyfalling/SQLiteLib 2019-06-12 19:09:19 +02:00
Gwendal Roué 44138c433f Refactor ValueObservation scheduling 2019-06-11 21:45:27 +02:00
Gwendal Roué f502db40b0 combine instance method 2019-06-10 23:24:02 +02:00
Gwendal Roué 86f7ab74a7 More ValueReducers namespacing 2019-06-10 22:18:20 +02:00
Gwendal Roué cea22f261e observationForCount, observationForAll, observationForFirst documentation 2019-06-10 20:19:08 +02:00
Gwendal Roué da34694663 observationForCount, observationForAll, observationForFirst 2019-06-10 20:19:00 +02:00
Gwendal Roué 085fd13ef6 CHANGELOG 2019-06-09 12:05:05 +02:00
Gwendal Roué 50c9792eb2 Merge pull request #546 from openbitapp/master
fix errors for Xcode 11 beta
2019-06-09 11:57:59 +02:00
Gwendal Roué 795056a3b6 Restore swift-tools-version:4.2 2019-06-09 11:47:08 +02:00
Gwendal Roué aca4db2c96 Move reducers to the ValueReducers namespace 2019-06-09 11:43:44 +02:00
Gwendal Roué cdec1a4318 Remove ImmediateValueReducer 2019-06-09 11:43:21 +02:00
Gwendal Roué 3971058dd8 Hide request from DatabaseValue reducers 2019-06-08 17:28:01 +02:00
Roberto Casula b6f988194c fix errors for Xcode 11 beta 2019-06-08 15:46:48 +02:00
Gwendal Roué ad24bd8021 RawValueReducer is an ImmediateValueReducer 2019-06-08 14:07:29 +02:00
Gwendal Roué 096096684e SPM requires Swift 5: don't test Xcode 10.1 and 10 2019-06-07 07:35:00 +02:00
Gwendal Roué 038a8d2d88 SPM requires Swift 5 2019-06-06 21:06:43 +02:00
Gwendal Roué 5abd21fa4a swift-tools-version:5.0 2019-06-06 21:01:52 +02:00
Gwendal Roué a80d6731a8 swift-tools-version:5.0 2019-06-06 20:57:08 +02:00
Gwendal Roué e7ed67d41d Introduce ImmediateValueReducer 2019-06-06 20:05:25 +02:00
Gwendal Roué da042eaae9 Clean up ValueObservation fetching system 2019-06-06 19:56:41 +02:00
Gwendal Roué 416d2cae1e Make sure ValueObservation.combine results can be splatted 2019-06-06 19:08:22 +02:00
Gwendal Roué ac85ffff84 Database.readOnly is reentrant 2019-06-06 18:58:44 +02:00
Gwendal Roué e3d2559b9d Add tests for combining up to 8 ValueObservation 2019-06-05 08:58:42 +02:00
Gwendal Roué c1a926e6dc Combine up to 8 ValueObservation 2019-06-05 08:39:38 +02:00
Gwendal Roué b31f46cbc0 Cleanup 2019-06-05 08:31:20 +02:00
Gwendal Roué 6b236ceb5c Import ValueObservation combine reducers from #541 2019-06-05 08:14:36 +02:00
Gwendal Roué 30812792df Merge branch 'development' into dev/SQLite-3.28.0
# Conflicts:
#	CHANGELOG.md
2019-06-04 18:46:07 +02:00
Gwendal Roué c1cbe51747 Merge pull request #542 from groue/dev/FetchRequest-cleanup
Move eager loading of hasMany associations to FetchRequest
2019-06-04 18:41:27 +02:00
Gwendal Roué 1416c6e179 CHANGELOG 2019-06-01 17:20:20 +02:00
Gwendal Roué 91ff9ce0b8 Documentation 2019-06-01 17:16:04 +02:00
Gwendal Roué 5099305257 Documentation 2019-06-01 17:11:09 +02:00
Gwendal Roué 92c13c3ea8 Documentation 2019-06-01 17:01:42 +02:00
Gwendal Roué 872f394339 Move eager loading of hasMany associations to FetchRequest 2019-06-01 16:08:05 +02:00
Gwendal Roué deaf60263d TODO 2019-05-31 08:44:54 +02:00
Gwendal Roué 7e53901544 New example of record definition 2019-05-31 08:19:25 +02:00
Gwendal Roué ce95590b8a New example of record definition 2019-05-31 07:59:33 +02:00
Gwendal Roué c42cf38fc2 TODO 2019-05-30 20:32:18 +02:00
Gwendal Roué dc4a66fe2c Changelog 2019-05-30 14:10:47 +02:00
Gwendal Roué c9ab5eb551 Update SQLite version in documentation 2019-05-30 14:10:40 +02:00
Gwendal Roué 4e33b06f0b Wait for https://github.com/swiftlyfalling/SQLiteLib/pull/41 to be merged 2019-05-30 14:03:30 +02:00
Gwendal Roué ff45864454 Merge pull request #539 from groue/dev/JoinableRequest
Expose joining methods of both requests and associations
2019-05-30 08:50:05 +02:00
Gwendal Roué fb3c722724 Merge branch 'development' into dev/JoinableRequest
# Conflicts:
#	CHANGELOG.md
2019-05-29 20:04:54 +02:00
Gwendal Roué 6c93e1509d Merge pull request #538 from Timac/#530
Add FAQ to clarify "Wrong number of statement arguments" error with "like '%?%'"
2019-05-29 19:59:27 +02:00
Gwendal Roué 0680e5abd7 Thank you notice 2019-05-29 19:55:32 +02:00
Gwendal Roué aefaa86302 CHANGELOG 2019-05-29 19:54:40 +02:00
Gwendal Roué ed509c5349 Merge branch 'development' into #530 2019-05-29 19:50:40 +02:00
Gwendal Roué 0232c8e792 Slight rewriting: focus on what's wrong, and provide a single fix because choices are complicated 2019-05-29 19:48:33 +02:00
Gwendal Roué cba1113a03 Wording 2019-05-29 19:27:04 +02:00
Gwendal Roué 1b4c3808d1 CHANGELOG 2019-05-29 19:23:09 +02:00
Gwendal Roué ac583e8fdf Fix link 2019-05-29 19:18:23 +02:00
Gwendal Roué fff7d1c49e Rewrite the request chapter 2019-05-29 19:17:09 +02:00
Gwendal Roué 0fe96619bf Layout 2019-05-29 14:13:04 +02:00
Gwendal Roué 0440736f3b The case of singletons 2019-05-29 14:08:48 +02:00
Gwendal Roué 35e1aeb7a8 The case of singletons 2019-05-29 14:07:03 +02:00
Gwendal Roué 8fe3b18121 Remove ambiguity 2019-05-29 14:00:22 +02:00
Gwendal Roué 26259ef0f9 didInsert(with:for:) is not always well understood 2019-05-29 13:58:56 +02:00
Gwendal Roué fb9244e5bb Foster DerivableRequest in GoodPracticesForDesigningRecordTypes.md 2019-05-29 13:48:06 +02:00
Gwendal Roué 03d9727f61 Add tests for joining methods added on DerivableRequest 2019-05-29 09:00:28 +02:00
Gwendal Roué e7a590b82b Extract joining methods to the JoinableRequest protocol 2019-05-29 08:36:55 +02:00
Gwendal Roué 1b5e94a050 Merge branch 'master' into development 2019-05-29 08:14:44 +02:00
Alexandre Colucci 3669fadecb Provide one example that lets Swift build the pattern and an example with the query interface. Then provide the second approach using the || operator. 2019-05-28 22:53:33 +02:00
Alexandre Colucci 7ed4b799b7 Use an SQLite query with the correct GRDB style 2019-05-28 22:51:29 +02:00
Alexandre Colucci bba9d42433 Remove the line "[? as a parameter]" in the "Good to Know" section 2019-05-28 22:41:28 +02:00
Gwendal Roué 6a5d3fe85b Update the List of Record Methods 2019-05-28 20:15:09 +02:00
Gwendal Roué 957d7b4c86 Update the List of Record Methods 2019-05-28 20:11:51 +02:00
Gwendal Roué 2dd5058878 Update the List of Record Methods 2019-05-28 19:46:21 +02:00
Gwendal Roué a02bbc5748 Update the List of Record Methods 2019-05-28 19:43:15 +02:00
Gwendal Roué bef13a7d0e Update the List of Record Methods 2019-05-28 19:41:51 +02:00
Gwendal Roué b0e140d4bb Add two safety tests for parenthesis 2019-05-28 08:03:33 +02:00
Alexandre Colucci ca9ecd7f66 #530: Wrong number of statement arguments with "like '%?%'"
- Rewrite the paragraph as an FAQ
- Explicitly mention the error "Wrong number of statement arguments" and give an example causing such issue.
- Improve the wording and add a link to the SQLite documentation
2019-05-27 21:22:55 +02:00
Gwendal Roué 4729405625 Merge branch 'master' into development 2019-05-27 18:24:03 +02:00
Gwendal Roué 7d92c665f0 Update link to migration guide 2019-05-27 18:23:37 +02:00
Gwendal Roué 4f4a5d92c7 Merge pull request #537 from groue/dev/remove-parenthesis
Remove useless parenthesis from generated SQL
2019-05-27 12:29:15 +02:00
Gwendal Roué 5bb54f0049 Less parenthesis in SQL interpolation 2019-05-27 07:59:11 +02:00
Gwendal Roué 543dfe9e69 CHANGELOG 2019-05-26 22:03:08 +02:00
Gwendal Roué 8b8722f376 Document that generated SQL can change without notice 2019-05-26 21:57:19 +02:00
Gwendal Roué 1d75863c9a Also turn SQLAssociationCondition SQL expression into an array 2019-05-26 21:46:19 +02:00
Gwendal Roué 6fa452b68c Fix joined(operator:) 2019-05-26 20:46:11 +02:00
Gwendal Roué ab000d7a4f Remove useless expression parenthesis from SQL 2019-05-26 20:08:13 +02:00
Gwendal Roué 680f3ad20c Nicer WHERE, HAVING and ON output 2019-05-26 15:32:00 +02:00
Gwendal Roué b6b1f9b3e8 Remove useless comment 2019-05-26 07:33:38 +02:00
Gwendal Roué 05a547f2df Fix typo 2019-05-26 07:21:36 +02:00
Gwendal Roué 1602a37d08 Small improvement 2019-05-26 06:22:28 +02:00
Gwendal Roué 49a7b2091c v4.0.1 2019-05-25 23:16:00 +02:00
Gwendal Roué bf94fc168e Merge pull request #534 from groue/dev/cocoapods-1.7.0
Support for CocoaPods 1.7.0
2019-05-25 23:09:08 +02:00
Gwendal Roué d2aea2e3a7 Wording 2019-05-25 20:20:03 +02:00
Gwendal Roué 0159d75b38 Wording 2019-05-25 20:10:43 +02:00
Gwendal Roué c8755a91e8 Wording 2019-05-25 20:01:25 +02:00
Gwendal Roué b0e4f286cb Wording 2019-05-25 19:59:58 +02:00
Gwendal Roué f641e2fc39 A wild comparison 2019-05-25 19:39:13 +02:00
Gwendal Roué 1402100d26 Link Good Practices for Designing Record Types from Why Adopt GRDB? 2019-05-25 19:03:31 +02:00
Gwendal Roué eda36829d0 CHANGELOG 2019-05-25 18:56:36 +02:00
Gwendal Roué 48017b2de2 Update tests for GRDB/SQLCipher 2019-05-25 18:55:09 +02:00
Gwendal Roué 862886fa0a Use CocoaPods 1.7.0 on Travis 2019-05-25 18:55:09 +02:00
Gwendal Roué 68221af5c3 Podspec swift_versions = ['4.2', '5'] 2019-05-25 18:55:09 +02:00
Gwendal Roué b3e547a347 Merge pull request #535 from groue/dev/record-good-practices
Update the Good Practices for Designing Record Types
2019-05-25 18:53:39 +02:00
Gwendal Roué 498c153be1 CHANGELOG 2019-05-25 18:50:28 +02:00
Gwendal Roué 7ed8168f11 Wording 2019-05-25 18:32:23 +02:00
Gwendal Roué 547fc98358 Wording 2019-05-25 18:28:28 +02:00
Gwendal Roué 6397d5757e Wording 2019-05-25 18:26:07 +02:00
Gwendal Roué 6d71f8b17c Relationship between view controllers and database managers 2019-05-25 18:18:53 +02:00
Gwendal Roué cafb329d6e Link to conventions 2019-05-25 17:44:42 +02:00
Gwendal Roué 071fdd3711 Improve Good Practices for Designing Record Types 2019-05-25 17:15:34 +02:00
Gwendal Roué 0cca73cdfc CHANGELOG 2019-05-25 08:41:23 +02:00
Gwendal Roué 31e59f3968 Merge pull request #533 from groue/dev/fix-has-many-through
Fix eager loading of HasManyThrough associations
2019-05-25 08:37:07 +02:00
Gwendal Roué d6e0dcafcb Fix two README typos 2019-05-25 08:35:56 +02:00
Gwendal Roué 203130da31 Test that merging of HasManyThrough happens on the pivot key 2019-05-24 19:02:15 +02:00
Gwendal Roué af4a83115b Ttest for parallel inclusion of hasManyThrough(_, through: hasOne, via: hasMany) 2019-05-24 18:56:54 +02:00
Gwendal Roué 0ad7d5e894 Fix failing test for parallel inclusion of hasManyThrough(_, through: belongsTo, via: hasMany) 2019-05-24 13:18:00 +02:00
Gwendal Roué 6e7a923d6e Failing test for parallel inclusion of hasManyThrough(_, through: belongsTo, via: hasMany) 2019-05-24 13:17:47 +02:00
Gwendal Roué d7d3f87921 Merge pull request #479 from groue/GRDB-4.0
GRDB 4.0
2019-05-23 19:39:32 +02:00
Gwendal Roué 3e7df8c774 Update badge name 2019-05-23 19:34:38 +02:00
Gwendal Roué db4598d881 performance tests update 2019-05-23 19:26:30 +02:00
Gwendal Roué 60312f63d7 v4.0.0 2019-05-23 18:56:22 +02:00
Gwendal Roué f54297d488 Make it possible to build GRDBDemo app on a (my) device 2019-05-23 14:21:59 +02:00
Gwendal Roué 4368c529fa Realm 3.15.0 2019-05-23 13:49:01 +02:00
Gwendal Roué bf40e77d9c stephencelis/SQLite.swift 0.12.0 2019-05-23 13:38:25 +02:00
Gwendal Roué 4ce4b2e0d1 Performance tests: updates for Swift 5.0.1 2019-05-23 13:36:51 +02:00
Gwendal Roué a3c86e343b Less @inlinable methods 2019-05-23 13:27:23 +02:00
Gwendal Roué 962ab13da9 TODO 2019-05-23 13:13:26 +02:00
Gwendal Roué 4085050e96 API diff 2019-05-23 08:56:26 +02:00
Gwendal Roué a80a2571f6 API diff 2019-05-23 08:52:34 +02:00
Gwendal Roué 2a43377079 API diff 2019-05-23 08:48:43 +02:00
Gwendal Roué 2a0bd93795 API diff 2019-05-23 08:42:31 +02:00
Gwendal Roué 05747a62ea API diff 2019-05-23 08:29:08 +02:00
Gwendal Roué e201dd21ac Enhance Inflections setup APIs 2019-05-23 08:23:30 +02:00
Gwendal Roué c04f3c7faa API diff 2019-05-23 07:34:17 +02:00
Gwendal Roué 83409e3dec API diff 2019-05-23 07:33:35 +02:00
Gwendal Roué def9997698 Reduce Travis coverage 2019-05-23 07:25:43 +02:00
Gwendal Roué bb7f4b2f86 Documentation diff 2019-05-22 23:35:26 +02:00
Gwendal Roué ee703142ce CHANGELOG 2019-05-22 23:16:59 +02:00
Gwendal Roué 324db50668 API diff 2019-05-22 23:04:21 +02:00
Gwendal Roué 2e84e11bfa API diff 2019-05-22 22:59:52 +02:00
Gwendal Roué 6062beb9f4 API diff 2019-05-22 22:58:05 +02:00
Gwendal Roué 1d8c924c4e API diff 2019-05-22 22:57:31 +02:00
Gwendal Roué 8b35343f3d API diff 2019-05-22 22:56:22 +02:00
Gwendal Roué 35ead1d4c1 API diff 2019-05-22 22:50:23 +02:00
Gwendal Roué 2c3e639f39 API diff 2019-05-22 22:49:28 +02:00
Gwendal Roué 0f9fb9a3e0 API diff 2019-05-22 22:48:27 +02:00
Gwendal Roué 567547a205 API diff 2019-05-22 22:44:54 +02:00
Gwendal Roué 9a28c0ae03 Fix a decoding error diagnostic 2019-05-22 22:28:13 +02:00
Gwendal Roué 82ccc121dd Cleanup 2019-05-22 22:25:24 +02:00
Gwendal Roué 472063c7c1 API diff 2019-05-22 22:25:15 +02:00
Gwendal Roué f23e41a866 Fix wrong Columns enums 2019-05-22 20:28:07 +02:00
Gwendal Roué faae864699 Query Interface code organization 2019-05-22 20:13:33 +02:00
Gwendal Roué d2b9137548 Stop fostering CodingKeys that adopt ColumnExpression. Expose Column(CodingKey) initializer instead 2019-05-22 13:42:26 +02:00
Gwendal Roué dec80ac300 Give a default name to the isEmpty aggregate 2019-05-22 13:19:47 +02:00
Gwendal Roué b471488a83 Documentation 2019-05-22 09:08:52 +02:00
Gwendal Roué 21d2df9ade New SQL interpolation "... \(tableOf: record) ..." (addresses #524) 2019-05-22 08:53:50 +02:00
Gwendal Roué 7461342089 Fix doc: Record Comparison only requires EncodableRecord conformance 2019-05-22 08:40:03 +02:00
Gwendal Roué e4498b2784 contains operator generates SQL equality test when collection contains a single element 2019-05-22 08:13:42 +02:00
Gwendal Roué 2734bd1266 Fix for Swift 4.2 2019-05-21 23:14:52 +02:00
Gwendal Roué 77a677296b Migration guide menu 2019-05-21 20:41:39 +02:00
Gwendal Roué c90560fda9 Documentation 2019-05-21 20:35:13 +02:00
Gwendal Roué f5be0e176d Fix failing test for observation of QueryInterfaceRequest with prefetched rows 2019-05-21 20:27:08 +02:00
Gwendal Roué 9691adc0bb Failing test for observation of QueryInterfaceRequest with prefetched rows 2019-05-21 20:26:30 +02:00
Gwendal Roué b1c953c536 Better error reporting for missing scopes or prefetched rows 2019-05-21 19:56:55 +02:00
Gwendal Roué 059ae19974 QueryInterfaceRequest unconditionnally conforms to TableRequest 2019-05-21 19:18:26 +02:00
Gwendal Roué 65c6360d0c Fix typo and add a TODO 2019-05-21 19:02:01 +02:00
Gwendal Roué 25526472b3 Test Xcode 10.2 with Travis 2019-05-21 09:01:51 +02:00
Gwendal Roué a4a26e01e7 SelectionRequest.annotated(with:) 2019-05-21 08:05:07 +02:00
Gwendal Roué e163b91cf0 Merge pull request #525 from groue/feature/including-all
Eager Loading of HasMany associations
2019-05-21 07:35:03 +02:00
Gwendal Roué c19b3ad305 Documentation 2019-05-20 20:19:30 +02:00
Gwendal Roué 6628c09db7 Documentation 2019-05-20 20:17:34 +02:00
Gwendal Roué 7674f2f522 Association prefetching: add support for composite foreign keys 2019-05-20 19:35:50 +02:00
Gwendal Roué c841120d3b Cleanup 2019-05-20 19:18:27 +02:00
Gwendal Roué 81476e58b8 Improve SQLAssociationKey documentation 2019-05-20 19:03:57 +02:00
Gwendal Roué 69baff31ef Remove a hack: merging hasMany and hasManyThrough with include(all:) is simply not supported yet 2019-05-20 19:03:43 +02:00
Gwendal Roué 6f6a8e3c3b Migration Guide: Associations 2019-05-20 14:31:55 +02:00
Gwendal Roué 403e5ab058 Fix SPM tests 2019-05-20 14:29:54 +02:00
Gwendal Roué bc1e74a73e Migration Guide: Associations 2019-05-20 14:25:56 +02:00
Gwendal Roué 1fdd0bc428 Migration Guide: fix links 2019-05-20 14:22:27 +02:00
Gwendal Roué 940e9c3871 Migration Guide: Associations 2019-05-20 14:21:29 +02:00
Gwendal Roué 844fb3ca8b Fix iOS9 test 2019-05-20 12:15:50 +02:00
Gwendal Roué 721fd52d12 Association documentation 2019-05-20 11:56:49 +02:00
Gwendal Roué 85a86424c9 Association documentation 2019-05-20 11:54:49 +02:00
Gwendal Roué 7d4306d383 Association documentation 2019-05-20 11:53:42 +02:00
Gwendal Roué 96780419e9 Association documentation 2019-05-20 11:50:15 +02:00
Gwendal Roué 332f42bba3 English table names is recommended 2019-05-20 11:46:48 +02:00
Gwendal Roué bab21d4c59 CHANGELOG 2019-05-20 08:14:05 +02:00
Gwendal Roué 2c7b3e7667 Association documentation 2019-05-20 07:55:59 +02:00
Gwendal Roué 30839bd19d Association documentation 2019-05-20 07:54:36 +02:00
Gwendal Roué 304fdabd88 Association documentation 2019-05-20 07:31:27 +02:00
Gwendal Roué fde53b13c6 Association documentation 2019-05-20 07:28:59 +02:00
Gwendal Roué 62557343a1 Restore the Convention for Database Table Names chapter 2019-05-20 07:25:43 +02:00
Gwendal Roué 4b565ae262 Association documentation 2019-05-20 06:22:07 +02:00
Gwendal Roué 64bcbde1ab Association documentation 2019-05-20 06:17:30 +02:00
Gwendal Roué 76891a351d Association documentation 2019-05-20 06:14:35 +02:00
Gwendal Roué b29b5215b9 Character.uppercased() and lowercased() come with the Swiift 5 compiller 2019-05-20 06:12:51 +02:00
Gwendal Roué 507d603a4e At last 2019-05-19 23:44:27 +02:00
Gwendal Roué a38850ab00 Association documentation 2019-05-19 23:40:34 +02:00
Gwendal Roué 6af4b180df Association documentation 2019-05-19 23:31:54 +02:00
Gwendal Roué 8f3036b090 Association documentation 2019-05-19 22:42:38 +02:00
Gwendal Roué 8fd4108463 Association documentation 2019-05-19 22:11:30 +02:00
Gwendal Roué 40260c2316 Association documentation 2019-05-19 20:59:16 +02:00
Gwendal Roué 7268085692 Association documentation 2019-05-19 20:54:14 +02:00
Gwendal Roué 5f3b879efd Association documentation and tests 2019-05-19 20:27:13 +02:00
Gwendal Roué 5b15a88974 Fix HasManyThrough row scopes 2019-05-19 19:59:28 +02:00
Gwendal Roué 95c7c10f35 Association documentation 2019-05-19 19:06:37 +02:00
Gwendal Roué d5943962b3 Documentation: associations no longer need a convention for database table names 2019-05-19 18:58:38 +02:00
Gwendal Roué ada6002c91 Cleanup 2019-05-19 18:50:13 +02:00
Gwendal Roué 09afd2fadf Tests for singularization of hasMany relationship 2019-05-19 18:20:55 +02:00
Gwendal Roué 4f17444a7e Cleanup 2019-05-19 17:38:15 +02:00
Gwendal Roué 87b77768ec Documentation 2019-05-19 17:18:37 +02:00
Gwendal Roué fe0198f453 Cleanup 2019-05-19 16:22:39 +02:00
Gwendal Roué ae6a224122 Documentation 2019-05-19 16:08:29 +02:00
Gwendal Roué 73773358c9 Tests for non-inflected singular 2019-05-19 16:06:36 +02:00
Gwendal Roué 8e2a8fe9d8 More Associations and inflections 2019-05-19 15:03:54 +02:00
Gwendal Roué a1b0baaca9 leaf, foot, hero 2019-05-19 13:55:38 +02:00
Gwendal Roué 15dd4fc477 Inflections Cleanup 2019-05-19 13:36:29 +02:00
Gwendal Roué 52add837e5 More inflections 2019-05-19 13:06:56 +02:00
Gwendal Roué 637c94b265 Pluralize/Singularize last word 2019-05-19 08:38:11 +02:00
Gwendal Roué ca76032b8b Association name is turned into singularized or pluralized keys 2019-05-19 07:33:18 +02:00
Gwendal Roué 35027a825f Add Rails license 2019-05-18 20:19:18 +02:00
Gwendal Roué 98a7f94248 Cleanup 2019-05-18 20:09:03 +02:00
Gwendal Roué cdcaaa4b77 Irregularity 2019-05-18 19:49:30 +02:00
Gwendal Roué d2c33715d0 String.pluralized, String.singularized 2019-05-18 19:48:51 +02:00
Gwendal Roué 5113d08ce3 AssociationPrefetchingSQLTests: no need for association keys 2019-05-18 16:02:00 +02:00
Gwendal Roué cd53e0102b Simplify PrefetchedRowsDecoder 2019-05-18 15:53:06 +02:00
Gwendal Roué c95e9fafb1 Cleanup 2019-05-18 15:43:57 +02:00
Gwendal Roué 1a368d30b0 Cleanup 2019-05-18 15:03:17 +02:00
Gwendal Roué ebd393f52a Cleanuo 2019-05-18 14:18:35 +02:00
Gwendal Roué 27cbe18c51 Pass tests for database region of prefetching requests 2019-05-18 14:09:00 +02:00
Gwendal Roué 670bca00b0 Failing tests for database region of prefetching requests 2019-05-17 18:23:28 +02:00
Gwendal Roué 2a85d89364 Cleanup 2019-05-17 18:16:01 +02:00
Gwendal Roué c5ac0ea941 Cleanup 2019-05-17 18:13:32 +02:00
Gwendal Roué d23f4c3ac7 Prevent fetching cursor of prefetched rows with a "Not implemented" fatal error 2019-05-17 18:10:26 +02:00
Gwendal Roué 604a51bb79 Cleanup 2019-05-17 17:58:57 +02:00
Gwendal Roué 3786482368 Add unordered() to OrderedRequest 2019-05-17 17:53:25 +02:00
Gwendal Roué f98502a136 Association: remove pivot/destination relation ambiguity 2019-05-17 17:24:02 +02:00
Gwendal Roué 7703741f25 Cleanup 2019-05-17 17:10:26 +02:00
Gwendal Roué 5f36b43441 Tests for Row.debugDescription with prefetched rows 2019-05-17 16:55:25 +02:00
Gwendal Roué eb977e9391 Make Row.PrefetchedView order predictible 2019-05-17 16:53:43 +02:00
Gwendal Roué ad1bdd7f01 Rename Row.prefetches to Row.prefetchedRows 2019-05-17 14:08:33 +02:00
Gwendal Roué c1ed3aa094 Better error messages 2019-05-17 13:46:54 +02:00
Gwendal Roué 901015368c Failing tests for copied prefetched rows 2019-05-17 13:42:58 +02:00
Gwendal Roué ae18041861 Pass tests for prefetched rows and equality check 2019-05-17 08:58:35 +02:00
Gwendal Roué a6d348fc57 Failing tests for prefetched rows and equality check 2019-05-17 08:58:29 +02:00
Gwendal Roué 70b948b1c8 Row subscript accepts any RangeReplaceableCollection 2019-05-16 22:30:35 +02:00
Gwendal Roué 8038a9db05 Tests for consumption of prefetched rows into sets 2019-05-16 22:21:52 +02:00
Gwendal Roué 3337e49f64 Tests for consumption of prefetched rows into FetchableRecord 2019-05-16 22:02:02 +02:00
Gwendal Roué 67ec70a117 Row prefetch subscript 2019-05-16 22:00:30 +02:00
Gwendal Roué c4be3e527d Split AssociationPrefetchingTests.swift 2019-05-16 20:35:03 +02:00
Gwendal Roué f5177a5612 Cleanup 2019-05-16 19:54:00 +02:00
Gwendal Roué d18c00231e Remove Swift 5 migration warning 2019-05-16 19:44:56 +02:00
Gwendal Roué 644064aa08 More tests for consumption of prefetched rows into Decodable records 2019-05-16 19:44:43 +02:00
Gwendal Roué 881bb45fae More tests for consumption of prefetched rows into Decodable records 2019-05-16 19:35:24 +02:00
Gwendal Roué 46b7618f38 More tests for consumption of prefetched rows into Decodable records 2019-05-16 19:21:12 +02:00
Alexandre Colucci 490a124cbf #530: Wrong number of statement arguments with "like '%?%'"
Add "? as a parameter" in the "Good to Know" section to explain how to build like pattern like '%?%'.
2019-05-14 08:59:41 +02:00
Gwendal Roué a7ea0913fa Fix SPM 2019-05-08 07:59:34 +02:00
Gwendal Roué c0616c6a26 More tests for consumption of prefetched rows into Decodable records 2019-05-07 08:37:39 +02:00
Gwendal Roué 9fc5cda92b Rename PrefetchesTreeView to PrefetchesView 2019-05-06 08:19:12 +02:00
Gwendal Roué 1c47f01e9a More tests for consumption of prefetched rows into Decodable records 2019-05-05 22:47:16 +02:00
Gwendal Roué 04ffc71dbb TODO 2019-05-05 22:35:37 +02:00
Gwendal Roué 2634a0918d More tests for consumption of prefetched rows into Decodable records 2019-05-05 22:00:41 +02:00
Gwendal Roué c7fed1c0b3 More tests for consumption of prefetched rows into Decodable records 2019-05-05 21:20:10 +02:00
Gwendal Roué 17e8df2d25 Tests for consumption of prefetched rows into Decodable records 2019-05-05 21:09:23 +02:00
Gwendal Roué 8786a60d31 More tests for consumption of prefetched rows 2019-05-05 20:31:56 +02:00
Gwendal Roué acb7432610 TODO 2019-05-05 20:23:23 +02:00
Gwendal Roué 560676a4bb More tests for consumption of prefetched rows 2019-05-05 19:54:15 +02:00
Gwendal Roué a45065c340 Fix failing tests for consumption of prefetched rows 2019-05-05 19:31:43 +02:00
Gwendal Roué bd0884503e Failing tests for consumption of prefetched rows 2019-05-05 18:19:19 +02:00
Gwendal Roué f6b2c7e9f3 More tests for consumption of prefetched rows 2019-05-05 17:46:05 +02:00
Gwendal Roué 814ed0e4f1 Fix failing tests for consumption of prefetched rows 2019-05-05 17:44:11 +02:00
Gwendal Roué 5eff7755fe More tests for consumption of prefetched rows 2019-05-05 17:37:05 +02:00
Gwendal Roué b1bcf637ab Fix failing tests for consumption of prefetched rows 2019-05-05 17:25:17 +02:00
Gwendal Roué f199dc3cbe Rubber duck debugging 2019-05-05 16:36:56 +02:00
Gwendal Roué 40b11f9f2f TODO: light HasManyThrough 2019-05-05 16:36:22 +02:00
Gwendal Roué 8f678c94cc Failing tests for consumption of prefetched rows 2019-05-05 16:03:10 +02:00
Gwendal Roué 171cdcb36e More tests for consumption of prefetched rows 2019-05-05 15:37:25 +02:00
Gwendal Roué 1dce152f95 Introduce Row.prefetchTree 2019-05-05 15:26:40 +02:00
Gwendal Roué 90dd8d19bc More tests for consumption of prefetched rows 2019-05-05 15:10:55 +02:00
Gwendal Roué efe89f000d More tests for consumption of prefetched rows 2019-05-05 14:52:54 +02:00
Gwendal Roué 590f6c2b2a More tests for consumption of prefetched rows 2019-05-05 14:23:45 +02:00
Gwendal Roué 623f2eaf43 First tests for consumption of prefetched rows 2019-05-05 13:54:55 +02:00
Gwendal Roué 8d759898d3 Cleanup 2019-05-04 23:07:45 +02:00
Gwendal Roué 5fb6c40036 Almost ready to use prefetched rows 2019-05-04 22:54:10 +02:00
Gwendal Roué 91ec3bada3 Group prefetched rows 2019-05-04 22:29:07 +02:00
Gwendal Roué 217b7eee9f AssociationHasManyPrefetchingSQLTests cleanup 2019-05-04 22:04:22 +02:00
Gwendal Roué f1522c09b5 AssociationHasManyPrefetchingSQLTests cleanup 2019-05-04 22:00:37 +02:00
Gwendal Roué b00271ad80 AssociationHasManyPrefetchingSQLTests cleanup 2019-05-04 21:45:29 +02:00
Gwendal Roué d7b4cf364d More passing prefetch tests 2019-05-04 21:35:06 +02:00
Gwendal Roué 7ef5669710 More passing prefetch tests 2019-05-04 21:28:59 +02:00
Gwendal Roué 73d622a074 Don't prefetch when there is no row 2019-05-04 21:28:47 +02:00
Gwendal Roué ce782cecac More passing prefetch tests 2019-05-04 21:04:55 +02:00
Gwendal Roué a7431403a5 AssociationHasManyPrefetchingSQLTests cleanup 2019-05-04 20:39:56 +02:00
Gwendal Roué 4b82656d3a More passing prefetch tests 2019-05-04 17:20:56 +02:00
Gwendal Roué 2ca2f11883 First prefetch and passing tests 2019-05-04 17:02:19 +02:00
Gwendal Roué 1fbe7cfecf Type constraint: check Row equality, not subtyping 2019-05-04 17:01:23 +02:00
Gwendal Roué 331938c647 More including(all:) 2019-05-04 15:48:58 +02:00
Gwendal Roué 995657108d Not all relation children impact parent's count 2019-05-04 14:34:49 +02:00
Gwendal Roué f6a5279ac9 Use "join" for actual SQL joins, and refactor SQLRelation around "children" 2019-05-04 14:15:53 +02:00
Gwendal Roué a88f20fb50 Introduce including(all:) 2019-05-04 12:24:43 +02:00
Gwendal Roué cfb1b2fc4d QueryInterfaceRequest is not a FetchRequest like others: it will prefetch 2019-05-04 12:20:36 +02:00
Gwendal Roué 0e2daff329 More Association cleanup 2019-05-04 12:17:47 +02:00
Gwendal Roué 18bd025e1c SQLAssociation clarification 2019-05-03 20:32:21 +02:00
Gwendal Roué dd87a8d42c SQLAssociation clarification 2019-05-03 20:16:05 +02:00
Gwendal Roué 96c10f017e TODO 2019-05-02 20:38:24 +02:00
Gwendal Roué 95ccb511db Fix typo 2019-05-02 20:38:15 +02:00
Gwendal Roué 820db3f07d Refactor SQLAssociation
# Conflicts:
#	GRDB/QueryInterface/Association/Association.swift
2019-05-02 20:34:10 +02:00
Gwendal Roué 1317dc5db0 Fix typo 2019-04-28 16:34:45 +02:00
Gwendal Roué 76971c44f6 Merge pull request #521 from groue/feature/join-condition-cleanup
Associations: join condition cleanup
2019-04-28 16:29:58 +02:00
Gwendal Roué 708538bcf0 Refactor join conditions 2019-04-28 14:46:20 +02:00
Gwendal Roué 1e3de49251 Rename SQLJoin.Condition to SQLJoinCondition 2019-04-28 13:25:56 +02:00
Gwendal Roué 73f4a9fb23 whitespace 2019-04-28 13:23:53 +02:00
Gwendal Roué aec26c66be Merge pull request #519 from Lutzifer/patch-1 2019-04-26 12:06:56 +02:00
Wolfgang Lutz 8fcabb5b73 fix typos in documentation 2019-04-26 11:50:22 +02:00
Gwendal Roué 9090c54c93 Migrating From GRDB 3 to GRDB 4 2019-04-24 13:50:49 +02:00
Gwendal Roué 425debd0db Migrating From GRDB 3 to GRDB 4 2019-04-24 13:39:08 +02:00
Gwendal Roué f335005efd Migrating From GRDB 3 to GRDB 4 2019-04-24 13:30:55 +02:00
Gwendal Roué 8084e83760 Migrating From GRDB 3 to GRDB 4 2019-04-24 13:28:54 +02:00
Gwendal Roué bdbcf682c4 Merge pull request #517 from groue/SQLCipher-4
Support for SQLCipher 4
2019-04-22 17:03:01 +02:00
Gwendal Roué 29188a0606 CHANGELOG 2019-04-21 14:21:21 +02:00
Gwendal Roué fba553bbb9 Fix typo 2019-04-21 14:00:08 +02:00
Gwendal Roué 2932b72200 Update documentation for SQLCipher and raw SQLite pointers 2019-04-21 13:56:13 +02:00
Gwendal Roué e6bbdeab2c SQLCipher installation documentation 2019-04-21 13:51:03 +02:00
Gwendal Roué c37ccb6448 Test for PRAGMA cipher_compatibility 2019-04-21 13:46:05 +02:00
Gwendal Roué 330005596a Carthage: don't beat around the bush 2019-04-21 13:08:40 +02:00
Gwendal Roué a336cf6ca4 Drop obsolete documentation 2019-04-21 13:04:07 +02:00
Gwendal Roué 801e8bb23c Remove remaining references to Carthage 2019-04-21 13:03:28 +02:00
Gwendal Roué 235ce0aba2 Remove remaining references to GRDBCipher 2019-04-21 13:01:54 +02:00
Gwendal Roué 2a72d08334 Restore Database.logError 2019-04-21 12:59:12 +02:00
Gwendal Roué 6b04996290 Remove remaining references to GRDBCipher 2019-04-21 12:55:24 +02:00
Gwendal Roué d2b65d9fb8 Travis 2019-04-21 12:47:26 +02:00
Gwendal Roué 1b9a1d3e30 SQLCipher tests: don't sign code 2019-04-20 22:03:48 +02:00
Gwendal Roué 5730dd5414 Refactor Makefile and .travis.yml for new SQLCipher tests 2019-04-20 20:44:52 +02:00
Gwendal Roué 322039d490 Drop GRDBCipher project 2019-04-20 20:24:34 +02:00
Gwendal Roué c0c2a40c22 SQLCipher3 tests 2019-04-20 20:15:45 +02:00
Gwendal Roué 7d50825bff SQLCipher4 tests 2019-04-20 20:10:50 +02:00
Gwendal Roué da55d09960 Travis cleanup - and disable flaky Carthage test nobody cares about 2019-04-20 16:40:33 +02:00
Gwendal Roué f9b0af5f7b Remove obsolete make test_CocoaPodsLint_GRDBCipher 2019-04-20 16:24:14 +02:00
Gwendal Roué d1fa479b31 Ignore test Podfile.lock 2019-04-20 16:10:29 +02:00
Gwendal Roué 6b3f2e844c Fix make test_install_GRDBCipher_CocoaPods 2019-04-20 16:06:25 +02:00
Gwendal Roué 9370036baf make test_install_GRDBCipher is obsolete 2019-04-20 16:05:44 +02:00
Gwendal Roué 95274c57dd SQLCipher 4: adapt tests for past-error Cursor.next() 2019-04-20 15:32:01 +02:00
Gwendal Roué e55a5bd1d0 SQLCipher can't backup encrypted databases 2019-04-20 15:29:43 +02:00
Gwendal Roué 97173dea60 Fix Xcode 10.2.1 warnings 2019-04-20 14:49:43 +02:00
Gwendal Roué 7e3e91ac99 Update Makefile for SQLCipher via CocoaPods 2019-04-20 11:08:43 +02:00
Gwendal Roué 1c1ee4e92a GRDBCipher is no longer. Long live GRDB.swift/SQLCipher. 2019-04-19 13:11:55 +02:00
Gwendal Roué 1e06ff24ec cocoapods ~> 1.6 2019-04-19 08:49:24 +02:00
Gwendal Roué ba91a79798 Instruct Travis to honor Gemfile 2019-04-19 08:41:11 +02:00
Gwendal Roué 3c977d7bf8 Add cocapods to the Travis gems 2019-04-19 08:36:55 +02:00
Gwendal Roué 261e9481b2 Fix share schemes 2019-04-19 08:33:19 +02:00
Gwendal Roué 1f50b4fefe Integrate SQLCipher as a CocoaPod 2019-04-19 08:33:19 +02:00
Gwendal Roué cbb1b27830 Delete SQLCipher/src submodule 2019-04-19 08:33:19 +02:00
Gwendal Roué bdf8d0bcd5 Merge pull request #515 from alextrob/feature/fetchOne-limit-1
Add "LIMIT 1" to `fetchOne` requests
2019-04-18 07:04:56 +02:00
Gwendal Roué 5af1686677 Thank you notice 2019-04-18 07:02:42 +02:00
Gwendal Roué 2711b9bb04 Merge branch 'GRDB-4.0' into feature/fetchOne-limit-1 2019-04-18 07:01:03 +02:00
Gwendal Roué a172473e37 CHANGELOG 2019-04-17 21:35:23 +02:00
Gwendal Roué 3f8047fc0e Tests for the singleResult hint and SQLRequest.init(_:request:) 2019-04-17 21:32:47 +02:00
Gwendal Roué a12830050b Tests for the singleResult hint and databaseRegion 2019-04-17 21:32:13 +02:00
Gwendal Roué 21c0175a71 Tests for the singleResult hint and fetchCount 2019-04-17 21:31:53 +02:00
Gwendal Roué 65fe2bb50c Tests for the singleResult hint and fetching methods 2019-04-17 21:31:30 +02:00
Gwendal Roué e3a0935914 Add SQL tests for all record testFetchOne…() methods
We usually update all those tests together
2019-04-17 14:01:16 +02:00
Gwendal Roué 693e6da773 Do not test that fetchOne does not add LIMIT 1 to raw SQL requests
We do not add LIMIT 1 to raw SQL requests because it is difficult. But it would not be wrong to do so.
2019-04-17 13:08:51 +02:00
Gwendal Roué 4716f91d8b Bake the single result expectation right into filter(key:) methods
This better hides this flag inside SQLSelectQuery, and avoids explicit support from FetchableRecord and TableRecord
2019-04-16 08:47:50 +02:00
Gwendal Roué 46791c8f74 Remove QueryInterfaceRequest.init(query:) 2019-04-16 07:56:44 +02:00
Alex Robinson 1b3f0e8ece Update FetchRequest protocol in README 2019-04-16 11:11:37 +10:00
Alex Robinson e2211aca21 Exclude LIMIT 1 in more cases
Adds a flag to SQLSelectQuery indicating that it expects a single record (for example when querying by primary or unique key).

Ensures that this example doesn't add an unnecessary LIMIT 1 to the resulting query:

    let request = Player.filter(key: 123) // or Player.filter(key: ["email": "me@example.com"])
    let player = try dbQueue.read { db in try request.fetchOne(db) }
2019-04-16 11:10:43 +10:00
Alex Robinson 235a612ce0 Remove LIMIT 1 from expected SQL when filtering by key
Tests now fail
2019-04-16 10:29:40 +10:00
Alex Robinson 7070dedf1a Replace FetchRequestHint with a boolean for single results
Fixes previous test failure
2019-04-16 10:20:36 +10:00
Alex Robinson 20aecd5328 Add failing test for fetchOne with a non-zero offset 2019-04-16 10:20:36 +10:00
Gwendal Roué 1af55653d3 Fix typo 2019-04-13 17:06:41 +02:00
Gwendal Roué 9efc20fa51 Association: introduce request(for:) before using it 2019-04-13 13:55:15 +02:00
Gwendal Roué f847be98f5 Associations: aggregates are available on HasManyThrough, too 2019-04-13 13:48:12 +02:00
Gwendal Roué ff00dabcd1 Associations documentation 2019-04-13 13:46:28 +02:00
Gwendal Roué 72f00ccd9a Associations: delay introduction of request(for:) 2019-04-13 13:34:34 +02:00
Gwendal Roué 5995f468e3 Associations: improve "Required Protocols" chapter 2019-04-13 06:55:28 +02:00
Gwendal Roué 023afce21b Put #514 in TODO 2019-04-11 08:31:16 +02:00
Gwendal Roué 9b24671043 Disable #514 failing tests 2019-04-11 08:14:04 +02:00
Alex Robinson 088f6c92c7 Update inline docs 2019-04-11 13:50:57 +10:00
Alex Robinson 207b90f1b5 Update FetchRequest protocol in README 2019-04-11 13:27:32 +10:00
Alex Robinson dd139b6268 Fix testing lastSQLQuery when a cursor hasn't retrieved a record
This problem was masked by the fact all queries in the test expected the same SQL query.
2019-04-11 13:19:04 +10:00
Alex Robinson 072fa2583a Add hints for use in request preparation
Hints are ignored by SQLRequest. When you write raw SQL you probably don't want GRDB to modify your query.
2019-04-11 13:14:41 +10:00
Alex Robinson af1fd6b90c More tests for presence of LIMIT 1 2019-04-11 13:08:29 +10:00
Alex Robinson f9868bd8b5 Update tests to expect "LIMIT 1" where appropriate
Tests currently fail
2019-04-11 11:51:16 +10:00
Gwendal Roué 00ae2de14e Another failing test for #514 2019-04-10 19:54:44 +02:00
Gwendal Roué a6cbd242e6 Add a failing test forr #514 2019-04-10 19:29:50 +02:00
Gwendal Roué be950162d0 Merge pull request #508 from michaelkirk-signal/mkirk/GRDB-4.0-sqlcipher-cipher_compatibility
Allow Database Connection Configuration
2019-04-10 13:47:03 +02:00
Gwendal Roué db34d9537b Remove more useless failing tests 2019-04-10 07:49:06 +02:00
Gwendal Roué 1682df5c4e Thank you notice 2019-04-09 20:26:28 +02:00
Gwendal Roué 3ca7647110 Merge branch 'GRDB-4.0' into mkirk/GRDB-4.0-sqlcipher-cipher_compatibility
# Conflicts:
#	CHANGELOG.md
2019-04-09 20:25:22 +02:00
Gwendal Roué 2c4a449c5b Fix prepareDatabase sample code and markdown layout 2019-04-09 20:23:08 +02:00
Gwendal Roué 49d92dc6ce Three slashes for documentation comment 2019-04-09 20:21:34 +02:00
Gwendal Roué d52fcbe0c9 Fixits for Configuration.cipherPageSize and kdfIterations 2019-04-09 20:21:17 +02:00
Gwendal Roué 5bf54dc5c9 Update README for cipher_page_size and kdf_iter SQLCipher pragmas 2019-04-09 20:15:46 +02:00
Gwendal Roué 0a814ee1e7 CHANGELOG 2019-04-09 20:04:20 +02:00
Gwendal Roué 94316540de Remove useless failing tests
They were failing because database initialization now uses high level methods which throw detailed errors.
2019-04-09 20:01:22 +02:00
Gwendal Roué b67a53e645 whitespace 2019-04-09 19:57:22 +02:00
Gwendal Roué a0f37c6e85 Simplify Database.validateFormat() 2019-04-09 19:56:01 +02:00
Gwendal Roué 82dc51c554 Document prepareDatabase call site
Because it willl be easy to forget the context of #508 when we read this code in the future
2019-04-09 19:55:45 +02:00
Gwendal Roué 6115078e95 Simplify Database.validateSQLCipher() 2019-04-09 19:46:58 +02:00
Gwendal Roué 8d35330e12 whitespace 2019-04-09 19:40:27 +02:00
Gwendal Roué e0e07a7454 Merge pull request #510 from signalapp/charlesmchen/tableRegionVisibility
Expose DatabaseRegion(table:) initializer
2019-04-09 19:31:57 +02:00
Gwendal Roué 7a42bb42f5 README: make DatabaseRegion documentation less detailed 2019-04-09 19:29:38 +02:00
Gwendal Roué 212290bbf9 Make DatabaseRegion documentation less detailed 2019-04-09 19:23:50 +02:00
Gwendal Roué 6f20d8b406 CHANGELOG 2019-04-09 19:17:24 +02:00
Matthew Chen 0561b7de5d Respond to CR. 2019-04-05 09:50:07 -04:00
Matthew Chen 9f41277bd4 Make more DatabaseRegion initializers public; elaborate docs. 2019-04-05 09:47:08 -04:00
Matthew Chen 9f4cad4134 Make DatabaseRegion initializer public to enable observation of tables. 2019-04-05 09:47:08 -04:00
Gwendal Roué bf012614bc CHANGELOG and thank you notice 2019-04-05 07:49:16 +02:00
Gwendal Roué aeeb59601a Merge pull request #511 from signalapp/charlesmchen/fixPoolNotificationName
Fix notification name.
2019-04-05 07:43:02 +02:00
Michael Kirk 747a6352d6 example docs 2019-04-04 16:03:30 -06:00
Matthew Chen 325b376f4c Fix notification name. 2019-04-04 18:01:12 -04:00
Michael Kirk dcc3db2730 Revert "update sqlcipher"
This reverts commit 26b8682e63.
2019-04-04 15:57:21 -06:00
Michael Kirk 29c1c5481c inline setupConnection, re-order method calls to call validateFormat later, convert static->instance methods where possible 2019-04-04 15:55:53 -06:00
Michael Kirk ebc7a9d8e0 fix #if scope 2019-04-04 15:42:19 -06:00
Michael Kirk 99065a4faf prepareDB block 2019-04-02 10:47:31 -06:00
Michael Kirk 26b8682e63 update sqlcipher 2019-03-31 14:27:46 -06:00
Gwendal Roué d41f6b4466 Makefile: support for Xcode 10.2 2019-03-28 07:08:18 +01:00
Gwendal Roué bfa5fbe8ce Documentation tweaks 2019-03-20 16:50:03 +01:00
Gwendal Roué 900134729a Where has count(where:) gone? 2019-03-16 15:31:00 +01:00
Gwendal Roué d888423676 Fix outdated documentation 2019-03-16 14:32:10 +01:00
Gwendal Roué eac38be34b Fix for Swift 5 2019-03-16 14:26:06 +01:00
Gwendal Roué f42a184401 Merge pull request #503 from groue/feature/aggregate-ifnull
IFNULL support for association aggregates
2019-03-15 13:06:56 +01:00
Gwendal Roué 5fbf56c373 KISS 2019-03-15 08:51:02 +01:00
Gwendal Roué 784ebcc8e9 Tighten SQLJoin 2019-03-15 08:41:57 +01:00
Gwendal Roué df84654554 Delete unused code 2019-03-15 08:23:08 +01:00
Gwendal Roué 53e513f1f8 Merge branch 'GRDB-4.0' into feature/aggregate-ifnull
# Conflicts:
#	CHANGELOG.md
2019-03-15 07:58:42 +01:00
Gwendal Roué 0074adc023 Merge pull request #502 from groue/feature/rename-future
Rename Future to DatabaseFuture
2019-03-15 07:56:56 +01:00
Gwendal Roué ca8987ad98 Remove ill-advised TODOs 2019-03-14 07:57:30 +01:00
Gwendal Roué 6460f639ee Cleanup: SQLRelation, JoinOperator, JoinCondition are no longer public 2019-03-14 07:54:45 +01:00
Gwendal Roué 41d93f546c Document aggregate operations 2019-03-14 07:46:49 +01:00
Gwendal Roué 80a642260f CHANGELOG 2019-03-14 07:29:47 +01:00
Gwendal Roué 39800b1257 IFNULL support for aggregates 2019-03-14 07:21:09 +01:00
Gwendal Roué d04fc07337 CHANGELOG 2019-03-14 07:02:39 +01:00
Gwendal Roué 11fd8d6b87 Update documentation 2019-03-14 07:01:39 +01:00
Gwendal Roué 7183457217 Rename Future to DatabaseFuture 2019-03-14 06:43:40 +01:00
Gwendal Roué cf4e512894 Documentation 2019-03-13 21:24:54 +01:00
Gwendal Roué cf837855f2 HasManyThroughAssociation and HasOneThroughAssociation doc 2019-03-13 21:19:13 +01:00
Gwendal Roué 916d3931aa Cleanup SQLAssociation 2019-03-13 20:47:55 +01:00
Gwendal Roué 9d9bbc5f5d Documentation 2019-03-13 10:24:00 +01:00
Gwendal Roué 153233ace4 Documentation 2019-03-13 10:16:46 +01:00
Gwendal Roué 4bae8e9ac5 More request(for:association) tests 2019-03-13 08:33:14 +01:00
Gwendal Roué 1e617381a8 AssociationsBasics.md: remove inner link 2019-03-13 07:57:01 +01:00
Gwendal Roué 6d5215c8cb One less contribution needed #499 2019-03-11 09:02:48 +01:00
Gwendal Roué 4ce6271f6d Merge pull request #499 from groue/feature/EndodableRecord
Extract EncodableRecord from MutablePersistableRecord
2019-03-10 23:01:24 +01:00
Gwendal Roué 10c75d1e5e CHANGELOG 2019-03-10 15:25:39 +01:00
Gwendal Roué 05258b1098 Fix SPM build 2019-03-10 15:21:39 +01:00
Gwendal Roué 1a513e8e6e EncodableRecord documentation 2019-03-10 15:07:05 +01:00
Gwendal Roué 4ae1fb11cc Extract EncodableRecord from MutablePersistableRecord
This fixes issue #426
2019-03-10 14:00:01 +01:00
Gwendal Roué 9500a74744 Merge branch 'development' into GRDB-4.0
# Conflicts:
#	.travis.yml
#	CHANGELOG.md
#	GRDB/QueryInterface/SQLSelectQueryGenerator.swift
#	GRDB/Utils/OrderedDictionary.swift
#	README.md
2019-03-10 12:16:08 +01:00
Gwendal Roué 973e82b139 Fix a typo 2019-03-10 05:48:25 +01:00
Gwendal Roué d88fb4d96f Fix typo 2019-03-09 15:27:09 +01:00
Gwendal Roué cd6c4a4232 CHANGELOG 2019-03-09 15:11:48 +01:00
Gwendal Roué aeb41dc1eb v3.7.0 2019-03-09 14:21:28 +01:00
Gwendal Roué d2b2e12a10 Remove CHANGELOG.md requirement from PULL_REQUEST_TEMPLATE.md 2019-03-09 14:05:57 +01:00
Gwendal Roué 9040970c8d CHANGELOG 2019-03-09 14:04:49 +01:00
Gwendal Roué 211ac7aada Make Configuration.cipherPageSize an Int
As said in https://github.com/groue/GRDB.swift/issues/498#issuecomment-471156347
2019-03-09 13:38:28 +01:00
Gwendal Roué d60b68ab8a Document the BusyMode.timeout unit (#498) 2019-03-09 12:45:11 +01:00
Gwendal Roué 82423c41f2 Disable Travis check for CocoaPods GRDBCipher until we figure out what has turned wrong 2019-03-08 12:55:05 +01:00
Gwendal Roué 2b460083af GRDBPlus CocoaPod is deprecated 2019-03-08 12:52:17 +01:00
Gwendal Roué bad862ba16 Remove all mentions of GRDBPlus 2019-03-08 12:40:00 +01:00
Gwendal Roué adc4aa7c41 Merge pull request #497 from Marus/sqlcipher_config_options
Add additional SQLCipher configuration options
2019-03-08 08:40:39 +01:00
Gwendal Roué 53d2e6b895 Fix typo 2019-03-08 08:26:18 +01:00
Gwendal Roué c46dbdd97e Turn WARNING into a Note 2019-03-08 08:25:02 +01:00
Marcel Ball 6543d75f6d Updated based upon feedback from @groue
- Renamed `KDFIternations` to `kdfIterations` to better fit naming conventions
- In case of errors setting values return the sqlite error code and message instead of .SQLITE_MISUSE and a generic message
- Fixed formatting/typos in documentation
2019-03-07 17:51:16 -04:00
Gwendal Roué 32f6a45e8f SE-0209: support both swift 4.2 and 5 2019-03-07 20:54:42 +01:00
Gwendal Roué 519fa9a41a Don't codesign GRDBCipherMacOS test app 2019-03-07 18:34:19 +01:00
Gwendal Roué 7d0b5cf03c Don't codesign GRDBFTS5MacOS test app 2019-03-07 18:32:30 +01:00
Gwendal Roué 35ffe9a9fd Merge pull request #496 from groue/feature/fix-495
Fix crash when trying to perform fetchCount or ValueObservation.trackCount on joined query
2019-03-07 07:54:04 +01:00
Gwendal Roué b063870739 Too much future: firstIndex is not available on Xcode 9.4- 2019-03-07 05:06:58 +01:00
Marcel Ball 8ca9839433 Cleanup of some things leftover from debugging/testing 2019-03-06 21:31:37 -04:00
Marcel Ball 47f9b0f4a9 Added inline comments for new configuration options. 2019-03-06 21:21:43 -04:00
Marcel Ball 349ef328c7 Updated documentation to cover new configuration options 2019-03-06 21:01:08 -04:00
Marcel Ball 8415e8c2a0 Rename parameter to better align with the SQLCipher PRAGMA 2019-03-06 20:58:55 -04:00
Marcel Ball d4eb7ba27b Added configuration options to GRDBcipher for kdf_iterations 2019-03-06 20:41:38 -04:00
Marcel Ball 090eea9923 Update naming for the enumeration to be clearer 2019-03-06 20:41:01 -04:00
Gwendal Roué d566838dc5 Restore missing comment 2019-03-06 22:22:35 +01:00
Gwendal Roué 5bed0ac58e Too much future 2019-03-06 22:12:54 +01:00
Gwendal Roué ee481b2327 Fix #495 2019-03-06 22:09:31 +01:00
Gwendal Roué 8fbc3ca875 From future import OrderedDictionary 2019-03-06 22:09:01 +01:00
Gwendal Roué 4aecad3649 Failing test for https://github.com/groue/GRDB.swift/issues/495 2019-03-06 21:58:36 +01:00
Marcel Ball cf128ac800 Added configuration option to set cipher_page_size on connection
* Defaults to 1024 - which is the default in SQLCipher
2019-03-06 16:50:55 -04:00
Marcel Ball 1a51eb6b52 Merge pull request #2 from groue/development
Down merge changes from @groue
2019-03-06 16:41:30 -04:00
Gwendal Roué a355b9eb03 Merge pull request #490 from groue/feature/HasOneThroughAssociation
Indirect Associations
2019-03-06 21:40:47 +01:00
Gwendal Roué a3c2cb7f1c Merge branch 'GRDB-4.0' into feature/HasOneThroughAssociation 2019-03-06 18:58:05 +01:00
Gwendal Roué 4ba16067d0 Merge branch 'development' into GRDB-4.0 2019-03-06 18:57:06 +01:00
Gwendal Roué 605b6f7593 Merge branch 'master' into development 2019-03-06 18:55:07 +01:00
Gwendal Roué 43fff32156 Thank you notice for davidkraus :-) 2019-03-06 18:51:08 +01:00
Gwendal Roué 9f776a119f Merge pull request #494 from davidkraus/master
improve fts5 documentation
2019-03-06 18:49:10 +01:00
Gwendal Roué 658c9d34cb Remove GRDBPlus from ReleaseProcess.md 2019-03-06 18:43:21 +01:00
Gwendal Roué 2f447cc237 Wording and formatting 2019-03-06 18:42:45 +01:00
Gwendal Roué 403c4a894f Apply lovely advice from @glessard 2019-03-06 18:18:15 +01:00
David Kraus ccf339d6ef improve fts5 documentation 2019-03-06 14:55:11 +01:00
Gwendal Roué 7ff21981f0 Restore tests by disabling a sanity check 2019-03-06 09:08:59 +01:00
Gwendal Roué 5d9fa76754 Fix fetchCount(_:) for joined queries 2019-03-06 08:59:06 +01:00
Gwendal Roué bd633e25ee Aggregate tests for HasManyThroughAssociation 2019-03-06 08:17:47 +01:00
Gwendal Roué 87cd76a468 Association aggregates are defined on AssociationToMany 2019-03-06 08:17:20 +01:00
Gwendal Roué fca6420053 Documentation 2019-03-06 06:10:18 +01:00
Gwendal Roué ec51f4dbdf CHANGELOG 2019-03-05 18:54:06 +01:00
Gwendal Roué 916311a851 Remove outdated information 2019-03-05 18:51:58 +01:00
Gwendal Roué d6b6028e42 Typo fix 2019-03-05 18:49:51 +01:00
Gwendal Roué c756d27808 Documentation 2019-03-05 18:48:03 +01:00
Gwendal Roué 13985d0553 Merge branch 'GRDB-4.0' into feature/HasOneThroughAssociation 2019-03-05 18:40:12 +01:00
Gwendal Roué 0363ca406d Merge pull request #493 from groue/feature/SQLite-3.27.2
Bump SQLite to 3.27.2
2019-03-05 18:29:46 +01:00
Gwendal Roué c20b7e5799 Bump swiftlyfalling/SQLiteLib 2019-03-05 18:29:07 +01:00
Gwendal Roué 7642eb054b Documentation 2019-03-05 08:33:17 +01:00
Gwendal Roué f3c68420a0 CHANGELOG 2019-03-05 08:05:39 +01:00
Gwendal Roué 223ed4c73c Merge branch 'GRDB-4.0' into feature/SQLite-3.27.2 2019-03-05 08:00:53 +01:00
Gwendal Roué 99d010cded SQLite 3.27.2 2019-03-05 07:58:07 +01:00
Gwendal Roué 5bf1e6f818 Association documentation: contextualize schema recommendations 2019-03-04 20:37:47 +01:00
Gwendal Roué 06f0961b13 Association documentation: avoid painful repetition 2019-03-04 20:13:12 +01:00
Gwendal Roué addfa45d3a hasMany(_:through:using:) 2019-03-04 08:52:07 +01:00
Gwendal Roué 6489c80846 hasOne(_:through:using:) 2019-03-04 08:49:03 +01:00
Gwendal Roué 9e8e00ff99 AssociationHasManySQLTests 2019-03-04 08:06:50 +01:00
Gwendal Roué 9ee25fdec1 Rename ToOneAssociation to AssociationToOne 2019-03-04 08:01:45 +01:00
Gwendal Roué 4d5e5e1de3 HasManyThroughAssociation 2019-03-03 18:35:05 +01:00
Gwendal Roué 1188969144 Cleanup 2019-03-03 17:34:23 +01:00
Gwendal Roué 66c72e7bd2 HasOneThroughAssociation request tests 2019-03-03 15:29:27 +01:00
Gwendal Roué eed30c0954 AssociationHasOneThroughDecodableRecordTests 2019-03-03 09:21:49 +01:00
Gwendal Roué 8dd9f5fd40 AssociationHasOneThroughFetchableRecordTests cleanup 2019-03-03 09:21:34 +01:00
Gwendal Roué 7cab5dbf2b Cleanup 2019-03-02 20:42:52 +01:00
Gwendal Roué 6fd14d0a70 AssociationHasOneThroughFetchableRecordTests 2019-03-02 20:41:52 +01:00
Gwendal Roué 51c0b7a2f8 Renamed AssociationHasOneThroughRowscopeTests 2019-03-02 20:26:31 +01:00
Gwendal Roué 679f989e96 More AssociationHasOneThroughSQLDerivationTests 2019-03-02 17:35:00 +01:00
Gwendal Roué 1a24f61723 HasOneThroughAssociation adopts TableRequest 2019-03-02 17:24:17 +01:00
Gwendal Roué 1ff5552d5e AssociationHasOneThroughSQLDerivationTests 2019-03-02 17:14:58 +01:00
Gwendal Roué 4815807f09 More AssociationHasOneThroughSQLTests 2019-03-02 17:01:27 +01:00
Gwendal Roué 8fc23e1771 Complete AssociationHasOneThroughSQLTests 2019-03-02 15:48:17 +01:00
Gwendal Roué 5cf2d4920d TODO 2019-03-02 15:37:44 +01:00
Gwendal Roué 3d6d1c89b2 HasOneThroughAssociation 2019-03-02 14:46:31 +01:00
Gwendal Roué 08451dfced Rename AssociationImpl to SQLAssociation 2019-03-02 14:46:12 +01:00
Gwendal Roué b506838519 ToOneAssociation 2019-03-01 19:13:46 +01:00
Gwendal Roué 1511981dc7 AssociationImpl is no longer a protocol 2019-03-01 19:13:28 +01:00
Gwendal Roué 661cca9f80 Merge pull request #488 from groue/feature/ValueObservationCleanup
ValueObservation Cleanup
2019-03-01 16:55:24 +01:00
Gwendal Roué 4ee2523d59 CHANGELOG 2019-03-01 13:51:22 +01:00
Gwendal Roué 997be18718 Update ValueObservation documentation 2019-03-01 13:51:15 +01:00
Gwendal Roué e966544aeb Remove ValueObservation.extent 2019-03-01 13:17:48 +01:00
Gwendal Roué 4935c6f258 Rename ValueScheduling.onQueue(_:startImmediately:) to .async(onQueue:startImmediately:) 2019-03-01 08:24:00 +01:00
Gwendal Roué 03fafa437c Cleanup 2019-03-01 08:05:46 +01:00
Gwendal Roué 0fe7db2694 Assume NSUUID.fromDatabaseValue no longer needs special care in Release configuration, since we target Xcode 10+ now 2019-02-28 13:28:06 +01:00
Gwendal Roué 22edb91796 Merge pull request #487 from groue/feature/SR-6067
Remove SR-6067 workaround
2019-02-28 12:15:41 +01:00
Gwendal Roué 5ffc35a955 Remove SR-6067 workaround 2019-02-28 08:35:16 +01:00
Gwendal Roué 1084fe0425 Cleanup 2019-02-26 20:45:58 +01:00
Gwendal Roué 8d867320b0 Remove DatabaseValue.losslessConvert methods
They were used by RxGRDB until 0.13.0.
2019-02-26 20:40:13 +01:00
Gwendal Roué 34dd011e90 TODO: replace ValueObservation.extent 2019-02-26 20:23:14 +01:00
Gwendal Roué 8fce4faeea Fix typo 2019-02-26 09:00:29 +01:00
Gwendal Roué 8faff704d5 Merge pull request #486 from groue/feature/RecordNotFound
Refactor PersistenceError.recordNotFound
2019-02-26 08:09:04 +01:00
Gwendal Roué 2d71679476 Cleanup 2019-02-26 08:07:13 +01:00
Gwendal Roué 715b7a7867 CHANGELOG 2019-02-25 20:48:35 +01:00
Gwendal Roué 8ef28b0683 Fix PersistenceError.description 2019-02-25 20:43:40 +01:00
Gwendal Roué 31bdb2eeaa PersistenceError.recordNotFound documentation 2019-02-25 20:21:20 +01:00
Gwendal Roué 63192e2b75 Refactor PersistenceError.recordNotFound 2019-02-25 20:17:49 +01:00
Gwendal Roué fcbbe17909 Documentation 2019-02-25 18:53:32 +01:00
Gwendal Roué a1e809cbc7 Cleanup TODO 2019-02-25 17:23:02 +01:00
Gwendal Roué 93b429cca4 CHANGELOG 2019-02-24 18:02:57 +01:00
Gwendal Roué 3aaa5e74ec Update README 2019-02-24 17:48:10 +01:00
Gwendal Roué 27156fd215 Support for remove_diacritics=2 in FTS5 2019-02-24 17:38:04 +01:00
Gwendal Roué bcac197910 [whitespace] FTS5 files indentation 2019-02-24 17:12:10 +01:00
Gwendal Roué 336081a78a Support for remove_diacritics=2 in FTS3/4 2019-02-24 17:06:44 +01:00
Gwendal Roué 6306bd31e3 Update SQLiiteCustom/src to branch 3.27.1 of groue/SQLiteLib 2019-02-24 16:00:17 +01:00
Gwendal Roué 690e980018 Fix double inclusion of GRDB-4.0.swift in GRDBWatchOS target 2019-02-24 15:40:15 +01:00
Gwendal Roué f9fbd42962 CHANGELOG 2019-02-24 15:22:40 +01:00
Gwendal Roué 919f6095c6 Merge pull request #484 from groue/feature/SE-0193
SE-0193 Cross-module inlining and specialization
2019-02-24 15:18:49 +01:00
Gwendal Roué 83f62eed79 CHANGELOG 2019-02-24 15:18:04 +01:00
Gwendal Roué 96b971b0da PersistenceContainer specialization 2019-02-24 14:42:00 +01:00
Gwendal Roué 05fe018fed GRDBProfiling enhancements 2019-02-24 06:28:35 +01:00
Gwendal Roué 921c5d636a Remove SQLite.swift dependency from GRDBOSXPerformanceTests target 2019-02-24 06:26:51 +01:00
Gwendal Roué 61ae460525 Persistence methods specialization, PersistenceContainer optimizations 2019-02-24 06:26:08 +01:00
Gwendal Roué caaf2365e0 Fix compiler warning: make SQLiteValue @usableFromInline 2019-02-23 20:31:56 +01:00
Gwendal Roué bed9164bcd Allow specialization of fetching methods 2019-02-23 18:34:42 +01:00
Gwendal Roué f3621da329 @inlinable remaining Row subscripts 2019-02-23 17:37:04 +01:00
Gwendal Roué 2c75582c22 @inlinable RecordCursor 2019-02-23 17:23:30 +01:00
Gwendal Roué aa4f7c3d78 @inlinable StatementCursor 2019-02-23 17:19:56 +01:00
Gwendal Roué 9906cf799c @inlinable DatabaseValueCursor and NullableDatabaseValueCursor 2019-02-23 17:04:32 +01:00
Gwendal Roué 304937161c Performance comparison: Realm 3.13.1 2019-02-23 16:17:23 +01:00
Gwendal Roué 789497da75 FMDatabaseQueue(path:) is a failable initializer 2019-02-23 16:08:24 +01:00
Gwendal Roué 14371cd7c6 Performance comparison: update Realm location 2019-02-23 15:57:56 +01:00
Gwendal Roué b9dbce47a2 Performance comparison: FMDB 2.7.5 2019-02-23 15:46:09 +01:00
Gwendal Roué eb1672dec3 Revert wrong Xcode refactoring 2019-02-23 15:41:38 +01:00
Gwendal Roué dd0926ebfb ValueConversionContext does not need to be @usableFromInline 2019-02-23 15:35:23 +01:00
Gwendal Roué e80f3639af Revert wrong Xcode refactoring 2019-02-23 15:34:25 +01:00
Gwendal Roué 944b3ac07d @inlinable RowCursor, and Row subscript returning StatementColumnConvertible 2019-02-23 15:27:12 +01:00
Gwendal Roué 746c22e950 @inlinable FastDatabaseValueCursor and FastNullableDatabaseValueCursor 2019-02-23 14:28:44 +01:00
Gwendal Roué a0c85f093c Remove all @inline(__always) 2019-02-23 13:37:00 +01:00
Gwendal Roué 728c3b28ed Typo fix 2019-02-22 14:28:36 +01:00
Gwendal Roué 03b8df2fe1 Merge pull request #478 from groue/feature/SQLInterpolation2
Swift 5: SQL interpolation
2019-02-22 13:43:11 +01:00
Gwendal Roué dae55e4105 Merge branch 'GRDB-4.0' into feature/SQLInterpolation2 2019-02-22 13:37:44 +01:00
Gwendal Roué f8a1ecb644 Use query variable name when an SQLLiteral contains a full SQL query 2019-02-22 13:34:30 +01:00
Gwendal Roué 22c2cfb4ea Test SQLRequest interpolation 2019-02-22 13:28:58 +01:00
Gwendal Roué b15eaa826b TODO 2019-02-22 13:07:27 +01:00
Gwendal Roué 32b8d87a64 Use sqlite3_prepare_v3 on iOS 12.0, OSX 10.14, watchOS 5.0 2019-02-22 13:06:24 +01:00
Gwendal Roué 62ba97f517 Inline documentation 2019-02-22 12:59:44 +01:00
Gwendal Roué e81a514f29 SQLInterpolation.md 2019-02-22 09:15:05 +01:00
Gwendal Roué e36ca9f645 Foster SQL interpolation 2019-02-21 23:23:35 +01:00
Gwendal Roué d9dc21a073 Merge branch 'GRDB-4.0' into feature/SQLInterpolation2 2019-02-21 23:11:58 +01:00
Gwendal Roué 59cc1fef67 SQLInterpolation.md 2019-02-21 23:10:06 +01:00
Gwendal Roué 8df8129743 SQLInterpolation.appendInterpolation(SQLRequest) 2019-02-21 14:20:50 +01:00
Gwendal Roué b6481e8a68 SQLInterpolation.md 2019-02-21 12:20:16 +01:00
Gwendal Roué 65b65f4d70 SQL Interpolation documentation 2019-02-21 08:51:01 +01:00
Gwendal Roué 870ef6bac8 CHANGELOG 2019-02-21 08:48:22 +01:00
Gwendal Roué f7f0810c17 Documentation 2019-02-20 14:08:31 +01:00
Gwendal Roué 17c3ac1911 Link to #482 2019-02-20 08:54:35 +01:00
Gwendal Roué d74340a317 GRDB 4 development process 2019-02-20 08:17:23 +01:00
Gwendal Roué e54410b608 Swift 5: link to the GRDB-4.0 branch 2019-02-20 07:56:52 +01:00
Gwendal Roué 58dc1c67d6 Fix some sample code 2019-02-17 13:28:41 +01:00
Gwendal Roué 7e9e50e52d Up to date playgrounds 2019-02-17 13:28:41 +01:00
Gwendal Roué df05e940e8 Minor 2019-02-17 13:28:41 +01:00
Gwendal Roué 8d6a2fb4f1 Documentation, support for interpolation of empty sequences 2019-02-17 13:28:41 +01:00
Gwendal Roué afa8360397 Restore SQLExpressionLiteral.sql and arguments 2019-02-17 13:28:41 +01:00
Gwendal Roué 50f8bcec34 Fixit for SQLExpression.literal 2019-02-17 13:28:41 +01:00
Gwendal Roué d13968b753 Documentation 2019-02-17 13:28:41 +01:00
Gwendal Roué 086e3e918e joined(separator:) for SQLLiteral sequences 2019-02-17 13:28:41 +01:00
Gwendal Roué e986f0d6e5 Test for interpolation of empty sequence 2019-02-17 13:28:41 +01:00
Gwendal Roué 36ce78bd37 Explicit sql argument label when building prepared statements 2019-02-17 13:28:41 +01:00
Gwendal Roué e2a11eeb05 Update some inline documentation 2019-02-17 13:28:41 +01:00
Gwendal Roué 2d40b86a50 Rename SQLLiteral.append(literal:) to append(_:) 2019-02-17 13:28:41 +01:00
Gwendal Roué 4f350631ff Remove fetching methods from SQLLiteral. 2019-02-17 13:28:41 +01:00
Gwendal Roué db67d3840b Principle of least astonishment: rrename argument label rawSQL to sql 2019-02-17 13:28:41 +01:00
Gwendal Roué 2cd20b79f7 Fix typo 2019-02-17 13:28:40 +01:00
Gwendal Roué b296e9824a SQLGenerationContext.append(arguments:) cleanup 2019-02-17 13:28:40 +01:00
Gwendal Roué b0d9c519e1 Fix SPM test 2019-02-17 13:28:40 +01:00
Gwendal Roué 6937193d28 Fix SPM compilation 2019-02-17 13:28:40 +01:00
Gwendal Roué 500a5eea28 SQLRequest(rawSQL:arguments:adapter:) 2019-02-17 13:28:40 +01:00
Gwendal Roué 9758e1783e [whitespace] 2019-02-17 13:28:40 +01:00
Gwendal Roué a57aa2e346 rawSQL migration complete 2019-02-17 13:28:40 +01:00
Gwendal Roué 4bd5ace2ee Use rawSQL as parameter name for raw SQL 2019-02-17 13:28:40 +01:00
Gwendal Roué 85f618e16e SQLLiteral.mapSQL 2019-02-17 13:28:40 +01:00
Gwendal Roué e7995b9cd4 SQLExpressionLiteral(rawSQL:) 2019-02-17 13:28:40 +01:00
Gwendal Roué 6e80c748d2 SQLRequest(rawSQL:arguments:adapter:) 2019-02-17 13:28:40 +01:00
Gwendal Roué c546c578ce fetchCursor/All/One(_:rawSQL:arguments:adapter:) 2019-02-17 13:28:40 +01:00
Gwendal Roué 59162d93de Rename Database.execute(_:String) to Database.execute(rawSQL:String) 2019-02-17 13:27:54 +01:00
Gwendal Roué 354d22d70d Update documentation for literal interpolation 2019-02-17 13:24:38 +01:00
Gwendal Roué f15b2e12d6 Remove support for check constraint defined with a literal
That's because we can't support it until SQLLiteral is able to quote values
2019-02-17 13:24:38 +01:00
Gwendal Roué 4ecef0ea11 Don't be shy on interpolation 2019-02-17 13:24:38 +01:00
Gwendal Roué 637de8b6fa SQLiteral are passed via a literal parameter 2019-02-17 13:24:38 +01:00
Gwendal Roué aa6f55d72f Statement arguments are generally non optional 2019-02-17 13:24:38 +01:00
Gwendal Roué f018c7f823 Rename SQLString to SQLLiteral 2019-02-17 13:24:38 +01:00
Gwendal Roué 98e2d009c6 SQLString tests 2019-02-17 13:24:38 +01:00
Gwendal Roué 09e85ba341 SQLString everywhere 2019-02-17 13:24:38 +01:00
Gwendal Roué f27a1e9504 request.select(SQLString) 2019-02-17 13:24:38 +01:00
Gwendal Roué 86409687a4 TODO: Documentation 2019-02-17 13:24:38 +01:00
Gwendal Roué ff439c2dbc Documentation 2019-02-17 13:24:37 +01:00
Gwendal Roué 9b6c9b421a Update CustomizedDecodingOfDatabaseRows for SQLString 2019-02-17 13:24:37 +01:00
Gwendal Roué b5bcdd9df4 Fetch FetchableRecord from SQLString 2019-02-17 13:24:37 +01:00
Gwendal Roué b36cf84b23 Fetch StatementColumnConvertible from SQLString 2019-02-17 13:24:37 +01:00
Gwendal Roué fb89b540cd Fetch DatabaseValueConvertible from SQLString 2019-02-17 13:24:37 +01:00
Gwendal Roué 86b8c35c04 Fetch rows from SQLString 2019-02-17 13:24:37 +01:00
Gwendal Roué e7497e707e SQLRequest.init(SQLString) 2019-02-17 13:24:37 +01:00
Gwendal Roué b7089bb025 Database.execute(SQLString) 2019-02-17 13:24:37 +01:00
Gwendal Roué 612bd70710 Test SQLString in Swift 4.2 mode 2019-02-17 13:24:37 +01:00
Gwendal Roué 8affc8abe4 Remove dead code 2019-02-17 13:24:37 +01:00
Gwendal Roué d9cf760a25 SQLString 2019-02-17 13:24:37 +01:00
Gwendal Roué 5b6d882d67 SQLRequest adopts ExpressibleByStringInterpolation 2019-02-17 13:24:37 +01:00
Gwendal Roué 87ee00c2c5 SQLInterpolation 2019-02-17 13:24:37 +01:00
Gwendal Roué e100287bd8 Fixits for ValueObservation 2019-02-17 13:09:19 +01:00
Gwendal Roué 323b8de3dc Fixits for ColumnCursor and NullableColumnCursor 2019-02-17 13:02:48 +01:00
Gwendal Roué 06ec4580be Fixit for DatabaseWriter.readFromCurrentState 2019-02-17 12:59:32 +01:00
Gwendal Roué efd69a628a Add fixit for Cursor.flatMap 2019-02-17 12:50:29 +01:00
Gwendal Roué cc80daec99 Fixit/GRDB-4.0.swift 2019-02-17 12:48:13 +01:00
Gwendal Roué fd398aa434 Fix cocapods lint tests 2019-02-17 11:09:56 +01:00
Gwendal Roué 4b8ea08f4f Simplify Statement preparation now that SR-2347 is solved 2019-02-10 14:20:12 +01:00
Gwendal Roué e57cf49dc4 Remove useless check 2019-02-09 20:27:15 +01:00
Gwendal Roué 111dcbcad4 Fix warnings 2019-02-09 20:10:11 +01:00
Gwendal Roué 4174896225 Fix DataMemoryTests 2019-02-09 16:05:03 +01:00
Gwendal Roué 5738edc1bb CHANGELOG 2019-02-09 14:25:33 +01:00
Gwendal Roué 192bd71c12 SQLRequest.arguments is no longer optional 2019-02-09 14:14:07 +01:00
Gwendal Roué 5ee3b9c878 SE-0235 Add Result to the Standard Library 2019-02-09 12:54:30 +01:00
Gwendal Roué d3020dbd8f Workaround SR-9893
https://bugs.swift.org/browse/SR-9893
2019-02-09 11:10:27 +01:00
Gwendal Roué 493575a47b SE-0220 count(where:) 2019-02-09 10:21:34 +01:00
Gwendal Roué fa4febfa93 GRDB 4.0 TODO 2019-02-09 10:04:24 +01:00
Gwendal Roué 8cd49082ec SE-0205 withUnsafePointer(to:_:) and withUnsafeBytes(of:_:) for immutable values 2019-02-09 09:56:12 +01:00
Gwendal Roué 0dbfe7d9e3 GRDB 4.0 TODO 2019-02-09 09:50:32 +01:00
Gwendal Roué bbc64e38c7 SE-0207 Add an allSatisfy algorithm to Sequence 2019-02-09 09:50:04 +01:00
Gwendal Roué d7188f4b93 TODO: Rename Future 2019-02-08 10:19:01 +01:00
Gwendal Roué bb045235bf Remove tests for deprecated methods 2019-02-08 10:16:17 +01:00
Gwendal Roué ca4879c496 Remove deprecated ValueObservation methods 2019-02-08 10:16:17 +01:00
Gwendal Roué a466a8b253 Remove deprecated Cursor types 2019-02-08 10:16:17 +01:00
Gwendal Roué 5cd66c1be8 Remove deprecated Cursor.flatMap 2019-02-08 10:16:17 +01:00
Gwendal Roué 4489106bd6 Remove deprecated DatabaseWriter.readFromCurrentState 2019-02-08 10:16:17 +01:00
Gwendal Roué 485d42373b GRDB 4 is the latest version for Swift 4.2 2019-02-08 09:00:34 +01:00
Gwendal Roué 249484a21f SE-0204 Add last(where:) and lastIndex(where:) Methods 2019-02-08 08:47:45 +01:00
Gwendal Roué fb8946254d Swift 5: update calls to Data.withUnsafeBytes 2019-02-08 08:22:23 +01:00
Gwendal Roué b8a2592737 TODO future support for SQLite 3.27.0 2019-02-08 07:55:07 +01:00
Gwendal Roué 3029949731 Add () to forward @autoclosure parameters 2019-02-08 05:30:57 +01:00
Gwendal Roué 91061ee669 Remove redundant public modifiers 2019-02-08 05:27:50 +01:00
Gwendal Roué 90a9aa3523 Fix SPM compilation 2019-02-07 12:57:09 +01:00
Gwendal Roué ad04ccc094 Drop all fixits for GRDB < 3.0 2019-02-07 12:52:52 +01:00
Gwendal Roué a230fe400d Availability checks: assume iOS >= 9.0 2019-02-07 08:52:38 +01:00
Gwendal Roué 62ef344a6c Simplify FTS5, assuming swift(>=4.2) 2019-02-07 08:39:06 +01:00
Gwendal Roué 3eb36768c6 Simplify iOS memory management, assuming swift(>=4.2) 2019-02-07 08:25:31 +01:00
Gwendal Roué b6f79f176c SE-0206 : Hashable Enhancements 2019-02-07 08:21:48 +01:00
Gwendal Roué e2d151e748 Travis: test Xcode 10.1 2019-02-06 21:30:49 +01:00
Gwendal Roué 54ddd3e025 Set IPHONEOS_DEPLOYMENT_TARGET to 9.0 2019-02-06 20:05:53 +01:00
Gwendal Roué 2d7857f45b Package.swift uses swift-tools-version:4.2 2019-02-06 20:04:39 +01:00
Gwendal Roué 81892491f2 Set default SWIFT_VERSION to 4.2 2019-02-06 19:53:00 +01:00
Gwendal Roué 0493a9646f GRDB 4.0 kickoff 2019-02-06 19:45:19 +01:00
Gwendal Roué e99823dbcc Make DatabasePromise a proper monad 2019-02-04 19:27:18 +01:00
Gwendal Roué a1c99425cc SQLQualifiedSource.init(_:) bugfix, and cleanup 2019-02-04 08:18:20 +01:00
Gwendal Roué dc6db13134 Merge pull request #476 from groue/feature/cleanup
SQL Generation Winter Cleaning
2019-02-04 07:41:56 +01:00
Gwendal Roué 699c63e913 Explain how SQLSelectQueryGenerator uses RowAdapter 2019-02-03 19:55:26 +01:00
Gwendal Roué e924587236 Extract generation of SQL SELECT queries into SQLSelectQueryGenerator 2019-02-03 14:56:28 +01:00
Gwendal Roué c776801c4a Document "merging" and "finalization" 2019-02-03 11:58:16 +01:00
Gwendal Roué 73782d5e9d BelongsTo, HasOne and HasMany share the same JoinAssociationImpl 2019-02-03 10:23:34 +01:00
Gwendal Roué 659171902e Move join-related types to SQLRelation.swift 2019-02-03 10:09:34 +01:00
Gwendal Roué 4a209fcbc4 Rename SQLSource to SQLRelation.Source 2019-02-03 10:06:23 +01:00
Gwendal Roué 91b68ffa4f Trim 2019-02-03 09:29:52 +01:00
Gwendal Roué 5ea914ce0a YAGNI: JoinCondition.sqlExpression is not optional 2019-02-03 08:42:37 +01:00
Gwendal Roué 950fa607a1 Hide implementation details of associations 2019-02-03 08:26:58 +01:00
Gwendal Roué c9ff5a53a1 JoinCondition: Equatable 2019-02-03 00:03:04 +01:00
Gwendal Roué f42d5f202d White space 2019-02-02 17:57:01 +01:00
Gwendal Roué 27c6390635 More Association trimming 2019-02-02 17:53:01 +01:00
Gwendal Roué e62cfe086c Documentation 2019-02-02 17:23:50 +01:00
Gwendal Roué 40f6b351ea Rename QueryInterfaceQuery to SQLSelectQuery 2019-02-02 17:15:29 +01:00
Gwendal Roué 89dda44364 Extract and document DatabasePromise 2019-02-02 17:04:16 +01:00
Gwendal Roué 9addac6f54 Rename QueryOrdering to SQLRelation.Ordering 2019-02-02 16:43:10 +01:00
Gwendal Roué 5a942d7213 More trimming: QueryInterfaceQuery now embeds a SQLRelation 2019-02-02 16:20:43 +01:00
Gwendal Roué bb972a351a Refactor JoinQuery into SQLRelation 2019-02-02 15:39:18 +01:00
Gwendal Roué 5f037c7e4e Replace JoinQuery initializer with QueryInterfaceRequest.asJoinQuery() 2019-02-02 14:54:31 +01:00
Gwendal Roué 9d391badc0 Documentation 2019-02-02 14:31:12 +01:00
Gwendal Roué f309a0c5f3 Documentation 2019-02-02 13:30:57 +01:00
Gwendal Roué d9530433f2 Move JoinCondition definition 2019-02-02 13:15:17 +01:00
Gwendal Roué 20d067c826 Documentation 2019-02-02 13:11:00 +01:00
Gwendal Roué 1e7840f0e4 More trimming 2019-02-02 11:38:27 +01:00
Gwendal Roué 77fd2b8411 Restore failing tests 2019-02-02 10:51:33 +01:00
Gwendal Roué b180fc37bb Trim associations 2019-02-02 10:38:47 +01:00
Gwendal Roué 4e4d591109 Typo fix 2019-01-30 08:46:18 +01:00
Gwendal Roué 7745e92a1f Merge pull request #470 from timwredwards/master
Update README.md
2019-01-14 14:06:22 +01:00
Tim Edwards b70de2033a Update README.md
Fixed "latest release" date
2019-01-14 13:02:50 +00:00
Gwendal Roué 134bc670ef CHANGELOG 2019-01-05 15:57:10 +01:00
610 changed files with 60146 additions and 33405 deletions

No files matched your search

+2 -1
View File
@@ -1,4 +1,5 @@
source 'https://rubygems.org'
gem 'xcpretty'
gem 'xcpretty-travis-formatter'
gem 'xcpretty-travis-formatter'
gem 'cocoapods', '~> 1.7'
+1
View File
@@ -0,0 +1 @@
github: [groue]
+1 -1
View File
@@ -18,7 +18,7 @@ Please fill out this template when filing an issue.
### Environment
**GRDB flavor(s):** (GRDB, GRDBCipher, GRDBCustom?)
**GRDB flavor(s):** (GRDB, SQLCipher, Custom SQLite build?)
**GRDB version:**
**Installation method:** (CocoaPods, SPM, manual?)
**Xcode version:**
+1 -2
View File
@@ -9,5 +9,4 @@ Please verify that your pull request checks those boxes:
- [ ] This pull request is submitted against the `development` branch.
- [ ] Inline documentation has been updated.
- [ ] README.md or another dedicated guide has been updated.
- [ ] Changes are tested, for all flavors of GRDB, GRDBCipher, and GRDBCustomSQLite.
- [ ] CHANGELOG.md has been updated.
- [ ] Changes are tested.
+3 -3
View File
@@ -101,13 +101,13 @@ SQLiteCustom/GRDBCustomSQLite-USER.h
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
# CocoaPods test
Podfile.lock
Pods
Tests/CocoaPods/*/*.xcworkspace
Podfile.lock
# SPM
.build
Package.resolved
GRDB.xcworkspace/xcshareddata/swiftpm
#Package.resolved
Tests/SPM/Packages
# Ruby
+1 -13
View File
@@ -1,15 +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 "SQLCipher/src"]
path = SQLCipher/src
url = https://github.com/groue/sqlcipher.git
[submodule "SQLiteCustom/src"]
path = SQLiteCustom/src
url = https://github.com/swiftlyfalling/SQLiteLib
url = https://github.com/swiftlyfalling/SQLiteLib.git
-1
View File
@@ -1 +0,0 @@
4.1
+63
View File
@@ -0,0 +1,63 @@
included:
- GRDB
disabled_rules:
- cyclomatic_complexity
- file_length
- force_cast
- force_try
- function_body_length
- function_parameter_count
- identifier_name
- is_disjoint
- nesting
- opening_brace
- redundant_optional_initialization
- syntactic_sugar
- todo
- trailing_comma
- trailing_whitespace
- type_body_length
- type_name
- unused_setter_value
opt_in_rules:
- anyobject_protocol
- array_init
- attributes
- closure_spacing
- collection_alignment
- contains_over_filter_count
- contains_over_filter_is_empty
- contains_over_first_not_nil
- contains_over_range_nil_comparison
- convenience_type
- empty_collection_literal
- empty_count
- empty_string
- explicit_init
- fatal_error_message
- first_where
- flatmap_over_map_reduce
- identical_operands
- joined_default_parameter
- last_where
- legacy_multiple
- legacy_random
- lower_acl_than_parent
- modifier_order
- no_extension_access_modifier
- overridden_super_call
- pattern_matching_keywords
- prohibited_super_call
- reduce_into
- redundant_type_annotation
- sorted_first_last
- toggle_bool
- unused_declaration
- unused_import
- yoda_condition
vertical_whitespace:
max_empty_lines: 2
+143 -175
View File
@@ -1,9 +1,24 @@
# The OS X Build Environment
# https://docs.travis-ci.com/user/reference/osx/#xcode-version
branches:
only:
- master
- development
language: objective-c
xcode_project: GRDB.xcodeproj
# Caches
cache:
- bundler
- cocoapods
# Custom CocoaPods installation so that Podfile.lock is honored
install:
- bundle install
- bundle exec pod repo update
# Disable the default Travis-CI submodule logic
# The various make commands ensure that the appropriate submodules are retrieved
git:
@@ -13,228 +28,181 @@ jobs:
include:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
## Test GRDB Xcode 11.4
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBOSX (Xcode 10, Swift 4.2, macOS)
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBOSX_maxSwift
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBOSX (Xcode 10, Swift 4.0, macOS)
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_minSwift
# Test GRDBWatchOS (Xcode 10)
- stage: Test GRDB
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBWatchOS (Xcode 10, watchOS)
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBiOS (Xcode 10, Swift 4.2, iOS <MAX>)
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode11.4
env:
- TID=GRDBiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
osx_image: xcode11.4
env:
- TID=GRDBiOS (Xcode 9.3, iOS <MIN>)
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 10, macOS)
- stage: Test GRDB
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDB [SPM] (Xcode 10, macOS)
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
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 GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 10)
- stage: Test GRDB + Custom SQLite
## Test GRDBCustom Xcode 11.4
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBCustomSQLiteOSX (Xcode 10, macOS)
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBCustomSQLiteiOS (Xcode 10, Swift 4.2, iOS <MAX>)
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBCustomSQLiteiOS (Xcode 10, Swift 4.0, iOS <MAX>)
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
# Test GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode11.4
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MIN>)
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 10)
- stage: Test GRDB + SQLCipher
## Test SQLCipher Xcode 11.4
- stage: Test SQLCipher Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBCipherOSX (Xcode 10, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
- TID=SQLCipher 3
script: make test_framework_SQLCipher3
- stage: Test SQLCipher Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=GRDBCipheriOS (Xcode 10, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
env:
- TID=GRDBCipheriOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
env:
- TID=GRDBCipheriOS (Xcode 9.3, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
- TID=SQLCipher 4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Methods
# Manual Install (Xcode 10)
- stage: Test Installation
## Test Installation Xcode 11.4
# Manual Install
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=Manual Install (Xcode 10)
- TID=Manual Install
script: make test_install_manual
# Manual Install (GRDBCipher, Xcode 10)
- stage: Test Installation
# CocoaPods Lint
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode11.4
env:
- TID=Manual Install (GRDBCipher, Xcode 10)
script: make test_install_GRDBCipher
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods Lint GRDB.swift (Xcode 10)
- TID=CocoaPods Lint
script: make test_CocoaPodsLint_GRDB
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods Lint GRDBPlus (Xcode 10)
script: make test_CocoaPodsLint_GRDBPlus
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods Lint GRDBCipher (Xcode 10)
script: make test_CocoaPodsLint_GRDBCipher
# CocoaPods Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (Xcode 10)
script: make test_install_GRDB_CocoaPods
# CocoaPods Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
- TID=SPM Package
script: make test_install_SPM_Package
# SPM Install
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB+FTS5 (Xcode 10)
script: make test_install_GRDBFTS5_CocoaPods
# CocoaPods Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
- TID=SPM Package in Xcode Project
script: make test_install_SPM_Project
# Custom SQLite Install
- stage: Test Installation Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDBCipher (Xcode 10)
script: make test_install_GRDBCipher_CocoaPods
# SPM Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
env:
- TID=SPM (Xcode 10)
script: make test_install_SPM
## Carthage Build
- stage: Test Installation
osx_image: xcode10
before_install:
- brew update
- brew outdated carthage || brew upgrade carthage
env:
- TID=Carthages
script: make test_CarthageBuild
- TID=Custom SQLite
script: make test_install_customSQLite
+105
View File
@@ -0,0 +1,105 @@
# Brag Document
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.
---
https://twitter.com/BelleBCooper/status/1223148814980091904
> I LOVE GRDB and highly recommend it. If you don’t need it now, do keep it in mind for future because it’s great and the documentation and support are top notch.
---
https://twitter.com/layoutSubviews/status/1202092984822648832
> GRDB is quickly becoming the best package I have ever dealt with.
> What an exceptional piece of work: the philosophy, the documentation, the API, the abstractions, the Swiftiness👌
---
https://twitter.com/fpillet/status/1193608995405209607
> GRDB keeps being the best-in-class interface to your database, and if you're not using it you're missing out. As always, amazing work from @groue !
---
https://twitter.com/lordmooch/status/1193537540583755776
> Best SQLite/Swift integration 😀👍🏻
---
https://twitter.com/BelleBCooper/status/1192195655743111168
> I’ve been working on a side project recently that uses SwiftUI (+UIKit for parent controllers and nav), Combine, GRDB, and GRDBCombine for automatic updating based on DB changes. I’m really liking this setup.
---
https://twitter.com/BelleBCooper/status/1186034269577048064
> Working on a new project today and using GRDB by @groue for the backend. This is my go-to for new Swift projects. Highly recommend it!
---
https://twitter.com/krzyzanowskim/status/1156568071303290882
> I think GRDB.swift is a godsend. So far sooooo good. (change my mind?)
---
https://twitter.com/iOSDevWeekly/status/1133780078398021637
> How had I never heard of GRDB before this week? Was I the only one missing out, or is this wonderful database library from @groue news to you all too? https://buff.ly/2X8yHGf #iosdev
----
https://twitter.com/micpringle/status/1132264501812891648
> Spent the last few weeks integrating it and it’s amazing! And this release brings a whole load more features—especially excited about eager loading of hasMany relationships.
>
> Quite possibly one of the best documented open source libs I’ve come across as well👌🏼
---
https://twitter.com/danielemargutti/status/1132217792902647808
> It’s a great successor for FMDB with tons of great stuff. Worth a look, we have choose it in our new project even if, actually, I preferred not using some of the ‘ORM’ like features.
---
https://twitter.com/lordmooch/status/1131664588494254086
> Woohoo! Absolutely superb Swift library for SQLite - I love it 😀
---
https://twitter.com/JadenGeller/status/1115483150564487168
> Wow, there are some *really* good looking SQLite frameworks in Swift.
---
https://twitter.com/strawb3rryx7/status/1073620070784516096
> If you looking for a SQLite wrapper in Swift, just take a look the GRDB library! 👇🏼 https://github.com/groue/GRDB.swift Well-maintained and documented! ✊🏼
---
https://twitter.com/BelleBCooper/status/1047017928112128000
> http://blog.bellebcooper.com/2018-10-02-16-39.html
>
> I love the way issues are handled in GRDB (SQLite for Swift). Groue is so friendly, and always goes above-and-beyond in helping to solve problems or explore new features for the library. It makes me happy to be a GRDB user.
+1171 -4
View File
File diff suppressed because it is too large. Load diff
+6 -77
View File
@@ -78,18 +78,13 @@ The ideas, in alphabetical order:
- [Date and Time Functions]
- [Decode NSDecimalNumber from Text Columns]
- [Documentation]
- [FetchedRecordsController Diffing Algorithm]
- [FetchedRecordsController Support for Any Request]
- [FetchedRecordsController Support for Sections]
- [Full Text Search Demo Application]
- [JSON]
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [Records: Splitting Database Encoding from Ability to Write in the Database]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Static Library]
- [Typed Expressions]
@@ -97,7 +92,7 @@ The ideas, in alphabetical order:
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
Associations can be enhanced in several ways. See the "Known Issues" and "Future Directions" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
Associations can be enhanced in several ways. See the "Known Issues" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
### CloudKit
@@ -207,50 +202,6 @@ Inline documentation, the one which is embedded right into the source code and i
If you are a good writer, your help will be very warmly welcomed.
### FetchedRecordsController Diffing Algorithm
:muscle: Hard
[FetchedRecordsController] uses a Levenshtein-based diffing algorithm which has a terrible algorithmic complexity. This makes this very useful class unable to deal with more than hundreds of elements.
There exists much more efficient O(n) diffing algorithms that would lift this limitation.
Starting points:
- [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources)
- [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit)
- [tonyarnold/Differ](https://github.com/tonyarnold/Differ)
- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff)
- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff)
### FetchedRecordsController Support for Any Request
:muscle: Hard
[FetchedRecordsController] is able to deal with records, but not with raw rows or values:
```swift
// Supported by FetchedRecordsController
let recordRequest = Player.all()
// Not supported by FetchedRecordsController
let stringRequest = Player.select(Column("name"), as: String.self)
let rowRequest = SQLRequest<Row>("SELECT ...")
```
This limitation does not apply to [ValueObservation] and [RxGRDB]. It would be nice if FetchedRecordsController would become just as versatile.
### FetchedRecordsController Support for Sections
:muscle: Hard
[FetchedRecordsController] mimics the API of Core Data's [NSFetchedResultsController](https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller), but does not yet support table and collection view sections.
This improvement most certainly depends on a refreshing of the [FetchedRecordsController Diffing Algorithm].
### Full Text Search Demo Application
:baby: Starter Task :pencil: Documentation
@@ -293,27 +244,16 @@ There are several SQLite features that GRDB could natively support:
- [Windows Functions](https://www.sqlite.org/windowfunctions.html)
- [More ideas](https://www.sqlite.org/lang.html)
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
### Reactive Database Observation
:baby: Starter Task
We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings.
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
We need more choices of reactive engines.
### Records: Splitting Database Encoding from Ability to Write in the Database
:baby: Starter Task :pencil: Documentation
Record types that know how to encode themselves in the database (converting themselves into columns and database values) currently are granted with [persistence methods] which can write in the database. Those record types all adopt the [PersistableRecord] protocol.
But encoding a record grants other features, such as [Record Comparison], or [Requesting Associated Records].
This is a problem: one should not have to grant a type with persistence methods, when one just needs read-only features.
The fix is to split database encoding from persistence methods. See [#426](https://github.com/groue/GRDB.swift/issues/426) for more information.
More choices of reactive engines would help more developers enjoy GRDB.
### SQL Console in the Debugger
@@ -330,13 +270,6 @@ Sometimes one needs, in lldb, a console similar to the [Command Line Shell For S
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
### Static Library
:question: Unknown Difficulty :hammer: Tooling
It would be nice to be able to integrate GRDB as a static library.
### Typed Expressions
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
@@ -380,22 +313,18 @@ Features that blur this focus are non-goals:
[Date and Time Functions]: #date-and-time-functions
[Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns
[Documentation]: #documentation
[FetchedRecordsController]: README.md#fetchedrecordscontroller
[FetchedRecordsController Diffing Algorithm]: #fetchedrecordscontroller-diffing-algorithm
[FetchedRecordsController Support for Any Request]: #fetchedrecordscontroller-support-for-any-request
[FetchedRecordsController Support for Sections]: #fetchedrecordscontroller-support-for-sections
[Full Text Search Demo Application]: #full-text-search-demo-application
[How is the Library Organized?]: Documentation/LibraryOrganization.md
[How is the Repository Organized?]: Documentation/RepositoryOrganization.md
[JSON]: #json
[Linux]: #linux
[More SQL Generation]: #more-sql-generation
[Reactive Database Observation]: #reactive-database-observation
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
[Non-Goals]: #non-goals
[Report Bugs]: #report-bugs
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[Concurrency]: #concurrency
[Static Library]: #static-library
[Sponsoring and Professional Support]: #sponsoring-and-professional-support
[SQL Console in the Debugger]: #sql-console-in-the-debugger
[SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

+250
View File
@@ -0,0 +1,250 @@
Sharing a Database in an App Group Container
============================================
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
1. **Database setup** may be attempted by multiple processes, concurrently.
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
4. **GRDB** database observation misses changes performed by external processes.
We'll address all of those challenges below.
- [Use a Database Pool]
- [How to limit the `SQLITE_BUSY` error]
- [How to limit the `0xDEAD10CC` exception]
- [How to perform cross-process database observation]
## Use a Database Pool
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool!
}
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator.
try migrator.migrate(dbPool)
return dbPool
}
```
- In a process that only reads in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL,
/// or nil if the database is not created yet, or does not have the required
/// schema version.
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openReadOnlyDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool
}
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
do {
var configuration = Configuration()
configuration.readonly = true
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
// Check here if the database schema is correct, for example
// with a DatabaseMigrator.
if try dbPool.read(migrator.hasCompletedMigrations) {
return dbPool
} else {
return nil
}
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
throw error
} else {
return nil
}
}
}
```
## How to limit the `SQLITE_BUSY` error
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
See https://www.sqlite.org/rescode.html#busy for more information about this error.
If several processes want to write in the database, configure the database pool of each process that wants to write:
```swift
var configuration = Configuration()
configuration.busyMode = .timeout(/* a TimeInterval */)
configuration.defaultTransactionKind = .immediate
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// Another process won't let you write. Deal with it.
}
```
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
## How to limit the `0xDEAD10CC` exception
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
}
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
Set the `observesSuspensionNotifications` configuration flag:
```swift
var configuration = Configuration()
configuration.suspendsOnBackgroundTimeExpiration = true
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationDidEnterBackground(_ application: UIApplication) {
// Suspend databases
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
}
}
```
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
}
}
```
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
// Proceed with background fetch
...
}
}
```
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
You can catch those errors:
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.isInterruptionError {
// Oops, the database is suspended.
// Maybe try again after database is resumed?
}
```
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with [DatabaseRegionObservation]:
```swift
// Notify all changes made to the "player" and "team" database tables
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
// Notify all changes made to the database
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
```
[Use a Database Pool]: #use-a-database-pool
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
File diff suppressed because it is too large. Load diff
+8 -6
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.25.2](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.28.0](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
@@ -11,13 +11,13 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
1. Clone the GRDB git repository, checkout the latest tagged version:
```sh
cd [GRDB directory]
git checkout v3.6.2
git checkout [latest tag]
git submodule update --init SQLiteCustom/src
````
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
@@ -111,7 +111,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
7. Add the `GRDBCustomSQLite.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
7. Add the `GRDBCustomSQLite.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
@@ -120,13 +120,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
Select your application target in the "Provide build settings from" menu.
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
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 {
@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -1,7 +1,6 @@
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@@ -26,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS</string>
<string>com.github.groue.GRDBDemoiOS2</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -7,6 +7,10 @@
objects = {
/* Begin PBXBuildFile section */
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
@@ -14,8 +18,6 @@
568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; };
568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; };
568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */; };
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */; };
568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */; };
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
@@ -24,17 +26,78 @@
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; };
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = {
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
remoteInfo = GRDBOSXPerformanceComparisonTests;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
56606D0B2355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
56606D112355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
56606D132355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
56606D152355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
56606D172355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
56606D192355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
remoteInfo = GRDBtvOS;
};
56606D1B2355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
remoteInfo = GRDBtvOSTests;
};
56606D1D2355937900185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
56606D22235593A300185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 5654909F1D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
@@ -50,83 +113,6 @@
remoteGlobalIDString = 568E5FBE1E926430002582E0;
remoteInfo = GRDBDemoWatchOS;
};
568E5FE21E926535002582E0 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 5654909F1D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
568E5FE61E926547002582E0 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 5654909F1D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
56B0363A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
56B0363C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
remoteInfo = GRDBOSXPerformanceTests;
};
56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
56B0365C1E8D9F8F003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
56B036601E8D9FB1003B6DA4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -158,7 +144,7 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */,
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -169,7 +155,7 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */,
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -196,7 +182,7 @@
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -204,7 +190,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
56606D24235593AB00185962 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -212,13 +198,35 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */,
56606D202355938A00185962 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56606CFD2355931F00185962 /* Products */ = {
isa = PBXGroup;
children = (
56606D0A2355931F00185962 /* GRDB.framework */,
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */,
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */,
56606D142355931F00185962 /* GRDB.framework */,
56606D162355931F00185962 /* GRDBiOSTests.xctest */,
56606D182355931F00185962 /* GRDB.framework */,
56606D1A2355931F00185962 /* GRDB.framework */,
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
56606D1F2355938A00185962 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
isa = PBXGroup;
children = (
@@ -248,6 +256,7 @@
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56B036041E8D9EBE003B6DA4 /* Products */,
56606D1F2355938A00185962 /* Frameworks */,
);
sourceTree = "<group>";
};
@@ -277,21 +286,6 @@
path = GRDBDemoiOS;
sourceTree = "<group>";
};
56B036271E8D9F79003B6DA4 /* Products */ = {
isa = PBXGroup;
children = (
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */,
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */,
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */,
56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */,
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -324,8 +318,7 @@
buildRules = (
);
dependencies = (
568E5FE31E926535002582E0 /* PBXTargetDependency */,
568E5FE71E926547002582E0 /* PBXTargetDependency */,
56606D23235593A300185962 /* PBXTargetDependency */,
);
name = "GRDBDemoWatchOS Extension";
productName = "GRDBDemoWatchOS Extension";
@@ -345,8 +338,7 @@
buildRules = (
);
dependencies = (
56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */,
56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */,
56606D1E2355937900185962 /* PBXTargetDependency */,
568E5FD81E926430002582E0 /* PBXTargetDependency */,
);
name = GRDBDemoiOS;
@@ -361,7 +353,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 0930;
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
568E5FBE1E926430002582E0 = {
@@ -372,18 +364,20 @@
568E5FCA1E926430002582E0 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
LastSwiftMigration = 1020;
ProvisioningStyle = Automatic;
};
56B036021E8D9EBE003B6DA4 = {
CreatedOnToolsVersion = 8.3;
DevelopmentTeam = AMD8W895CT;
LastSwiftMigration = 1020;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
@@ -394,7 +388,7 @@
projectDirPath = "";
projectReferences = (
{
ProductGroup = 56B036271E8D9F79003B6DA4 /* Products */;
ProductGroup = 56606CFD2355931F00185962 /* Products */;
ProjectRef = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
},
);
@@ -408,60 +402,60 @@
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXPerformanceComparisonTests.xctest;
remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = {
56606D0A2355931F00185962 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56B0363A1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */ = {
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
remoteRef = 56B0363C1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXPerformanceTests.xctest;
remoteRef = 56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */ = {
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56606D112355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */ = {
56606D142355931F00185962 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56606D132355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */ = {
56606D162355931F00185962 /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56606D152355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */ = {
56606D182355931F00185962 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
remoteRef = 56606D172355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D1A2355931F00185962 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56606D192355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBtvOSTests.xctest;
remoteRef = 56606D1B2355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
@@ -521,6 +515,16 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
56606D1E2355937900185962 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 56606D1D2355937900185962 /* PBXContainerItemProxy */;
};
56606D23235593A300185962 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBWatchOS;
targetProxy = 56606D22235593A300185962 /* PBXContainerItemProxy */;
};
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */;
@@ -531,26 +535,6 @@
target = 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */;
targetProxy = 568E5FD71E926430002582E0 /* PBXContainerItemProxy */;
};
568E5FE31E926535002582E0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBWatchOS;
targetProxy = 568E5FE21E926535002582E0 /* PBXContainerItemProxy */;
};
568E5FE71E926547002582E0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBWatchOS;
targetProxy = 568E5FE61E926547002582E0 /* PBXContainerItemProxy */;
};
56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 56B0365C1E8D9F8F003B6DA4 /* PBXContainerItemProxy */;
};
56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 56B036601E8D9FB1003B6DA4 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -589,12 +573,11 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Debug;
};
@@ -606,12 +589,11 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Release;
};
@@ -624,12 +606,11 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Debug;
};
@@ -642,12 +623,11 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
name = Release;
};
@@ -655,6 +635,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
@@ -700,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 = 4.2;
SWIFT_VERSION = 5.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
name = Debug;
};
@@ -713,6 +696,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
@@ -752,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 = 4.2;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
name = Release;
};
@@ -769,7 +755,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -783,7 +769,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -55,8 +55,6 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
@@ -66,8 +64,8 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
@@ -91,17 +89,6 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -27,8 +27,6 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
@@ -38,8 +36,8 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Release"
@@ -61,8 +59,6 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -18,9 +18,5 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management
dbQueue.setupMemoryManagement(in: application)
}
}
@@ -1,71 +1,112 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"size" : "29x29",
"filename" : "icon_20pt@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"size" : "29x29",
"filename" : "icon_20pt@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"size" : "40x40",
"filename" : "icon_29pt@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon_29pt@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon_40pt@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon_40pt@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-60@2x.png",
"filename" : "icon_60pt@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-60@3x.png",
"filename" : "icon_60pt@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "icon_20pt.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "icon_20pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt@2x-1.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt@2x-1.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt@2x.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon_83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon.png",
"scale" : "1x"
}
],
"info" : {
Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -1,10 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -12,23 +10,23 @@
<scene sceneID="Juk-Ad-tZ2">
<objects>
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<sections>
<tableViewSection id="Nzq-eO-jT3">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="16" y="12" width="343" height="20"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
<connections>
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
@@ -43,15 +41,15 @@
</tableViewCellContentView>
</tableViewCell>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
<rect key="frame" x="0.0" y="44" width="375" height="44"/>
<rect key="frame" x="0.0" y="72" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="16" y="12" width="343" height="20"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
</textField>
</subviews>
@@ -103,7 +101,7 @@
<objects>
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="56"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -119,7 +117,7 @@
<objects>
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -134,30 +132,29 @@
<scene sceneID="9su-ms-vdJ">
<objects>
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="tX0-ON-WSI">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="tX0-ON-WSI">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
<rect key="frame" x="0.0" y="28" width="375" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
<rect key="frame" x="0.0" y="0.0" width="341" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="348" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
<rect key="frame" x="16" y="12" width="31.5" height="19.5"/>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
<rect key="frame" x="298.5" y="12" width="41.5" height="19.5"/>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
<rect key="frame" x="296" y="12" width="44" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<color key="textColor" red="0.5568627451" green="0.5568627451" blue="0.57647058819999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
</subviews>
@@ -8,18 +8,19 @@ struct Player {
var score: Int
}
// Hashable conformance supports tableView diffing
extension Player: Hashable { }
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Add ColumnExpression to Codable's CodingKeys so that we can use them
// as database columns.
//
// See https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
// for more information about CodingKeys.
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
// Update a player id after it has been inserted in the database.
@@ -34,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(CodingKeys.name)
Player.order(Columns.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
return Player.order(CodingKeys.score.desc, CodingKeys.name)
Player.order(Columns.score.desc, Columns.name)
}
}
@@ -56,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)
}
}
@@ -9,12 +9,13 @@ class PlayersViewController: UITableViewController {
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var playersController: FetchedRecordsController<Player>!
private var playerCountObserver: TransactionObserver?
private var players: [Player] = []
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
try! playersController.setRequest(playersRequest)
configureOrderingBarButtonItem()
configureTableView()
}
}
private var playersRequest: QueryInterfaceRequest<Player> {
@@ -58,12 +59,12 @@ class PlayersViewController: UITableViewController {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ⬇︎",
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ⬆︎",
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
}
@@ -71,58 +72,69 @@ class PlayersViewController: UITableViewController {
private func configureTitle() {
// Track changes in the number of players
playerCountObserver = try! ValueObservation
.trackingCount(playersRequest)
.start(in: dbQueue) { [unowned self] count in
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
playerCountCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
switch count {
case 0: self.navigationItem.title = "No Player"
case 1: self.navigationItem.title = "1 Player"
default: self.navigationItem.title = "\(count) Players"
}
}
})
}
private func configureTableView() {
// Track changes in the database players
playersController = try! FetchedRecordsController(dbQueue, request: playersRequest)
// Animate changes in the table view
playersController.trackChanges(
willChange: { [unowned self] _ in
self.tableView.beginUpdates()
},
onChange: { [unowned self] (controller, record, change) in
switch change {
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
case .deletion(let indexPath):
self.tableView.deleteRows(at: [indexPath], with: .fade)
case .update(let indexPath, _):
if let cell = self.tableView.cellForRow(at: indexPath) {
self.configure(cell, at: indexPath)
}
case .move(let indexPath, let newIndexPath, _):
// Actually move cells around for more demo effect :-)
let cell = self.tableView.cellForRow(at: indexPath)
self.tableView.moveRow(at: indexPath, to: newIndexPath)
if let cell = cell {
self.configure(cell, at: newIndexPath)
}
// A quieter animation:
// self.tableView.deleteRows(at: [indexPath], with: .fade)
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
}
},
didChange: { [unowned self] _ in
self.tableView.endUpdates()
// Track changes in the list of players
let request = self.playersRequest
let observation = ValueObservation.tracking { db in
try request.fetchAll(db)
}
playersCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
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()
// Initial fetch
try! playersController.performFetch()
// 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)
}
}
@@ -133,7 +145,7 @@ extension PlayersViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
let player = playersController.record(at: tableView.indexPathForSelectedRow!)
let player = players[tableView.indexPathForSelectedRow!.row]
let controller = segue.destination as! PlayerEditionViewController
controller.title = player.name
controller.player = player
@@ -162,12 +174,8 @@ extension PlayersViewController {
// MARK: - UITableViewDataSource
extension PlayersViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return playersController.sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playersController.sections[section].numberOfRecords
players.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
@@ -178,14 +186,14 @@ extension PlayersViewController {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = playersController.record(at: indexPath)
let player = players[indexPath.row]
try! dbQueue.write { db in
_ = try player.delete(db)
}
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = playersController.record(at: indexPath)
let player = players[indexPath.row]
if player.name.isEmpty {
cell.textLabel?.text = "-"
} else {
@@ -7,7 +7,7 @@ Demo Application
- how to setup a database in an iOS app
- how to define a simple [Codable Record](../../README.md#codable-records)
- how to track database changes and animate a table view with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
- how to track database changes and animate a table view with [ValueObservation](../../README.md#valueobservation).
**Files of interest:**
@@ -25,7 +25,7 @@ Demo Application
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
`PlayersViewController` displays a list of players. It keeps its title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
+2 -2
View File
@@ -81,7 +81,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
```swift
try db.execute("INSERT INTO documents VALUES (?)", arguments: ["..."])
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["..."])
try Document(content: "...").insert(db)
let pattern = FTS5Pattern(matchingAnyTokenIn:"...")
@@ -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 {
+347
View File
@@ -0,0 +1,347 @@
# FetchedRecordsController
**FetchedRecordsController is a sunsetted GRDB API.**
It is not deprecated. But FetchedRecordsController has known limitations which are not planned to be lifted.
You are advised to use [ValueObservation] instead of FetchedRecordsController.
---
**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.**
It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/).
Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record.
- [Creating the Fetched Records Controller](#creating-the-fetched-records-controller)
- [Responding to Changes](#responding-to-changes)
- [The Changes Notifications](#the-changes-notifications)
- [Modifying the Fetch Request](#modifying-the-fetch-request)
- [Table and Collection Views](#table-and-collection-views)
- [Implementing the Table View Datasource Methods](#implementing-the-table-view-datasource-methods)
- [Implementing Table View Updates](#implementing-table-view-updates)
- [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency)
## Creating the Fetched Records Controller
When you initialize a fetched records controller, you provide the following mandatory information:
- A [database connection](../README.md#database-connections)
- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class
- A fetch request
```swift
class Player : Record { ... }
let dbQueue = DatabaseQueue(...) // or DatabasePool
// Using a Request from the Query Interface:
let controller = FetchedRecordsController(
dbQueue,
request: Player.order(Column("name")))
// Using SQL, and eventual arguments:
let controller = FetchedRecordsController<Player>(
dbQueue,
sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?",
arguments: ["FR"])
```
The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request.
```swift
let controller = FetchedRecordsController<Author>(
dbQueue,
sql: """
SELECT author.name, COUNT(book.id) AS bookCount
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
ORDER BY author.name
""")
```
After creating an instance, you invoke `performFetch()` to actually execute
the fetch.
```swift
try controller.performFetch()
```
## Responding to Changes
In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values.
Changes are not reflected until they are applied in the database by a successful [transaction](../README.md#transactions-and-savepoints):
```swift
// One transaction
try dbQueue.write { db in // or dbPool.write
try player1.insert(db)
try player2.insert(db)
}
// One transaction
try dbQueue.inTransaction { db in // or dbPool.writeInTransaction
try player1.insert(db)
try player2.insert(db)
return .commit
}
// Two transactions
try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
try player1.insert(db)
try player2.insert(db)
}
```
When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together.
## The Changes Notifications
An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of *callbacks*:
```swift
let controller = try FetchedRecordsController(...)
controller.trackChanges(
// controller's records are about to change:
willChange: { controller in ... },
// notification of individual record changes:
onChange: { (controller, record, change) in ... },
// controller's records have changed:
didChange: { controller in ... })
try controller.performFetch()
```
See [Implementing Table View Updates](#implementing-table-view-updates) for more detail on table view updates.
**All callbacks are optional.** When you only need to grab the latest results, you can omit the `didChange` argument name:
```swift
controller.trackChanges { controller in
let newPlayers = controller.fetchedRecords // [Player]
}
```
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
```swift
// BAD: memory leak
controller.trackChanges { _ in
let newPlayers = controller.fetchedRecords
}
// GOOD
controller.trackChanges { controller in
let newPlayers = controller.fetchedRecords
}
```
**Callbacks are invoked asynchronously.** See [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) for more information.
**Values fetched from inside callbacks may be inconsistent with the controller's records.** This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen.
To avoid inconsistencies, provide a `fetchAlongside` argument to the `trackChanges` method, as below:
```swift
controller.trackChanges(
fetchAlongside: { db in
// Fetch any extra value, for example the number of fetched records:
return try Player.fetchCount(db)
},
didChange: { (controller, count) in
// The extra value is the second argument.
let recordsCount = controller.fetchedRecords.count
assert(count == recordsCount) // guaranteed
})
```
Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch.
```swift
controller.trackErrors { (controller, error) in
print("Missed a transaction because \(error)")
}
```
## Modifying the Fetch Request
You can change a fetched records controller's fetch request or SQL query.
```swift
controller.setRequest(Player.order(Column("name")))
controller.setRequest(sql: "SELECT ...", arguments: ...)
```
The [notification callbacks](#the-changes-notifications) are notified of eventual changes if the new request fetches a different set of records.
> :point_up: **Note**: This behavior differs from Core Data's NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced.
**Change callbacks are invoked asynchronously.** This means that modifying the request from the main thread does *not* immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called:
```swift
// Change request on the main thread:
controller.setRequest(Player.order(Column("name")))
// Here callbacks have not been called yet.
// You can cancel them, and refresh records immediately:
try controller.performFetch()
```
## Table and Collection Views
FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content.
For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key:
```swift
class Player : TableRecord { ... }
let controller = FetchedRecordsController(
dbQueue,
request: Player.all())
```
For other types, the fetched records controller needs you to be more explicit:
```swift
let controller = FetchedRecordsController(
dbQueue,
request: ...,
isSameRecord: { (player1, player2) in player1.id == player2.id })
```
### Implementing the Table View Datasource Methods
The table view data source asks the fetched records controller to provide relevant information:
```swift
func numberOfSections(in tableView: UITableView) -> Int {
fetchedRecordsController.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
fetchedRecordsController.sections[section].numberOfRecords
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
let record = fetchedRecordsController.record(at: indexPath)
// Configure the cell
return cell
}
```
> :point_up: **Note**: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section.
### Implementing Table View Updates
When changes in the fetched records should reload the whole table view, you can simply tell so:
```swift
controller.trackChanges { [unowned self] _ in
self.tableView.reloadData()
}
```
Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView.
#### Typical Table View Updates
For animated table view updates, use the `willChange` and `didChange` callbacks to bracket events provided by the fetched records controller, as illustrated in the following example:
```swift
// Assume self has a tableView property, and a cell configuration
// method named configure(_:at:).
controller.trackChanges(
// controller's records are about to change:
willChange: { [unowned self] _ in
self.tableView.beginUpdates()
},
// notification of individual record changes:
onChange: { [unowned self] (controller, record, change) in
switch change {
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
case .deletion(let indexPath):
self.tableView.deleteRows(at: [indexPath], with: .fade)
case .update(let indexPath, _):
if let cell = self.tableView.cellForRow(at: indexPath) {
self.configure(cell, at: indexPath)
}
case .move(let indexPath, let newIndexPath, _):
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.insertRows(at: [newIndexPath], with: .fade)
// // Alternate technique which actually moves cells around:
// let cell = self.tableView.cellForRow(at: indexPath)
// self.tableView.moveRow(at: indexPath, to: newIndexPath)
// if let cell = cell {
// self.configure(cell, at: newIndexPath)
// }
}
},
// controller's records have changed:
didChange: { [unowned self] _ in
self.tableView.endUpdates()
})
```
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
>
> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
## FetchedRecordsController Concurrency
**A fetched records controller *can not* be used from any thread.**
When the database itself can be read and modified from [any thread](../README.md#database-connections), fetched records controllers **must** be used from the main thread. Record changes are also [notified](#the-changes-notifications) on the main thread.
**Change callbacks are invoked asynchronously.** This means that changes made from the main thread are *not* immediately notified. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called:
```swift
// Change database on the main thread:
try dbQueue.write { db in
try Player(...).insert(db)
}
// Here callbacks have not been called yet.
// You can cancel them, and refresh records immediately:
try controller.performFetch()
```
> :point_up: **Note**: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well.
>
> ```swift
> let queue = DispatchQueue()
> queue.async {
> let controller = try FetchedRecordsController(..., queue: queue)
> controller.trackChanges { /* in queue */ }
> try controller.performFetch()
> }
> ```
[ValueObservation]: ../README.md#valueobservation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[TableRecord]: ../README.md#tablerecord-protocol
+688
View File
@@ -0,0 +1,688 @@
Full-Text Search
================
**Full-Text Search is an efficient way to search a corpus of textual documents.**
```swift
// Create full-text tables
try db.create(virtualTable: "book", using: FTS4()) { t in // or FTS3(), or FTS5()
t.column("author")
t.column("title")
t.column("body")
}
// Populate full-text table with records or SQL
try Book(...).insert(db)
try db.execute(
sql: "INSERT INTO book (author, title, body) VALUES (?, ?, ?)",
arguments: [...])
// Build search patterns
let pattern = FTS3Pattern(matchingPhrase: "Moby-Dick")
// Search with the query interface or SQL
let books = try Book.matching(pattern).fetchAll(db)
let books = try Book.fetchAll(db,
sql: "SELECT * FROM book WHERE book MATCH ?",
arguments: [pattern])
```
- **[Choosing the Full-Text Engine](#choosing-the-full-text-engine)**
- **[Enabling FTS5 Support](#enabling-fts5-support)**
- **Create Full-Text Virtual Tables**: [FTS3/4](#create-fts3-and-fts4-virtual-tables), [FTS5](#create-fts5-virtual-tables)
- **Choosing a Tokenizer**: [FTS3/4](#fts3-and-fts4-tokenizers), [FTS5](#fts5-tokenizers)
- **Search Patterns**: [FTS3/4](#fts3pattern), [FTS5](#fts5pattern)
- **Sorting by Relevance**: [FTS5](#fts5-sorting-by-relevance)
- **External Content Full-Text Tables**: [FTS4/5](#external-content-full-text-tables)
- **Full-Text Record**s: [FTS3/4/5](#full-text-records)
- **Unicode Full-Text Gotchas**: [FTS3/4/5](#unicode-full-text-gotchas). Unicorns don't exist.
- **Custom Tokenizers**: [FTS5](FTS5Tokenizers.md). Leverage extra full-text features such as synonyms or stop words. Avoid [unicode gotchas](#unicode-full-text-gotchas).
- **Sample Code**: [WWDC Companion](https://github.com/groue/WWDCCompanion), an iOS app that stores, displays, and lets the user search the WWDC 2016 sessions.
## Choosing the Full-Text Engine
**SQLite supports three full-text engines: [FTS3, FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).**
Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this does not really tell which engine to choose for your application. Instead, make your choice depend on:
- **The full-text features needed by the application**:
| Full-Text Needs | FTS3 | FTS4 | FTS5 |
| -------------------------------------------------------------------------- | :--: | :--: | :--: |
| :question: Queries | | | |
| **Words searches** (documents that contain "database") | X | X | X |
| **Prefix searches** (documents that contain a word starting with "data") | X | X | X |
| **Phrases searches** (documents that contain the phrase "SQLite database") | X | X | X |
| **Boolean searches** (documents that contain "SQLite" or "database") | X | X | X |
| **Proximity search** (documents that contain "SQLite" near "database") | X | X | X |
| :scissors: Tokenization | | | |
| **Ascii case insensitivity** (have "DATABASE" match "database") | X | X | X |
| **Unicode case insensitivity** (have "ÉLÉGANCE" match "élégance") | X | X | X |
| **Latin diacritics insensitivity** (have "elegance" match "élégance") | X | X | X |
| **English Stemming** (have "frustration" match "frustrated") | X | X | X |
| **English Stemming and Ascii case insensitivity** | X | X | X |
| **English Stemming and Unicode case insensitivity** | | | X |
| **English Stemming and Latin diacritics insensitivity** | | | X |
| **Synonyms** (have "1st" match "first") | ¹ | ¹ | X ² |
| **Pinyin and Romaji** (have "romaji" match "ローマ字") | ¹ | ¹ | X ² |
| **Stop words** (don't index, and don't match words like "and" and "the") | ¹ | ¹ | X ² |
| **Spell checking** (have "alamaba" match "alabama") | ¹ | ¹ | ¹ |
| :bowtie: Other Features | | | |
| **Ranking** (sort results by relevance) | ¹ | ¹ | X |
| **Snippets** (display a few words around a match) | X | X | X |
¹ Requires extra setup, possibly hard to implement.
² Requires a [custom tokenizer](FTS5Tokenizers.md).
For a full feature list, read the SQLite documentation. Some missing features can be achieved with extra application code.
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. FTS4 only supports content compression.
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
- **The SQLite library integrated in your application.** The version of SQLite that ships with iOS, macOS, tvOS and watchOS supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see [Enabling FTS5 Support](#enabling-fts5-support).
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
> :point_up: **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
## Create FTS3 and FTS4 Virtual Tables
**FTS3 and FTS4 full-text tables store and index textual content.**
Create tables with the `create(virtualTable:using:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts3(content)
try db.create(virtualTable: "document", using: FTS3()) { t in
t.column("content")
}
// CREATE VIRTUAL TABLE document USING fts4(content)
try db.create(virtualTable: "document", using: FTS4()) { t in
t.column("content")
}
```
**All columns in a full-text table contain text.** If you need to index a table that contains other kinds of values, you need an ["external content" full-text table](#external-content-full-text-tables).
You can specify a [tokenizer](#fts3-and-fts4-tokenizers):
```swift
// CREATE VIRTUAL TABLE book USING fts4(
// tokenize=porter,
// author,
// title,
// body
// )
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .porter
t.column("author")
t.column("title")
t.column("body")
}
```
FTS4 supports [options](https://www.sqlite.org/fts3.html#fts4_options):
```swift
// CREATE VIRTUAL TABLE book USING fts4(
// content,
// uuid,
// content="",
// compress=zip,
// uncompress=unzip,
// prefix="2,4",
// notindexed=uuid,
// languageid=lid
// )
try db.create(virtualTable: "document", using: FTS4()) { t in
t.content = ""
t.compress = "zip"
t.uncompress = "unzip"
t.prefixes = [2, 4]
t.column("content")
t.column("uuid").notIndexed()
t.column("lid").asLanguageId()
}
```
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
See [SQLite documentation](https://www.sqlite.org/fts3.html) for more information.
## FTS3 and FTS4 Tokenizers
**A tokenizer defines what "matching" means.** Depending on the tokenizer you choose, full-text searches won't return the same results.
SQLite ships with three built-in FTS3/4 tokenizers: `simple`, `porter` and `unicode61` that use different algorithms to match queries with indexed content:
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
// Pick one:
t.tokenizer = .simple // default
t.tokenizer = .porter
t.tokenizer = .unicode61(...)
}
```
See below some examples of matches:
| content | query | simple | porter | unicode61 |
| ----------- | ---------- | :----: | :----: | :-------: |
| Foo | Foo | X | X | X |
| Foo | FOO | X | X | X |
| Jérôme | Jérôme | X ¹ | X ¹ | X ¹ |
| Jérôme | JÉRÔME | | | X ¹ |
| Jérôme | Jerome | | | X ¹ |
| Database | Databases | | X | |
| Frustration | Frustrated | | X | |
¹ Don't miss [Unicode Full-Text Gotchas](#unicode-full-text-gotchas)
- **simple**
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .simple // default
}
```
The default "simple" tokenizer is case-insensitive for ASCII characters. It matches "foo" with "FOO", but not "Jérôme" with "JÉRÔME".
It does not provide stemming, and won't match "databases" with "database".
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
- **porter**
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .porter
}
```
The "porter" tokenizer compares English words according to their roots: it matches "database" with "databases", and "frustration" with "frustrated".
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
- **unicode61**
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .unicode61()
t.tokenizer = .unicode61(diacritics: .keep)
}
```
The "unicode61" tokenizer is case-insensitive for unicode characters. It matches "Jérôme" with "JÉRÔME".
It strips diacritics from latin script characters by default, and matches "jérôme" with "jerome". This behavior can be disabled, as in the example above.
It does not provide stemming, and won't match "databases" with "database".
See [SQLite tokenizers](https://www.sqlite.org/fts3.html#tokenizer) for more information.
## FTS3Pattern
**Full-text search in FTS3 and FTS4 tables is performed with search patterns:**
- `database` matches all documents that contain "database"
- `data*` matches all documents that contain a word starting with "data"
- `SQLite database` matches all documents that contain both "SQLite" and "database"
- `SQLite OR database` matches all documents that contain "SQLite" or "database"
- `"SQLite database"` matches all documents that contain the "SQLite database" phrase
**Not all search patterns are valid**: they must follow the [Full-Text Index Queries Grammar](https://www.sqlite.org/fts3.html#full_text_index_queries).
The FTS3Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
```swift
struct FTS3Pattern {
init(rawPattern: String) throws
init?(matchingAnyTokenIn string: String)
init?(matchingAllTokensIn string: String)
init?(matchingPhrase string: String)
}
```
The first initializer validates your raw patterns against the query grammar, and may throw a [DatabaseError](../README.md#databaseerror):
```swift
// OK: FTS3Pattern
let pattern = try FTS3Pattern(rawPattern: "sqlite AND database")
// DatabaseError: malformed MATCH expression: [AND]
let pattern = try FTS3Pattern(rawPattern: "AND")
```
The three other initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
```swift
let query = "SQLite database"
// Matches documents that contain "SQLite" or "database"
let pattern = FTS3Pattern(matchingAnyTokenIn: query)
// Matches documents that contain both "SQLite" and "database"
let pattern = FTS3Pattern(matchingAllTokensIn: query)
// Matches documents that contain "SQLite database"
let pattern = FTS3Pattern(matchingPhrase: query)
```
They return nil when no pattern could be built from the input string:
```swift
let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
sql: "SELECT * FROM document WHERE content MATCH ?",
arguments: [pattern])
```
Use them in the [query interface](../README.md#the-query-interface):
```swift
// Search in all columns
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
```
## Enabling FTS5 Support
When the FTS3 and FTS4 full-text engines don't suit your needs, you may want to use FTS5. See [Choosing the Full-Text Engine](#choosing-the-full-text-engine) to help you make a decision.
The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you'll need to install GRDB with one of those installation techniques:
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with FTS5 support, but only on iOS 11.4+ / macOS 10.13+ / tvOS 11.4+ / watchOS 4.3+:
```ruby
pod 'GRDB.swift'
platform :ios, '11.4' # or above
post_install do |installer|
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
target.build_configurations.each do |config|
config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5"
end
end
end
```
> :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
> :point_up: **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)):
```ruby
pod 'GRDB.swift/SQLCipher'
```
3. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_FTS5` compilation option.
## Create FTS5 Virtual Tables
**FTS5 full-text tables store and index textual content.**
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
Create FTS5 tables with the `create(virtualTable:using:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts5(content)
try db.create(virtualTable: "document", using: FTS5()) { t in
t.column("content")
}
```
**All columns in a full-text table contain text.** If you need to index a table that contains other kinds of values, you need an ["external content" full-text table](#external-content-full-text-tables).
You can specify a [tokenizer](#fts5-tokenizers):
```swift
// CREATE VIRTUAL TABLE book USING fts5(
// tokenize='porter',
// author,
// title,
// body
// )
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .porter()
t.column("author")
t.column("title")
t.column("body")
}
```
FTS5 supports [options](https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization):
```swift
// CREATE VIRTUAL TABLE book USING fts5(
// content,
// uuid UNINDEXED,
// content='table',
// content_rowid='id',
// prefix='2 4',
// columnsize=0,
// detail=column
// )
try db.create(virtualTable: "document", using: FTS5()) { t in
t.column("content")
t.column("uuid").notIndexed()
t.content = "table"
t.contentRowID = "id"
t.prefixes = [2, 4]
t.columnSize = 0
t.detail = "column"
}
```
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
See [SQLite documentation](https://www.sqlite.org/fts5.html) for more information.
## FTS5 Tokenizers
**A tokenizer defines what "matching" means.** Depending on the tokenizer you choose, full-text searches won't return the same results.
SQLite ships with three built-in FTS5 tokenizers: `ascii`, `porter` and `unicode61` that use different algorithms to match queries with indexed content.
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
// Pick one:
t.tokenizer = .unicode61() // default
t.tokenizer = .unicode61(...)
t.tokenizer = .ascii
t.tokenizer = .porter(...)
}
```
See below some examples of matches:
| content | query | ascii | unicode61 | porter on ascii | porter on unicode61 |
| ----------- | ---------- | :----: | :-------: | :-------------: | :-----------------: |
| Foo | Foo | X | X | X | X |
| Foo | FOO | X | X | X | X |
| Jérôme | Jérôme | X ¹ | X ¹ | X ¹ | X ¹ |
| Jérôme | JÉRÔME | | X ¹ | | X ¹ |
| Jérôme | Jerome | | X ¹ | | X ¹ |
| Database | Databases | | | X | X |
| Frustration | Frustrated | | | X | X |
¹ Don't miss [Unicode Full-Text Gotchas](#unicode-full-text-gotchas)
- **unicode61**
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .unicode61()
t.tokenizer = .unicode61(diacritics: .keep)
}
```
The default "unicode61" tokenizer is case-insensitive for unicode characters. It matches "Jérôme" with "JÉRÔME".
It strips diacritics from latin script characters by default, and matches "jérôme" with "jerome". This behavior can be disabled, as in the example above.
It does not provide stemming, and won't match "databases" with "database".
- **ascii**
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .ascii
}
```
The "ascii" tokenizer is case-insensitive for ASCII characters. It matches "foo" with "FOO", but not "Jérôme" with "JÉRÔME".
It does not provide stemming, and won't match "databases" with "database".
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
- **porter**
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .porter() // porter wrapping unicode61 (the default)
t.tokenizer = .porter(.ascii) // porter wrapping ascii
t.tokenizer = .porter(.unicode61(diacritics: .keep)) // porter wrapping unicode61 without diacritics stripping
}
```
The porter tokenizer is a wrapper tokenizer which compares English words according to their roots: it matches "database" with "databases", and "frustration" with "frustrated".
It strips diacritics from latin script characters if it wraps unicode61, and does not if it wraps ascii (see the example above).
See [SQLite tokenizers](https://www.sqlite.org/fts5.html#tokenizers) for more information, and [custom FTS5 tokenizers](FTS5Tokenizers.md) in order to add your own tokenizers.
## FTS5Pattern
**Full-text search in FTS5 tables is performed with search patterns:**
- `database` matches all documents that contain "database"
- `data*` matches all documents that contain a word starting with "data"
- `SQLite database` matches all documents that contain both "SQLite" and "database"
- `SQLite OR database` matches all documents that contain "SQLite" or "database"
- `"SQLite database"` matches all documents that contain the "SQLite database" phrase
**Not all search patterns are valid**: they must follow the [Full-Text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
The FTS5Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
```swift
extension Database {
func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern
}
struct FTS5Pattern {
init?(matchingAnyTokenIn string: String)
init?(matchingAllTokensIn string: String)
init?(matchingPhrase string: String)
}
```
The `Database.makeFTS5Pattern(rawPattern:forTable:)` method validates your raw patterns against the query grammar and the columns of the targeted table, and may throw a [DatabaseError](../README.md#databaseerror):
```swift
// OK: FTS5Pattern
try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "book")
// DatabaseError: syntax error near \"AND\"
try db.makeFTS5Pattern(rawPattern: "AND", forTable: "book")
// DatabaseError: no such column: missing
try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "book")
```
The FTS5Pattern initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
```swift
let query = "SQLite database"
// Matches documents that contain "SQLite" or "database"
let pattern = FTS5Pattern(matchingAnyTokenIn: query)
// Matches documents that contain both "SQLite" and "database"
let pattern = FTS5Pattern(matchingAllTokensIn: query)
// Matches documents that contain "SQLite database"
let pattern = FTS5Pattern(matchingPhrase: query)
// Matches documents that start with "SQLite database"
let pattern = FTS5Pattern(matchingPrefixPhrase: query)
```
They return nil when no pattern could be built from the input string:
```swift
let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
sql: "SELECT * FROM document WHERE document MATCH ?",
arguments: [pattern])
```
Use them in the [query interface](../README.md#the-query-interface):
```swift
let documents = try Document.matching(pattern).fetchAll(db)
```
## FTS5: Sorting by Relevance
**FTS5 can sort results by relevance** (most to least relevant):
```swift
// SQL
let documents = try Document.fetchAll(db,
sql: "SELECT * FROM document WHERE document MATCH ? ORDER BY rank",
arguments: [pattern])
// Query Interface
let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
```
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results)
GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Application Tips](https://www.sqlite.org/fts3.html#appendix_a) if you really need it.
## External Content Full-Text Tables
**An external content table does not store the indexed text.** Instead, it indexes the text stored in another table.
This is very handy when you want to index a table that can not be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
The two tables must be kept up-to-date, so that the full-text index matches the content of the regular table. This synchronization happens automatically if you use the `synchronize(withTable:)` method in your full-text table definition:
```swift
// A regular table
try db.create(table: "book") { t in
t.column("author", .text)
t.column("title", .text)
t.column("content", .text)
...
}
// A full-text table synchronized with the regular table
try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
t.synchronize(withTable: "book")
t.column("author")
t.column("title")
t.column("content")
}
```
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
### Deleting Synchronized Full-Text Tables
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
```swift
// Create tables
try db.create(table: "book") { t in
...
}
try db.create(virtualTable: "book_ft", using: FTS4()) { t in
t.synchronize(withTable: "book")
...
}
// Drop full-text table
try db.drop(table: "book_ft")
try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
```
> :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
>
> ```swift
> // Drop full-text table
> try db.drop(table: "book_ft")
> try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
> try db.dropFTS4SynchronizationTriggers(forTable: "book") // Support for GRDB <= 2.3.1
> ```
### Querying External Content Full-Text Tables
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
```swift
// SQLite error 1: unable to use function MATCH in the requested context
// SELECT * FROM book WHERE book MATCH '...'
let books = Book.matching(pattern).fetchAll(db)
```
The solution is to perform a joined request, using raw SQL:
```swift
let sql = """
SELECT book.*
FROM book
JOIN book_ft
ON book_ft.rowid = book.rowid
AND book_ft MATCH ?
"""
let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
```
## Full-Text Records
**You can define [record](../README.md#records) types around the full-text virtual tables.**
However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`.
You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key.
## Unicode Full-Text Gotchas
The SQLite built-in tokenizers for [FTS3, FTS4](#fts3-and-fts4-tokenizers) and [FTS5](#fts5-tokenizers) are generally unicode-aware, with a few caveats, and limitations.
Generally speaking, matches may fail when content and query don't use the same [unicode normalization](http://unicode.org/reports/tr15/). SQLite actually exhibits inconsistent behavior in this regard.
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/reference/swift/string/1407210-precomposedstringwithcanonicalma) to turn a string into NFC.
Besides, if you want "fi" to match the ligature "&#xfb01;" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/reference/swift/string/1407834-precomposedstringwithcompatibili) to turn a string into NFKC.
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method can help.
GRDB lets you write [custom FTS5 tokenizers](FTS5Tokenizers.md) that can transparently deal with all these issues. For FTS3 and FTS4, you'll need to pre-process your strings before injecting them in the full-text engine.
Happy indexing!
-533
View File
@@ -1,533 +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) as columns:
```swift
// GRDB 3
struct Player: Codable, FetchableRecord, PersistableRecord {
var id: Int64
var name: String
var score: Int
// Add ColumnExpression conformance
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
}
}
extension Player {
static func filter(name: String) -> QueryInterfaceRequest<Player> {
return filter(CodingKeys.name == name)
}
static var maximumScore: QueryInterfaceRequest<Int> {
return select(max(CodingKeys.score), as: Int.self)
}
}
```
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol whenever you define a custom column type:
```swift
struct TypedColumn: ColumnExpression {
var name: String
var sqlType: String
}
let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
## 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 slighly 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
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[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
+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
@@ -5,20 +5,25 @@ This guide aims at helping you leverage the best of GRDB [records] and [associat
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
To support this guide, we'll design a simply library application that lets the user crawl through books and their authors.
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Record Types are Responsible for Their Tables]
- [Persistable Record Types are Responsible for Their Tables]
- [Define Record Requests]
- [Compose Records]
- [Fetch In Time]
- [How to Design Database Managers]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
SQLite is a robust database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
This is important because we developers write bugs, and some of them will ship in the wild, affecting your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes is a robust **database schema**.
This is why we recommend defining a **robust database schema** even before playing with record types.
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
@@ -29,31 +34,33 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("country", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (4)
t.column("authorId", .integer) // (5)
.notNull() // (6)
.indexed() // (7)
.references("author", onDelete: .cascade) // (8)
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
try migrator.migrate(dbQueue)
```
1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. A book must have a title.
5. The `book.authorId` column is used to link a book to the author it belongs to.
6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
7. The `book.authorId` column is indexed in order to ease the selection of an author's books.
8. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
>
@@ -82,27 +89,36 @@ Thanks to this database schema, you can be confident so no matter how wrong our
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
## Record Types are Responsible for Their Tables
## Persistable Record Types are Responsible for Their Tables
Define one record type per database table.
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
```swift
struct Author: Codable, FetchableRecord, MutablePersistableRecord {
struct Author: Codable {
var id: Int64?
var name: String
var country: String?
}
struct Book: Codable {
var id: Int64?
var authorId: Int64
var title: String
}
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
struct Book: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64?
var authorId: Int64
var title: String
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
@@ -116,9 +132,11 @@ That's it. The `Author` type can read and write in the `author` database table.
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method:
>
> ```swift
> var author = Author(id: nil, name: "Hermann Melville")
> try author.insert(db)
> print(author.id) // Some non-nil id
> try dbQueue.write { db in
> var author = Author(id: nil, name: "Hermann Melville", country: "United States")
> try author.insert(db)
> print(author.id!) // Guaranteed non-nil id
> }
> ```
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
@@ -128,87 +146,221 @@ Applying the **[Single Responsibility Principle]** has a consequence: don't even
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
## Compose Records
## Define Record Requests
Now that we have two types for authors and books, we'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations, along with their companion properties:
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
```swift
// For a codable record
extension Author {
static let books = hasMany(Book.self)
var books: QueryInterfaceRequest<Book> {
return request(for: Author.books)
}
}
extension Book {
static let author = belongsTo(Author.self)
var author: QueryInterfaceRequest<Author> {
return request(for: Book.author)
// Define database columns from CodingKeys
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let country = Column(CodingKeys.country)
}
}
```
Thanks to this setup, you can fetch associated records:
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
```swift
// Fetch an author and its books
struct AuthorInfo {
var author: Author
var books: [Book]
// For a non-codable record
extension Author {
// Define database columns as an enum
enum Columns: String, ColumnExpression {
case id, name, country
}
}
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: 123) else { return nil }
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
Here is how you define those requests:
```swift
// Some requests of Author --------------------v
extension DerivableRequest where RowDecoder == Author {
/// Returns a request for all authors ordered by name, in a localized
/// case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Returns a request for all authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
}
```
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
```swift
try dbQueue.read { db in
let sortedAuthors: [Author] = try Author.all()
.orderByName()
.fetchAll(db)
let frenchAuthors: [Author] = try Author.all()
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthors: [Author] = try Author.all()
.filter(country: "Spain")
.orderByName()
.fetchAll(db)
}
```
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
```swift
// Some requests of Book
extension DerivableRequest where RowDecoder == Book {
/// Returns a request for all books from a country
func filter(authorCountry: String) -> Self {
// A book is from a country if it can be
// joined with an author from that country:
// ---------------------------v
joining(required: Book.author.filter(country: authorCountry))
}
}
// Fetch all authorships
try dbQueue.read { db in
let italianBooks = try Book.all()
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
```swift
// More requests of Author -------------------------v
extension QueryInterfaceRequest where RowDecoder == Author {
/// Returns a request for all authors with at least one book
func havingBooks() -> QueryInterfaceRequest<Author> {
having(Author.books.isEmpty == false)
}
}
```
Those requests defined on `QueryInterfaceRequest` still compose fluently:
```swift
try dbQueue.read { db in
let sortedFrenchAuthorsHavingBooks = try Author.all()
.filter(country: "France")
.havingBooks() // <-
.orderByName()
.fetchAll(db)
}
```
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
```swift
extension MySingletonRecord {
/// The one any only record stored in the database
static let shared = all().limit(1)
}
let singleton = try dbQueue.read { db
try MySingletonRecord.shared.fetchOne(db)
}
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
```swift
extension Author {
static let books = hasMany(Book.self)
}
extension Book {
static let author = belongsTo(Author.self)
}
```
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
```swift
// Fetch all authors and their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
let request = Author.annotated(with: Author.books.count)
return try AuthorInfo.fetchAll(db, request)
}
// Fetch all Colombian books and their authors:
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
let request = Book.including(required: Book.author)
let request = Book.including(required: Book.author.filter(country: "Colombia"))
return try Authorship.fetchAll(db, request)
}
```
The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
That is because other ORMs perform lazy loading:
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
```ruby
# Ruby's Active Record
author = Author.find(123) # fetch author
books = author.books # lazily fetches books on demand
```
> :question: **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
>
> That is because other ORMs perform lazy loading:
>
> ```ruby
> # Ruby's Active Record
> author = Author.find(123) # fetch author
> book_count = author.books.count # lazily counts books on demand
> ```
>
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
>
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. This is why GRDB has removed lazy loading from the list of desirable features. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below:
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
1. Prepare the application screen that lists all authors:
```swift
let authors: [Author] = dbQueue.read { db in
Author.order(Colum("name")).fetchAll(db)
let authors: [Author] = try dbQueue.read { db in
try Author.all().orderByName().fetchAll(db)
}
```
2. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
struct AuthorInfo: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: authorId) else { return nil }
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
let request = Author
.filter(key: authorId)
.including(all: Author.books)
return try AuthorInfo.fetchOne(db, request)
}
```
@@ -228,79 +380,296 @@ The consequence is that each part of your application will load the data it need
}
```
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less.
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
## Fetch In Time
> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**.
A last extension on your record types will further help navigation from records to associated ones:
```swift
// NOT RECOMMENDED
let bookId = 123
// Two fetches not grouped in a single `read` block:
if let book = databaseManager.getBook(id: bookId) {
let author = databaseManager.getAuthor(id: book.authorId)!
// use book and author
}
// RECOMMENDED (without associations)
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
// All fetches are grouped in a single `read` block:
if let book = try Book.fetchOne(db, key: bookId) {
let author = try Author.fetchOne(db, key: book.authorId)!
return BookInfo(book: book, author: author)
} else {}
return nil
extension Author {
/// The request for the author's books
var books: QueryInterfaceRequest<Book> {
request(for: Author.books)
}
}
if let bookInfo = bookInfo {
// use bookInfo
}
// RECOMMENDED (with associations)
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
// All fetches are grouped in a single `read` block:
let request = Book
.filter(key: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
if let bookInfo = bookInfo {
// use bookInfo
extension Book {
/// The request for the author of the book
var author: QueryInterfaceRequest<Author> {
request(for: Book.author)
}
}
```
This tip is paramount, and deserves an explanation because too many database libraries out there tend to completely disregard multi-threading gotchas.
Those properties provide an alternative way to feed our application:
When you do not fetch your data in a single database access block, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss.
1. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(
author: author,
books: books)
}
```
Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
2. Prepare the application screen that displays a book information:
```swift
struct BookInfo {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
guard let book = try Book.fetchOne(db, key: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
```
```ruby
# Ruby's Active Record
if book = Book.find(123) # fetch book
author = book.author # fetch author
# use book and author
end
## How to Design Database Managers
Many developpers want to hide GRDB database queues and pools inside "database managers":
```swift
// LibraryManager grants access to the library database.
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
```
The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
Design your database managers with the [GRDB concurrency rules] in mind.
GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit with database access methods such as `dbQueue.read`.
Practically, let's start with a naive example, and gradually improve it:
Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
```swift
// A naive manager that we will improve
class NaiveLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) -> Author? {
do {
return try dbQueue.read { db in
try Author.fetchOne(db, key: id)
}
} catch {
return nil
}
}
func book(id: Int64) -> Book? {
do {
return try dbQueue.read { db in
try Book.fetchOne(db, key: id)
}
} catch {
return nil
}
}
func books(writtenBy author: Author) -> [Book] {
do {
return try dbQueue.read { db in
try author.books.fetchAll(db)
}
} catch {
return []
}
}
}
```
**This manager can be improved in two ways.**
- [Embrace Errors]
- [Thread-Safety is also an Application Concern]
### Embrace Errors
Have database managers throw database errors instead of catching them.
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
Exposing errors will help you building your application:
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
- You will be able to opt in for advanced OS features like [data protection].
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
```swift
// An improved manager that does not hide errors
class ImprovedLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) throws -> Author? {
try dbQueue.read { db in
try Author.fetchOne(db, key: id)
}
}
func book(id: Int64) throws -> Book? {
try dbQueue.read { db in
try Book.fetchOne(db, key: id)
}
}
func books(writtenBy author: Author) throws -> [Book] {
try dbQueue.read { db in
try author.books.fetchAll(db)
}
}
}
```
### Thread-Safety is also an Application Concern
Now, let's make our database manager **thread-safe**.
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
For example, in the screen that displays an author and her books, we would write:
```swift
let authorId = 123
if let author = libraryManager.author(id: authorId) {
let books = libraryManager.books(writtenBy: author)
// Use author and books
}
```
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
This gives a much safer manager:
```swift
// A manager that actually manages
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
// Feeds the list of authors
extension LibraryManager {
struct AuthorListItem: Decodable, FetchableRecord {
let author: Author
let bookCount: Int
}
func authorList() throws -> [AuthorListItem] {
try dbQueue.read { db in
let request = Author
.annotated(with: Author.books.count)
.orderByName()
return try AuthorListItem.fetchAll(db, request)
}
}
}
// Feeds a book screen
extension LibraryManager {
struct BookInfo {
var book: Book
var author: Author
}
func bookInfo(bookId: Int64) throws -> BookInfo? {
try dbQueue.read { db in
guard let book = try Book.fetchOne(db, key: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
}
}
// Feeds an author screen
extension LibraryManager {
struct AuthorInfo {
var author: Author
var books: [Book]
}
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
}
}
```
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
> :question: **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
>
> ```ruby
> # Ruby's Active Record
> book = Book.find(123) # fetch book
> author = book.author # fetch author
> # use book and author
> ```
>
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
>
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
>
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
>
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
## Observe the Database and Refetch when Needed
We have seen above that the Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it.
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
Fetched information eventually becomes obsoleted, as the application modifies the database content.
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
@@ -310,7 +679,7 @@ Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view.
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
@@ -318,7 +687,6 @@ Instead, have a look at [Database Observation]:
>
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
[records]: ../README.md#records
[associations]: AssociationsBasics.md
[FMDB]: https://github.com/ccgus/fmdb
@@ -337,14 +705,25 @@ Instead, have a look at [Database Observation]:
[migration]: ../README.md#migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: ../README.md#concurrency
[GRDB concurrency rules]: ../README.md#concurrency
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Database Observation]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[TransactionObserver]: ../README.md#transactionobserver-protocol
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Record Types are Responsible for Their Tables]: #record-types-are-responsible-for-their-tables
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[Fetch In Time]: #fetch-in-time
[How to Design Database Managers]: #how-to-design-database-managers
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
[query interface]: ../README.md#the-query-interface
[observe database changes]: ../README.md#database-changes-observation
[data protection]: ../README.md#data-protection
[Embrace Errors]: #embrace-errors
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema
[Association Aggregates]: AssociationsBasics.md#association-aggregates
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
@@ -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()
@@ -83,15 +83,17 @@ try dbQueue.write { db in
}
// Demo values: two Foo and one Bar
try db.execute("""
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
""", arguments: [
try db.execute(
sql: """
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
""",
arguments: [
"Foo", "Arthur", nil,
"Bar", nil, 100,
"Foo", "Barbara", nil,
])
])
}
//: We also need a method that decodes database rows into `Foo` or `Bar`
@@ -140,7 +142,7 @@ extension Base {
try dbQueue.read { db in
print("> KISS: Fetch from SQL")
let rows = try Row.fetchAll(db, "SELECT * FROM base") // Fetch database rows
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
let bases = rows.map { row in // Decode database rows
Base.decode(row: row)
}
@@ -210,13 +212,15 @@ extension Base: MyDatabaseDecoder {
//: **prepared statement**:
//:
//: try dbQueue.read { db in
//: let statement = try db.makeSelectStatement("SELECT ...")
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
//: try Base.fetchCursor(statement) // Cursor of Base
//: try Base.fetchAll(statement) // [Base]
//: try Base.fetchOne(statement) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from SelectStatement
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
// fetching parameters of GRDB. Make sure to accept them all:
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
@@ -239,7 +243,7 @@ extension MyDatabaseDecoder {
try dbQueue.read { db in
print("> Fetch from prepared statement")
let statement = try db.makeSelectStatement("SELECT * FROM base")
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
let bases = try Base.fetchAll(statement)
for base in bases {
print(base.description)
@@ -258,6 +262,8 @@ try dbQueue.read { db in
//: try Base.fetchOne(db, request) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from FetchRequest
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
@@ -293,16 +299,18 @@ try dbQueue.read { db in
//: try request.fetchOne(db) // Base?
//: }
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)
}
}
@@ -324,16 +332,18 @@ try dbQueue.read { db in
//: try Base.fetchOne(db) // Base?
//: }
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)
}
}
@@ -345,31 +355,32 @@ try dbQueue.read { db in
}
}
//: Finally, you don't have a true GRDB record unless it allows fetching from
//: raw SQL:
//: Finally, you can support raw SQL as well:
//:
//: try dbQueue.read { db in
//: try Base.fetchCursor(db, "SELECT ...") // Cursor of Base
//: try Base.fetchAll(db, "SELECT ...") // [Base]
//: try Base.fetchOne(db, "SELECT ...") // Base?
//: try Base.fetchAll(db,
//: sql: "SELECT ... WHERE name = ?",
//: arguments: ["O'Brien"]) // [Base]
//: }
extension MyDatabaseDecoder {
static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
return try fetchCursor(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
// MARK: - Fetch from SQL
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
return try fetchAll(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
return try fetchOne(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
try dbQueue.read { db in
print("> Fetch from SQL")
let bases = try Base.fetchAll(db, "SELECT * FROM base")
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
for base in bases {
print(base.description)
}
@@ -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
@@ -35,61 +35,52 @@ try dbQueue.inDatabase { db in
}
// Define the Player `Codable` that is a `FetchableRecord` and `MutablePersistableRecord`.
// Define the Player codable record type
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64
var name: String
var score: Int
// Add ColumnExpression to Codable's CodingKeys so that we can use them
// as database columns.
//
// See https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
// for more information about CodingKeys.
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
// Update a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
extension Player {
static func orderedById() -> QueryInterfaceRequest<Player> {
return order(CodingKeys.id)
}
}
// This is just the container of our incoming JSON
struct PlayersToSync: Codable {
let players: [Player]
}
// Make Player identifiable
extension Player: Identifiable { }
// Synchronizes the players table with a JSON payload
func synchronizePlayers(with jsonString: String, in db: Database) throws {
struct SyncData: Decodable {
let players: [Player]
}
let jsonData = jsonString.data(using: .utf8)!
let dataToSync = try JSONDecoder().decode(PlayersToSync.self, from: jsonData)
let syncData = try JSONDecoder().decode(SyncData.self, from: jsonData)
// Sort new players to sync by id:
let playersToSync = dataToSync.players.sorted { $0.id < $1.id }
// Sort players to sync by id:
let playersToSync = syncData.players.sorted { $0.id < $1.id }
// Sort database players by id:
let players = try Player.orderedById().fetchAll(db)
let players = try Player.orderByPrimaryKey().fetchAll(db)
// Now that both lists are sorted by id, we can compare them with
// the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770).
// SortedDifference (see https://github.com/groue/SortedDifference).
//
// We'll delete, insert or update players, depending on their presence
// in either lists.
for mergeStep in sortedMerge(
for change in SortedDifference(
left: players, // Database players
right: playersToSync, // PlayersToSync players (Decoded)
leftKey: { $0.id }, // The id of a database player
rightKey: { $0.id }) // The id of a PlayersToSync player
right: playersToSync) // PlayersToSync players (Decoded)
{
switch mergeStep {
switch change {
case .left(let player):
// Delete database player without matching JSON player:
try player.delete(db)
@@ -142,3 +133,20 @@ do {
try synchronizePlayers(with: jsonString2, in: db)
}
}
do {
let jsonString3 = """
{
"players": [
{ "id": 2, "name": "Barbara", "score": 3000},
{ "id": 3, "name": "Craig", "score": 500},
{ "id": 4, "name": "Daniel", "score": 1500},
]
}
"""
print("---\nImport \(jsonString3)")
try dbQueue.inDatabase { db in
// SELECT * FROM player ORDER BY id
try synchronizePlayers(with: jsonString3, in: db)
}
}
@@ -0,0 +1,245 @@
// Copyright (C) 2020 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/// Given two sequences (left and right), this sequence tells whether elements
/// are only found on the left, on the right, or on both sides.
public struct SortedDifference<LeftSequence, RightSequence, ID>: Sequence where
LeftSequence: Sequence,
RightSequence: Sequence,
ID: Comparable
{
private let left: LeftSequence
private let right: RightSequence
private let lID: (LeftSequence.Element) -> ID
private let rID: (RightSequence.Element) -> ID
/// Given two sequences (left and right), returns a sequence which tells
/// whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both input sequences do not have to share the same element type, but
/// their elements must share a common comparable id.
///
/// For example:
///
/// // Prints:
/// // - common(Left(id: 1), Right(id: 1))
/// // - left(Left(id: 2))
/// struct Left { var id: Int }
/// struct Right { var id: Int }
/// for change in SortedDifference(
/// left: [Left(id: 1), Left(id: 2)],
/// identifiedBy: { $0.id },
/// right: [Right(id: 1)],
/// identifiedBy: { $0.id })
/// {
/// print(change)
/// }
///
/// - precondition: Both input sequences must be sorted by id.
/// - precondition: Ids must be unique in each sequences.
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
/// - leftID: A function that returns the id of a left element.
/// - rightID: A function that returns the id of a right element.
public init(
left: LeftSequence,
identifiedBy leftID: @escaping (LeftSequence.Element) -> ID,
right: RightSequence,
identifiedBy rightID: @escaping (RightSequence.Element) -> ID)
{
self.left = left
self.right = right
self.lID = leftID
self.rID = rightID
}
public func makeIterator() -> Iterator {
Iterator(
lIterator: left.makeIterator(),
rIterator: right.makeIterator(),
lID: lID,
rID: rID)
}
public struct Iterator: IteratorProtocol {
private var lIterator: LeftSequence.Iterator
private var rIterator: RightSequence.Iterator
private var lOpt: LeftSequence.Element?
private var rOpt: RightSequence.Element?
private let lID: (LeftSequence.Element) -> ID
private let rID: (RightSequence.Element) -> ID
init(
lIterator: LeftSequence.Iterator,
rIterator: RightSequence.Iterator,
lID: @escaping (LeftSequence.Element) -> ID,
rID: @escaping (RightSequence.Element) -> ID)
{
self.lIterator = lIterator
self.rIterator = rIterator
self.lID = lID
self.rID = rID
self.lOpt = self.lIterator.next()
self.rOpt = self.rIterator.next()
}
public mutating func next() -> SortedDifferenceChange<LeftSequence.Element, RightSequence.Element>? {
switch (lOpt, rOpt) {
case let (lElem?, rElem?):
let (lID, rID) = (self.lID(lElem), self.rID(rElem))
if lID > rID {
rOpt = rIterator.next()
return .right(rElem)
} else if lID == rID {
(lOpt, rOpt) = (lIterator.next(), rIterator.next())
return .common(lElem, rElem)
} else {
lOpt = lIterator.next()
return .left(lElem)
}
case let (nil, rElem?):
rOpt = rIterator.next()
return .right(rElem)
case let (lElem?, nil):
lOpt = lIterator.next()
return .left(lElem)
case (nil, nil):
return nil
}
}
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension SortedDifference where
LeftSequence.Element: Identifiable,
RightSequence.Element: Identifiable,
LeftSequence.Element.ID == ID,
RightSequence.Element.ID == ID
{
/// Given two sequences (left and right), returns a sequence which tells
/// whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both input sequences do not have to share the same element type, but
/// their elements must share a common comparable id.
///
/// For example:
///
/// // Prints:
/// // - common(Left(id: 1), Right(id: 1))
/// // - left(Left(id: 2))
/// struct Left: Identifiable { var id: Int }
/// struct Right: Identifiable { var id: Int }
/// for change in SortedDifference(
/// left: [Left(id: 1), Left(id: 2)],
/// right: [Right(id: 1)])
/// {
/// print(change)
/// }
///
/// - precondition: Both input sequences must be sorted by id.
/// - precondition: Ids must be unique in each sequences.
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
public init(left: LeftSequence, right: RightSequence) {
self.init(
left: left,
identifiedBy: { $0.id },
right: right,
identifiedBy: { $0.id })
}
}
extension SortedDifference where
LeftSequence.Element: Comparable,
RightSequence.Element == LeftSequence.Element,
LeftSequence.Element == ID
{
/// Given two sequences (left and right), this sequence tells whether
/// elements are only found on the left, on the right, or on both sides.
///
/// For example:
///
/// // Prints:
/// // - common(1, 1)
/// // - left(2)
/// for change in SortedDifference(left: [1, 2], right: [1]) {
/// print(change)
/// }
///
/// - precondition: Both input sequences must be sorted.
/// - precondition: Both input sequences must contain unique elements.
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
public init(left: LeftSequence, right: RightSequence) {
self.init(
left: left,
identifiedBy: { $0 },
right: right,
identifiedBy: { $0 })
}
}
/// An element of the SortedDifference sequence.
public enum SortedDifferenceChange<Left, Right> {
/// An element only found in the left sequence
case left(Left)
/// An element only found in the right sequence
case right(Right)
/// Left and right elements share a common id
case common(Left, Right)
}
extension SortedDifferenceChange: CustomStringConvertible {
public var description: String {
switch self {
case let .left(lhs):
return "left(\(String(describing: lhs)))"
case let .right(rhs):
return "right(\(String(describing: rhs)))"
case let .common(lhs, rhs):
return "common(\(String(describing: lhs)), \(String(describing: rhs)))"
}
}
}
extension SortedDifferenceChange: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .left(lhs):
return "left(\(String(reflecting: lhs)))"
case let .right(rhs):
return "right(\(String(reflecting: rhs)))"
case let .common(lhs, rhs):
return "common(\(String(reflecting: lhs)), \(String(reflecting: rhs)))"
}
}
}
extension SortedDifferenceChange: Equatable where
Left: Equatable,
Right: Equatable
{ }
@@ -13,9 +13,9 @@ try! dbQueue.inDatabase { db in
t.column("name", .text)
}
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
let names = try String.fetchAll(db, "SELECT name FROM persons")
let names = try String.fetchAll(db, sql: "SELECT name FROM persons")
print(names)
}
@@ -9,7 +9,7 @@
//: Tour
//: ======
//:
//: This playground is a tour of GRDB.
//: This playground is a quick tour of GRDB.
import GRDB
import CoreLocation
@@ -26,44 +26,45 @@ let dbQueue = DatabaseQueue(configuration: configuration)
//: Execute SQL queries
try dbQueue.inDatabase { db in
try db.execute(
"CREATE TABLE pointOfInterests (" +
"id INTEGER PRIMARY KEY, " +
"title TEXT, " +
"favorite BOOLEAN NOT NULL, " +
"latitude DOUBLE NOT NULL, " +
"longitude DOUBLE NOT NULL" +
")")
try db.execute(sql: """
CREATE TABLE place (
id INTEGER PRIMARY KEY,
title TEXT,
favorite BOOLEAN NOT NULL,
latitude DOUBLE NOT NULL,
longitude DOUBLE NOT NULL
)
""")
try db.execute(
"INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " +
"VALUES (?, ?, ?, ?)",
arguments: ["Paris", true, 48.85341, 2.3488])
try db.execute(sql: """
INSERT INTO place (title, favorite, latitude, longitude)
VALUES (?, ?, ?, ?)
""", arguments: ["Paris", true, 48.85341, 2.3488])
let parisId = db.lastInsertedRowID
}
//: Fetch database rows and values
try dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
while let row = try rows.next() {
let title: String = row["title"]
let favorite: Bool = row["favorite"]
let coordinate = CLLocationCoordinate2DMake(
row["latitude"],
row["longitude"])
let coordinate = CLLocationCoordinate2D(
latitude: row["latitude"],
longitude: row["longitude"])
print("Fetched", title, favorite, coordinate)
}
let poiCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM pointOfInterests")! // Int
let poiTitles = try String.fetchAll(db, "SELECT title FROM pointOfInterests") // [String]
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
let placeTitles = try String.fetchAll(db, sql: "SELECT title FROM place") // [String]
}
//: Insert and fetch records
struct PointOfInterest {
struct Place {
var id: Int64?
var title: String?
var favorite: Bool
@@ -71,7 +72,7 @@ struct PointOfInterest {
}
// Adopt FetchableRecord
extension PointOfInterest : FetchableRecord {
extension Place : FetchableRecord {
init(row: Row) {
id = row["id"]
title = row["title"]
@@ -83,12 +84,12 @@ extension PointOfInterest : FetchableRecord {
}
// Adopt TableRecord
extension PointOfInterest : TableRecord {
static let databaseTableName = "pointOfInterests"
extension Place : TableRecord {
static let databaseTableName = "place"
}
// Adopt MutablePersistableRecord
extension PointOfInterest : MutablePersistableRecord {
extension Place : MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["title"] = title
@@ -103,7 +104,7 @@ extension PointOfInterest : MutablePersistableRecord {
}
try dbQueue.inDatabase { db in
var berlin = PointOfInterest(
var berlin = Place(
id: nil,
title: "Berlin",
favorite: false,
@@ -116,7 +117,7 @@ try dbQueue.inDatabase { db in
try berlin.update(db)
// Fetch from SQL
let pois = try PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") // [PointOfInterest]
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
//: Avoid SQL with the query interface:
@@ -124,10 +125,10 @@ try dbQueue.inDatabase { db in
let title = Column("title")
let favorite = Column("favorite")
berlin = try PointOfInterest.filter(title == "Berlin").fetchOne(db)! // PointOfInterest
let paris = try PointOfInterest.fetchOne(db, key: 1) // PointOfInterest?
let favoritePois = try PointOfInterest // [PointOfInterest]
.filter(favorite)
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
let paris = try Place.fetchOne(db, key: 1) // Place?
let favoritePlaces = try Place // [Place]
.filter(favorite == true)
.order(title)
.fetchAll(db)
}
@@ -0,0 +1,84 @@
//: To run this playground:
//:
//: - Open GRDB.xcworkspace
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
//: - Build: menu Product > Build
//: - Select the playground in the Playgrounds Group
//: - Run the playground
import GRDB
// Create the databsae
let dbQueue = DatabaseQueue() // Memory database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
}
migrator.registerMigration("createPet") { db in
try db.create(table: "pet") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("ownerId", .integer).references("person", onDelete: .cascade)
}
}
try! migrator.migrate(dbQueue)
//
class TableChangeObserver : NSObject, TransactionObserver {
private var changedTableNames: Set<String> = []
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
func databaseDidChange(with event: DatabaseEvent) {
changedTableNames.insert(event.tableName)
}
func databaseDidCommit(_ db: Database) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
}
func databaseDidRollback(_ db: Database) {
changedTableNames = []
}
}
let observer = TableChangeObserver()
dbQueue.add(transactionObserver: observer)
//
print("-- Changes without transaction")
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
let arthurId = db.lastInsertedRowID
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
}
print("-- Rollbacked changes")
try dbQueue.inTransaction { db in
try db.execute(sql: "INSERT INTO person (name) VALUES ('Arthur')")
try db.execute(sql: "INSERT INTO person (name) VALUES ('Barbara')")
return .rollback
}
print("-- Changes wrapped in a transaction")
try dbQueue.write { db in
try db.execute(sql: "DELETE FROM person")
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
let arthurId = db.lastInsertedRowID
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
}
-5
View File
@@ -15,18 +15,13 @@ To release a new GRDB version:
- Update GRDB version number and release date in:
- Makefile
- CHANGELOG.md
- Documentation/CustomSQLiteBuilds.md
- GRDB.swift.podspec
- GRDBCipher.podspec
- GRDBPlus.podspec
- README.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- `pod trunk push --allow-warnings GRDBPlus.podspec`
- `pod trunk push --allow-warnings GRDBCipher.podspec`
- `make doc`, and update index.html in the `gh-pages` branch
- Update http://github.com/groue/WWDCCompanion
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
+454
View File
@@ -0,0 +1,454 @@
SQL Interpolation
=================
Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents commonplace challenges. For example, you want to make sure your queries don't break whenever the database schema changes as you ship new versions of your application. When you inject user values in the database, you have to use statement arguments, and it is easy to make a mistake in the process.
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
```swift
try db.execute(
sql: """
UPDATE student
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
registrationDate = ?, mainTeacherId = ?
WHERE id = ?
""",
arguments: [firstName, lastName, department, birthDate,
registrationDate, mainTeacherId])
```
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
- [Introduction]
- [SQLLiteral]
- [SQL Interpolation and the Query Interface]
- [SQL Interpolation and Record Protocols]
- [SQL Interpolation Reference]
## Introduction
**SQL Interpolation** lets you embed values in your SQL queries by wrapping them inside `\(` and `)`:
```swift
let name: String = ...
let id: Int64 = ...
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
SQL interpolation looks and feel just like regular [String interpolation]:
```swift
let name = "World"
print("Hello \(name)!") // prints "Hello World!"
```
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
```swift
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
let name = "O'Brien"
let id = 42
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
Under the hood, SQL interpolation generates a plain SQL string. It runs exactly as below:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
- For plain SQL strings, use the `sql` argument label:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
- For SQL interpolation, use the `literal` argument label:
```swift
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
## SQLLiteral
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
```
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
```swift
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a String
try db.execute(literal: query)
```
SQLLiteral can build your queries step by step, with regular operators and methods:
```swift
// +, +=, append
var query: SQLLiteral = "UPDATE player "
query += "SET name = \(name) "
query.append(literal: "WHERE id = \(id)")
// joined(), joined(separator:)
let components: [SQLLiteral] = [
"UPDATE player",
"SET name = \(name)",
"WHERE id = \(id)"
]
let query = components.joined(separator: " ")
```
Extract the plain SQL string from a literal:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
```swift
let query = SQLLiteral(
sql: "UPDATE player SET name = ? WHERE id = ?",
arguments: [name, id])
```
SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
## SQL Interpolation and the Query Interface
SQL Interpolation and SQLLiteral let you embed raw SQL snippets in [query interface requests].
For example:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let request = Player.filter(literal: "name = \("O'Brien")")
```
You can also build literal expressions from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
```swift
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
let createdAt = Column("createdAt")
let creationDay = SQLLiteral("DATE(\(createdAt))").sqlExpression
let request = Player.filter(creationDay == "2020-01-23")
```
Such literal expressions can be returned by Swift functions:
```swift
func date(_ value: SQLExpressible) -> SQLExpression {
SQLLiteral("DATE(\(value))").sqlExpression
}
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
let createdAt = Column("createdAt")
let request = Player.filter(date(createdAt) == "2020-01-23")
```
## SQL Interpolation and Record Protocols
The [record protocols] extend your application types with database abilities.
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names:
```swift
struct Player {
var id: Int64
var name: String
var score: Int?
}
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
"""
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
```
Let's breakdown each one of those methods.
- `deleteAllWithoutScore(_:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
}
```
Usage:
```swift
try dbQueue.write { db in
// DELETE FROM player WHERE score IS NULL
try Player.deleteAllWithoutScore(db)
}
```
`DELETE FROM \(self) ...` embeds the Player type itself. Since Player adopts the [TableRecord] protocol, this embeds `Player.databaseTableName` in the SQL query.
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
- `filter(id:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
}
```
Usage:
```swift
let player = try dbQueue.read { db in
// SELECT * player WHERE id = 42
try Player.filter(id: 42).fetchOne(db) // Player?
}
```
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. And it profits from SQL interpolation: this is why this method can simply return an "SQL literal"".
It embeds `\(self)` (the Player type which adopts the TableRecord protocol) and `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and `\(id)` (a [value]).
- `filter(ids:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
}
```
Usage:
```swift
let players = try dbQueue.read { db in
// SELECT * player WHERE id IN (1, 2, 3)
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
}
```
It embeds `\(ids)`, an array of ids. All [value] sequences are supported (arrays, sets, etc.) Empty sequences are supported as well, with both `IN` and `NOT IN` SQL operators.
- `maximumScore()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
}
```
Usage:
```swift
let maximumScore = try dbQueue.read { db in
// SELECT MAX(score) FROM player
try Player.maximumScore().fetchOne(db) // Int?
}
```
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
- `leaders()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
"""
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
}
```
Usage:
```swift
let leaders = try dbQueue.read { db in
// SELECT * FROM player
// WHERE score = (SELECT MAX(score) FROM player)
try Player.leaders().fetchAll(db) // [Player]
}
```
This request embeds `\(maximumScore())`, the `SQLRequest<Int>` returned by the `maximumScore` method. After values, coding keys, and types that adopt the TableRecord protocol, this ends our quick tour of things you can embed between `\(` and `)`. Check out the [SQL Interpolation Reference] for the full list of supported interpolations.
- `complexRequest()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
```
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be expressed in a single "SQL literal".
## SQL Interpolation Reference
This chapter lists all kinds of supported interpolations.
- Types adopting the [TableRecord] protocol:
```swift
// SELECT * FROM player
extension Player: TableRecord { }
"SELECT * FROM \(Player.self)"
// INSERT INTO player ...
let player: Player = ...
"INSERT INTO \(tableOf: player) ..."
```
- [Expressions] and [values]:
```swift
// SELECT name FROM player
"SELECT \(Column("name")) FROM player"
// SELECT (score + 100) AS points FROM player
let bonus = 100
"SELECT \(Column("score") + bonus) AS points FROM player"
// SELECT (score + 100) AS points FROM player
"SELECT (score + \(bonus)) AS points FROM player"
```
- Coding keys:
```swift
// SELECT name FROM player
"SELECT \(CodingKeys.name) FROM player"
```
- Sequences:
```swift
// SELECT * FROM player WHERE id IN (1, 2, 3)
let ids = [1, 2, 3]
"SELECT * FROM player WHERE id IN \(ids)"
```
- Orderings:
```swift
// SELECT * FROM player ORDER BY name DESC
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
```
- SQLRequest:
```swift
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = \(subQuery)"
```
- SQLLiteral:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let condition: SQLLiteral = "name = \("O'Brien")"
"SELECT * FROM player WHERE \(literal: condition)"
```
- Plain SQL strings and eventual arguments:
```swift
// SELECT * FROM player
"SELECT * FROM \(sql: "player")"
// SELECT * FROM player WHERE name = 'O''Brien'
"SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
```
[Introduction]: #introduction
[SQLLiteral]: #sqlliteral
[SQL Interpolation and the Query Interface]: #sql-interpolation-and-the-query-interface
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
[SQL Interpolation Reference]: #sql-interpolation-reference
[String interpolation]: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292
[SQL injection]: ../README.md#avoiding-sql-injection
[record protocols]: ../README.md#record-protocols-overview
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[TableRecord]: ../README.md#tablerecord-protocol
[Decodable]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[value]: ../README.md#values
[values]: ../README.md#values
[request types]: ../README.md#custom-requests
[row]: ../README.md#row-queries
[record]: ../README.md#records
[Expressions]: ../README.md#expressions
[welcomed]: ../README.md#sqlite-api
[query interface requests]: ../README.md#requests
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
+70 -51
View File
@@ -69,7 +69,7 @@ By adopting the [FetchableRecord] protocol, places can be loaded from SQL reques
```swift
extension Place: FetchableRecord { ... }
let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place]
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
```
Add the [TableRecord] protocol, and SQL requests are generated for you:
@@ -90,6 +90,8 @@ For your convenience, those record protocols can be derived from the [Decodable
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
### Allow database records to cross threads
@@ -113,25 +115,41 @@ let player = Player(name: "arthur", score: 1000)
let players = try Player.fetchAll(db)
```
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and react accordingly.
There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change, or [FetchedRecordsController], which animates table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
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
Player.all().rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Players have changed")
})
/// An observation of [Player]
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
// Vanilla GRDB
let cancellable = observation.start(in: dbQueue,
onError: { error in ... },
onChange: { (players: [Player]) in print("Fresh players") })
// GRDBCombine
let cancellable = observation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players") })
// RxGRDB
let disposable = observation.rx.observe(in: dbQueue).subscribe(
onNext: { (players: [Player]) in print("Fresh playerss") },
onError: { error in ... })
```
No matter which observation technique you use, you have common guarantees:
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions.
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). GRDB makes sure notifications happen in the same order as database transactions.
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
See [Database Observation](../README.md#database-changes-observation) for further information.
### Non-blocking database reads
@@ -170,16 +188,23 @@ We can see that the threat of conflicts is *always* left to the application. Cor
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
For further information about GRDB concurrency, check its detailed [Concurrency Guide].
For detailed information about GRDB concurrency, check the [Concurrency Guide].
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
### Never pay for using raw SQL
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
GRDB [query interface] and [associations] can generate SQL for you:
GRDB [records], [query interface] and [associations] can generate SQL for you:
```swift
// UPDATE player SET score = 950 WHERE id = 42
try player.updateChanges {
$0.score += 10
}
// SELECT * FROM player ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
@@ -202,37 +227,51 @@ let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
But you can always switch to SQL when you want to:
```swift
let bestPlayers: [Player] = try Player.fetchAll(db, """
try db.execute(
sql: "UPDATE player SET score = ? WHERE id = ?",
arguments: [950, 42])
let bestPlayers: [Player] = try Player.fetchAll(db, sql: """
SELECT * FROM player ORDER BY score DESC LIMIT 10
""")
let maximumScore: Int? = try Int.fetchOne(db, """
let maximumScore: Int? = try Int.fetchOne(db, sql: """
SELECT MAX(score) FROM player
""")
```
Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)):
With Swift 5, you can profit from **SQL interpolation**. It lets you build SQL queries from natural looking strings, but without any risk of syntax error or [SQL injection](https://xkcd.com/327/):
```swift
let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
SELECT book.*, author.*
FROM book
LEFT JOIN author ON author.id = book.authorId
""")
.adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
db.columns(in: "book").count,
db.columns(in: "author").count])
return ScopeAdapter([
"book": adapters[0],
"author": adapters[1]])
try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)")
extension Player {
static func filter(name: String) -> SQLRequest<Player> {
"SELECT * FROM player WHERE name = \(name)"
}
}
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
```
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation], or the companion libraries [GRDBCombine] and [RxGRDB]:
```swift
let playerObservation = ValueObservation.tracking { db in
try Player.filter(name: "Arthur O'Brien").fetchOne(db)
}
// Observe the SQL request with GRDBCombine
let cancellable = playerObservation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (player: Player?) in print("Player has changed") })
```
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
```swift
let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player")
// As close to SQLite metal as possible
let rows = try Row.fetchCursor(db, sql: "SELECT id, name, score FROM player")
while let row = try rows.next() {
let id: Int64 = row[0]
let name: String = row[1]
@@ -240,28 +279,6 @@ while let row = try rows.next() {
}
```
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests):
```swift
extension Player {
static func customRequest(...) -> SQLRequest<Player> {
return SQLRequest<Player>("SELECT ...", arguments: ...)
}
}
let players = try Player.customRequest(...).fetchAll(db)
```
Those custom requests are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.customRequest(...).rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Players have changed")
})
```
---
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
@@ -276,7 +293,6 @@ Happy GRDB! :gift:
[Diesel]: http://diesel.rs
[FCModel]: https://github.com/marcoarment/FCModel
[ValueObservation]: ../README.md#valueobservation
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
[Fluent]: https://github.com/vapor/fluent
[FMDB]: http://github.com/ccgus/fmdb
[GRDB]: http://github.com/groue/GRDB.swift
@@ -286,6 +302,8 @@ Happy GRDB! :gift:
[FetchableRecord]: ../README.md#records
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[RxSwift]: https://github.com/ReactiveX/RxSwift
[GRDBCombine]: http://github.com/groue/GRDBCombine
[Combine]: https://developer.apple.com/documentation/combine
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
[StORM]: https://www.perfect.org/docs/StORM.html
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
@@ -294,3 +312,4 @@ Happy GRDB! :gift:
[query interface]: ../README.md#the-query-interface
[associations]: AssociationsBasics.md
[Codable records]: ../README.md#codable-records
[records]: ../README.md#records
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

+22 -7
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '3.6.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,12 +9,27 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.9'
s.swift_versions = ['5.2']
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.10'
s.watchos.deployment_target = '2.0'
s.tvos.deployment_target = '9.0'
s.default_subspec = 'standard'
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
s.module_map = 'Support/module.modulemap'
s.framework = 'Foundation'
s.library = 'sqlite3'
s.subspec 'standard' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
ss.framework = 'Foundation'
ss.library = 'sqlite3'
end
s.subspec 'SQLCipher' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
ss.framework = 'Foundation'
ss.dependency 'SQLCipher', '>= 3.4.0'
ss.xcconfig = {
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER -D SQLITE_ENABLE_FTS5',
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER -DSQLITE_ENABLE_FTS5',
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1 GRDBCIPHER=1 SQLITE_ENABLE_FTS5=1'
}
end
end
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -40,8 +40,17 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
codeCoverageEnabled = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO">
@@ -77,17 +86,6 @@
</SkippedTests>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
@@ -108,8 +106,6 @@
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -29,8 +29,6 @@
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
@@ -51,8 +49,6 @@
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,8 +26,17 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
codeCoverageEnabled = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO">
@@ -40,17 +49,6 @@
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
@@ -71,8 +69,6 @@
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0910"
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,10 +14,10 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
BuildableName = "GRDBiOS.app"
BlueprintName = "GRDBiOS"
ReferencedContainer = "container:GRDBiOS.xcodeproj">
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -26,45 +26,49 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
BuildableName = "GRDBiOS.app"
BlueprintName = "GRDBiOS"
ReferencedContainer = "container:GRDBiOS.xcodeproj">
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
BuildableName = "GRDBtvOSTests.xctest"
BlueprintName = "GRDBtvOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
BuildableName = "GRDBiOS.app"
BlueprintName = "GRDBiOS"
ReferencedContainer = "container:GRDBiOS.xcodeproj">
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</MacroExpansion>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -72,16 +76,15 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
BuildableName = "GRDBiOS.app"
BlueprintName = "GRDBiOS"
ReferencedContainer = "container:GRDBiOS.xcodeproj">
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
+2 -8
View File
@@ -2,7 +2,7 @@
<Workspace
version = "1.0">
<Group
location = "group:Playgrounds"
location = "group:Documentation/Playgrounds"
name = "Playgrounds">
<FileRef
location = "group:Tour.playground">
@@ -10,9 +10,6 @@
<FileRef
location = "group:JSONSynchronization.playground">
</FileRef>
<FileRef
location = "group:Record.playground">
</FileRef>
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
@@ -50,13 +47,10 @@
<FileRef
location = "group:GRDBCustom.xcodeproj">
</FileRef>
<FileRef
location = "group:GRDBCipher.xcodeproj">
</FileRef>
<FileRef
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
</FileRef>
<FileRef
location = "group:DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
location = "group:Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
</FileRef>
</Workspace>
+61 -27
View File
@@ -1,10 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Configuration for a DatabaseQueue or DatabasePool.
public struct Configuration {
@@ -73,16 +68,54 @@ public struct Configuration {
/// Default: nil
public var trace: TraceFunction?
// MARK: - Encryption
#if SQLITE_HAS_CODEC
/// The passphrase for encrypted database.
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
/// string as a string literal if it does not match any valid identifier.
///
/// Default: nil
public var passphrase: String?
#endif
/// For example:
///
/// // Error: no such column: foo
/// let name = try String.fetchOne(db, sql: """
/// SELECT "foo" FROM "player"
/// """)
///
/// When true, or before version 3.29.0, such strings are interpreted as
/// string literals, as in the example below. This is a well known SQLite
/// [misfeature](https://sqlite.org/quirks.html#dblquote).
///
/// // Success: "foo"
/// let name = try String.fetchOne(db, sql: """
/// SELECT "foo" FROM "player"
/// """)
///
/// - Recommended value: false
/// - Default value: false
public var acceptsDoubleQuotedStringLiterals = false
/// When true, the `Database.suspendNotification` and
/// `Database.resumeNotification` suspend and resume the database. Database
/// suspension helps avoiding the [`0xdead10cc`
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
///
/// During suspension, all database accesses but reads in WAL mode may throw
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
/// check for those error codes with the
/// `DatabaseError.isInterruptionError` property.
///
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var observesSuspensionNotifications = false
// MARK: - Managing SQLite Connections
/// A function that is run when an SQLite connection is opened, before the
/// connection is made available for database access methods.
///
/// For example:
///
/// var config = Configuration()
/// config.prepareDatabase = { db in
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
/// }
public var prepareDatabase: ((Database) throws -> Void)?
// MARK: - Transactions
@@ -141,10 +174,18 @@ 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 the work performed by the database.
/// The target queue for all database accesses.
///
/// When you use a database pool, make sure the queue is concurrent. If
/// it is serial, no concurrent database access can happen, and you may
/// experience deadlocks.
///
/// If the queue is nil, all database accesses happen in unspecified
/// dispatch queues whose quality of service and label are determined by the
/// `qos` and `label` Configuration properties.
///
/// Default: nil
public var targetQueue: DispatchQueue? = nil
@@ -152,21 +193,14 @@ 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
var threadingMode: Database.ThreadingMode = .`default`
var SQLiteConnectionDidOpen: (() -> ())?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
var SQLiteConnectionDidClose: (() -> ())?
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
var SQLiteOpenFlags: Int32 {
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
return threadingMode.SQLiteOpenFlags | readWriteFlags
+51 -44
View File
@@ -14,8 +14,9 @@
extension Array {
/// Creates an array containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let strings = try Array(cursor) // ["foo", "bar"]
@inlinable
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
@@ -28,15 +29,18 @@ extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>> {
return AnyCursor(self).flatMap(transform)
public func flatMap<SegmentOfResult: Cursor>(
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
{
AnyCursor(self).flatMap(transform)
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let strings = try Set(cursor) // ["foo"]
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
@@ -75,7 +79,7 @@ extension Set {
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
/// `suffix`.
public protocol Cursor : class {
public protocol Cursor: AnyObject {
/// The type of element traversed by the cursor.
associatedtype Element
@@ -88,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
@@ -111,7 +115,7 @@ extension Cursor {
/// Returns a cursor of pairs (n, x), where n represents a consecutive
/// integer starting at zero, and x represents an element of the cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
@@ -119,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
@@ -140,13 +144,10 @@ extension Cursor {
/// Returns a cursor over the concatenated non-nil results of mapping
/// transform over this cursor.
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
return map(transform).filter { $0 != nil }.map { $0! }
}
@available(*, deprecated, renamed: "compactMap")
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
return compactMap(transform)
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{
map(transform).filter { $0 != nil }.map { $0! }
}
/// Returns a cursor that skips any initial elements that satisfy
@@ -157,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
@@ -177,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.
@@ -192,9 +193,9 @@ 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
/// elements.
///
@@ -242,19 +243,25 @@ 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
/// over self.
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>> {
return flatMap { try AnyCursor(transform($0)) }
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
where SegmentOfResult: Sequence
{
flatMap { try AnyCursor(transform($0)) }
}
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
return map(transform).joined()
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
where SegmentOfResult: Cursor
{
map(transform).joined()
}
/// Calls the given closure on each element in the cursor.
@@ -267,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
@@ -327,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
@@ -338,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
@@ -441,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.
@@ -453,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: <)
}
}
@@ -462,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)
}
}
@@ -471,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 }
}
}
@@ -507,7 +514,7 @@ extension Cursor where Element: StringProtocol {
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public final class AnyCursor<Element> : Cursor {
public final class AnyCursor<Element>: Cursor {
private let element: () throws -> Element?
/// Creates a cursor that wraps a base cursor but whose type depends only on
@@ -538,16 +545,16 @@ public final class AnyCursor<Element> : Cursor {
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
return try element()
try element()
}
}
/// :nodoc:
public final class DropFirstCursor<Base: Cursor> : Cursor {
public final class DropFirstCursor<Base: Cursor>: Cursor {
private let base: Base
private let limit: Int
private var dropped: Int = 0
init(_ base: Base, limit: Int) {
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
self.base = base
@@ -570,7 +577,7 @@ public final class DropFirstCursor<Base: Cursor> : Cursor {
/// consecutive elements of some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class DropWhileCursor<Base: Cursor> : Cursor {
public final class DropWhileCursor<Base: Cursor>: Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
@@ -600,7 +607,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
/// on a cursor:
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
@@ -609,7 +616,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
/// // Prints: "1: bar"
///
/// :nodoc:
public final class EnumeratedCursor<Base: Cursor> : Cursor {
public final class EnumeratedCursor<Base: Cursor>: Cursor {
private let base: Base
private var index: Int
@@ -632,7 +639,7 @@ public final class EnumeratedCursor<Base: Cursor> : Cursor {
/// also satisfy a given predicate.
///
/// :nodoc:
public final class FilterCursor<Base: Cursor> : Cursor {
public final class FilterCursor<Base: Cursor>: Cursor {
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
@@ -660,7 +667,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
///
/// :nodoc:
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
private let base: Base
private var inner: Base.Element?
@@ -690,7 +697,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
/// See Cursor.map(_:)
///
/// :nodoc:
public final class MapCursor<Base: Cursor, Element> : Cursor {
public final class MapCursor<Base: Cursor, Element>: Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
@@ -712,7 +719,7 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
/// `Base` cursor.
///
/// :nodoc:
public final class PrefixCursor<Base: Cursor> : Cursor {
public final class PrefixCursor<Base: Cursor>: Cursor {
private let base: Base
private let maxLength: Int
private var taken = 0
@@ -739,7 +746,7 @@ public final class PrefixCursor<Base: Cursor> : Cursor {
/// some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
+62 -51
View File
@@ -1,13 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Schema
/// Clears the database schema cache.
///
/// You may need to clear the cache manually if the database schema is
@@ -26,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.
@@ -48,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 {
@@ -69,7 +63,7 @@ extension Database {
.names(ofType: type)
.contains { $0.lowercased() == name }
}
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
@@ -150,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)
@@ -171,17 +165,17 @@ extension Database {
}
let indexes = try Row
.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.map { row -> IndexInfo in
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row
.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { row -> (Int, String) in
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.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)
@@ -201,8 +195,13 @@ extension Database {
/// True if a sequence of columns uniquely identifies a row, that is to say
/// if the columns are the primary key, or if there is a unique index on them.
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
public func table<T: Sequence>(
_ tableName: String,
hasUniqueKey columns: T)
throws -> Bool
where T.Iterator.Element == String
{
try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
/// The foreign keys defined on table named `tableName`.
@@ -211,9 +210,11 @@ extension Database {
return foreignKeys
}
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var rawForeignKeys: [(
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
let id: Int = row[0]
let seq: Int = row[1]
@@ -222,9 +223,13 @@ extension Database {
let destination: String? = row[4]
if previousId == id {
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
rawForeignKeys[rawForeignKeys.count - 1]
.mapping
.append((origin: origin, destination: destination, seq: seq))
} else {
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
rawForeignKeys.append((
destinationTable: table,
mapping: [(origin: origin, destination: destination, seq: seq)]))
previousId = id
}
}
@@ -279,7 +284,7 @@ extension Database {
}
extension Database {
/// The columns in the table named `tableName`
///
/// - throws: A DatabaseError if table does not exist.
@@ -311,7 +316,7 @@ extension Database {
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
@@ -320,9 +325,9 @@ extension Database {
}
}
let columns = try ColumnInfo
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
if columns.isEmpty {
throw DatabaseError(message: "no such table: \(tableName)")
}
@@ -333,14 +338,31 @@ extension Database {
/// If there exists a unique key on columns, return the columns
/// ordered as the matching index (or primay key). Case of returned columns
/// is not guaranteed.
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
func columnsForUniqueKey<T: Sequence>(
_ columns: T,
in tableName: String)
throws -> [String]?
where T.Iterator.Element == String
{
// Check primaryKey first, so that we fail early if the table does not exist
let lowercasedColumns = Set(columns.map { $0.lowercased() })
// Assume "rowid" is a primary key
if lowercasedColumns == ["rowid"] {
return ["rowid"]
}
let primaryKey = try self.primaryKey(tableName)
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
return primaryKey.columns
}
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
// There is an explicit unique index on the columns
// Is there is an explicit unique index on the columns?
let indexes = try self.indexes(on: tableName)
let matchingIndex = indexes.first { index in
index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns
}
if let index = matchingIndex {
return index.columns
}
return nil
@@ -364,7 +386,7 @@ extension Database {
/// 2 score INTEGER 0 NULL 0
///
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo : FetchableRecord {
public struct ColumnInfo: FetchableRecord {
let cid: Int
/// The column name
@@ -386,7 +408,7 @@ public struct ColumnInfo : FetchableRecord {
///
/// For example:
///
/// try db.execute("""
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY,
/// name TEXT DEFAULT 'Anonymous',
@@ -501,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 {
@@ -559,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)
}
}
@@ -579,7 +601,7 @@ struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
init(_ db: Database) throws {
objects = try Set(SchemaObject.fetchCursor(db, """
objects = try Set(SchemaObject.fetchCursor(db, sql: """
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
UNION \
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
@@ -588,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)
}
@@ -597,7 +619,7 @@ struct SchemaInfo: Equatable {
/// Returns the canonical name of the object:
///
/// try db.execute("CREATE TABLE FooBar (...)")
/// try db.execute(sql: "CREATE TABLE FooBar (...)")
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
@@ -610,16 +632,5 @@ struct SchemaInfo: Equatable {
var tbl_name: String?
var sql: String?
var isTemporary: Bool
#if !swift(>=4.2)
var hashValue: Int {
var hash = type.hashValue
hash ^= name.hashValue
hash ^= (tbl_name?.hashValue ?? 0)
hash ^= (sql?.hashValue ?? 0)
hash ^= isTemporary.hashValue
return hash
}
#endif
}
}
+190 -94
View File
@@ -6,20 +6,20 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - 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, prepFlags: 0)
public func makeSelectStatement(sql: String) throws -> SelectStatement {
try makeSelectStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -28,13 +28,13 @@ extension Database {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.cachedSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -44,31 +44,31 @@ extension Database {
/// - parameter sql: An SQL query.
/// - 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)
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
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)
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
try internalStatementCache.selectStatement(sql)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - 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, prepFlags: 0)
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
try makeUpdateStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -77,13 +77,13 @@ extension Database {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.cachedUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -93,107 +93,185 @@ extension Database {
/// - parameter sql: An SQL query.
/// - 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)
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
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)
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
try internalStatementCache.updateStatement(sql)
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO player (name) VALUES (:name)",
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute("""
/// try db.execute(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(literal: SQLLiteral(
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"]))
///
/// try db.execute(literal: SQLLiteral(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// try db.execute(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"));
/// INSERT INTO player (name) VALUES (\("Barbara"));
/// INSERT INTO player (name) VALUES (\("O'Brien"));
/// """)
///
/// This method may throw a DatabaseError.
///
/// - parameter sqlLiteral: An SQLLiteral.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(literal sqlLiteral: SQLLiteral) throws {
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
// It adds support for arguments, and the tricky part is to consume
// arguments as statements are executed.
//
// Here we build two functions:
// - consumeArguments returns arguments for a statement
// - validateRemainingArguments validates the remaining arguments, after
// all statements have been executed, in the same way
// as Statement.validate(arguments:)
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
//
// And before we return, we'll check that all arguments were consumed.
var arguments = arguments ?? StatementArguments()
var context = SQLGenerationContext.sqlLiteralContext
let sql = sqlLiteral.sql(&context)
var arguments = context.arguments
let initialValuesCount = arguments.values.count
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
return StatementArguments(bindings)
}
let validateRemainingArguments = {
if !arguments.values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
// Iterate SQL statements
let sqlCodeUnits = sql.utf8CString
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
let sqlEnd = sqlStart + sqlCodeUnits.count
// Build a C string (SQLite wants that), and execute SQL statements one
// after the other.
try sql.utf8CString.withUnsafeBufferPointer { buffer in
guard let sqlStart = buffer.baseAddress else { return }
let sqlEnd = sqlStart + buffer.count // past \0
var statementStart = sqlStart
while statementStart < sqlEnd - 1 {
while statementStart < sqlEnd {
var statementEnd: UnsafePointer<Int8>? = nil
let nextStatement: UpdateStatement?
// Compile
do {
let statement: UpdateStatement
// Compile
do {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
statement = try UpdateStatement(
let authorizer = StatementCompilationAuthorizer()
nextStatement = try withAuthorizer(authorizer) {
try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
authorizer: authorizer)
}
// Execute
let arguments = try consumeArguments(statement)
statement.unsafeSetArguments(arguments)
try statement.execute()
// Next
statementStart = statementEnd!
} catch is EmptyStatementError {
// End
}
guard let statement = nextStatement else {
// End of SQL string
break
}
// Extract statement arguments
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
// unsafe is OK because we just extracted the correct number of arguments
statement.setUncheckedArguments(StatementArguments(bindings))
// Execute
try statement.execute()
// Next
statementStart = statementEnd!
}
}
// Check that all arguments were consumed: it is a programmer error to
// provide arguments that do not match the statement.
if arguments.values.isEmpty == false {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
}
extension Database {
func executeUpdateStatement(_ statement: UpdateStatement) throws {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
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
withAuthorizer(authorizer) {
while true {
code = sqlite3_step(sqliteStatement)
if code == SQLITE_ROW {
// Statement returns a row, but the user ignores the
// content of this row:
//
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
} else {
break
}
}
}
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
try! validateRemainingArguments() // throws if there are remaining arguments.
}
}
extension Database {
func updateStatementWillExecute(_ statement: UpdateStatement) {
observationBroker.updateStatementWillExecute(statement)
// Statement has been fully executed, and authorizer has been reset.
// We can now move on further tasks.
if code == SQLITE_DONE {
try updateStatementDidExecute(statement)
} else {
assert(code != SQLITE_ROW)
try updateStatementDidFail(statement)
throw DatabaseError(
resultCode: code,
message: lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
}
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
@@ -201,7 +279,7 @@ extension Database {
try observationBroker.updateStatementDidExecute(statement)
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
@@ -213,6 +291,18 @@ extension Database {
try observationBroker.updateStatementDidFail(statement)
}
@inline(__always)
func selectStatementWillExecute(_ statement: SelectStatement) throws {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.selectedRegion)
}
}
func selectStatementDidFail(_ statement: SelectStatement) {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
@@ -248,17 +338,22 @@ struct StatementCache {
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
//
// TODO: use SQLITE_PREPARE_PERSISTENT if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeSelectStatement(sql)
let statement: SelectStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeSelectStatement(sql: sql)
}
#endif
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
@@ -273,12 +368,17 @@ struct StatementCache {
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
//
// TODO: use SQLITE_PREPARE_PERSISTENT if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeUpdateStatement(sql)
let statement: UpdateStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeUpdateStatement(sql: sql)
}
#endif
updateStatements[sql] = statement
return statement
@@ -290,14 +390,10 @@ struct StatementCache {
}
mutating func remove(_ statement: SelectStatement) {
if let index = selectStatements.index(where: { $0.1 === statement }) {
selectStatements.remove(at: index)
}
selectStatements.removeFirst { $0.value === statement }
}
mutating func remove(_ statement: UpdateStatement) {
if let index = updateStatements.index(where: { $0.1 === statement }) {
updateStatements.remove(at: index)
}
updateStatements.removeFirst { $0.value === statement }
}
}
+508 -253
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 610 files, more files were not shown because too many files have changed in this diff. Show more